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
a5f6f03187e63779f7080cc89d6d78432b19665b
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/data/rbtree/insert.lean
8cbedb147c3c5ca6d4dce5819e126b26562d10a5
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
33,618
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree.find universes u v local attribute [simp] rbnode.lift namespace rbnode variables {α : Type u} open color @[simp] lemma balance1_eq₁ (l : rbnode α) (x r₁ y r₂ v t) : balance1 (red_node l x r₁) y r₂ v t = red_node (black_node l x r₁) y (black_node r₂ v t) := begin cases r₂; refl end @[simp] lemma balance1_eq₂ (l₁ : rbnode α) (y l₂ x r v t) : get_color l₁ ≠ red → balance1 l₁ y (red_node l₂ x r) v t = red_node (black_node l₁ y l₂) x (black_node r v t) := begin cases l₁; simp [get_color, balance1, false_implies_iff] end @[simp] lemma balance1_eq₃ (l : rbnode α) (y r v t) : get_color l ≠ red → get_color r ≠ red → balance1 l y r v t = black_node (red_node l y r) v t := begin cases l; cases r; simp [get_color, balance1, false_implies_iff] end @[simp] lemma balance2_eq₁ (l : rbnode α) (x₁ r₁ y r₂ v t) : balance2 (red_node l x₁ r₁) y r₂ v t = red_node (black_node t v l) x₁ (black_node r₁ y r₂) := by cases r₂; refl @[simp] lemma balance2_eq₂ (l₁ : rbnode α) (y l₂ x₂ r₂ v t) : get_color l₁ ≠ red → balance2 l₁ y (red_node l₂ x₂ r₂) v t = red_node (black_node t v l₁) y (black_node l₂ x₂ r₂) := begin cases l₁; simp [get_color, balance2, false_implies_iff] end @[simp] lemma balance2_eq₃ (l : rbnode α) (y r v t) : get_color l ≠ red → get_color r ≠ red → balance2 l y r v t = black_node t v (red_node l y r) := begin cases l; cases r; simp [get_color, balance2, false_implies_iff] end /- We can use the same induction principle for balance1 and balance2 -/ lemma balance.cases {p : rbnode α → α → rbnode α → Prop} (l y r) (red_left : ∀ l x r₁ y r₂, p (red_node l x r₁) y r₂) (red_right : ∀ l₁ y l₂ x r, get_color l₁ ≠ red → p l₁ y (red_node l₂ x r)) (other : ∀ l y r, get_color l ≠ red → get_color r ≠ red → p l y r) : p l y r := begin cases l; cases r, any_goals { apply red_left }, any_goals { apply red_right; simp [get_color]; contradiction; done }, any_goals { apply other; simp [get_color]; contradiction; done }, end lemma balance1_ne_leaf (l : rbnode α) (x r v t) : balance1 l x r v t ≠ leaf := by apply balance.cases l x r; intros; simp [*]; contradiction lemma balance1_node_ne_leaf {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance1_node s a t ≠ leaf := begin intro h, cases s, { contradiction }, all_goals { simp [balance1_node], apply balance1_ne_leaf } end lemma balance2_ne_leaf (l : rbnode α) (x r v t) : balance2 l x r v t ≠ leaf := by apply balance.cases l x r; intros; simp [*]; contradiction lemma balance2_node_ne_leaf {s : rbnode α} (a : α) (t : rbnode α) : s ≠ leaf → balance2_node s a t ≠ leaf := begin intro h, cases s, { contradiction }, all_goals { simp [balance2_node], apply balance2_ne_leaf } end variables (lt : α → α → Prop) [decidable_rel lt] @[elab_as_eliminator] lemma ins.induction {p : rbnode α → Prop} (t x) (is_leaf : p leaf) (is_red_lt : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (ih : p a), p (red_node a y b)) (is_red_eq : ∀ a y b (hc : cmp_using lt x y = ordering.eq), p (red_node a y b)) (is_red_gt : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (ih : p b), p (red_node a y b)) (is_black_lt_red : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (hr : get_color a = red) (ih : p a), p (black_node a y b)) (is_black_lt_not_red : ∀ a y b (hc : cmp_using lt x y = ordering.lt) (hnr : get_color a ≠ red) (ih : p a), p (black_node a y b)) (is_black_eq : ∀ a y b (hc : cmp_using lt x y = ordering.eq), p (black_node a y b)) (is_black_gt_red : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (hr : get_color b = red) (ih : p b), p (black_node a y b)) (is_black_gt_not_red : ∀ a y b (hc : cmp_using lt x y = ordering.gt) (hnr : get_color b ≠ red) (ih : p b), p (black_node a y b)) : p t := begin induction t, case leaf { apply is_leaf }, case red_node : a y b { cases h : cmp_using lt x y, case ordering.lt { apply is_red_lt; assumption }, case ordering.eq { apply is_red_eq; assumption }, case ordering.gt { apply is_red_gt; assumption }, }, case black_node : a y b { cases h : cmp_using lt x y, case ordering.lt { by_cases get_color a = red, { apply is_black_lt_red; assumption }, { apply is_black_lt_not_red; assumption }, }, case ordering.eq { apply is_black_eq; assumption }, case ordering.gt { by_cases get_color b = red, { apply is_black_gt_red; assumption }, { apply is_black_gt_not_red; assumption }, } } end lemma is_searchable_balance1 {l y r v t lo hi} : is_searchable lt l lo (some y) → is_searchable lt r (some y) (some v) → is_searchable lt t (some v) hi → is_searchable lt (balance1 l y r v t) lo hi := by apply balance.cases l y r; intros; simp [*]; is_searchable_tactic lemma is_searchable_balance1_node {t} [is_trans α lt] : ∀ {y s lo hi}, is_searchable lt t lo (some y) → is_searchable lt s (some y) hi → is_searchable lt (balance1_node t y s) lo hi := begin cases t; simp!; intros; is_searchable_tactic, { cases lo, { apply is_searchable_none_low_of_is_searchable_some_low, assumption }, { simp at *, apply is_searchable_some_low_of_is_searchable_of_lt; assumption } }, all_goals { apply is_searchable_balance1; assumption } end lemma is_searchable_balance2 {l y r v t lo hi} : is_searchable lt t lo (some v) → is_searchable lt l (some v) (some y) → is_searchable lt r (some y) hi → is_searchable lt (balance2 l y r v t) lo hi := by apply balance.cases l y r; intros; simp [*]; is_searchable_tactic lemma is_searchable_balance2_node {t} [is_trans α lt] : ∀ {y s lo hi}, is_searchable lt s lo (some y) → is_searchable lt t (some y) hi → is_searchable lt (balance2_node t y s) lo hi := begin induction t; simp!; intros; is_searchable_tactic, { cases hi, { apply is_searchable_none_high_of_is_searchable_some_high, assumption }, { simp at *, apply is_searchable_some_high_of_is_searchable_of_lt, assumption' } }, all_goals { apply is_searchable_balance2, assumption' } end lemma is_searchable_ins {t x} [is_strict_weak_order α lt] : ∀ {lo hi} (h : is_searchable lt t lo hi), lift lt lo (some x) → lift lt (some x) hi → is_searchable lt (ins lt t x) lo hi := begin with_cases { apply ins.induction lt t x; intros; simp! [*] at * {eta := ff}; is_searchable_tactic }, case is_red_lt hs₁ { apply ih h_hs₁, assumption, simp [*] }, case is_red_eq hs₁ { apply is_searchable_of_is_searchable_of_incomp hc, assumption }, case is_red_eq hs₂ { apply is_searchable_of_incomp_of_is_searchable hc, assumption }, case is_red_gt hs₂ { apply ih h_hs₂, cases hi; simp [*], assumption }, case is_black_lt_red { apply is_searchable_balance1_node, apply ih h_hs₁, assumption, simp [*], assumption }, case is_black_lt_not_red hs₁ { apply ih h_hs₁, assumption, simp [*] }, case is_black_eq hs₁ { apply is_searchable_of_is_searchable_of_incomp hc, assumption }, case is_black_eq hs₂ { apply is_searchable_of_incomp_of_is_searchable hc, assumption }, case is_black_gt_red { apply is_searchable_balance2_node, assumption, apply ih h_hs₂, simp [*], assumption }, case is_black_gt_not_red hs₂ { apply ih h_hs₂, assumption, simp [*] } end lemma is_searchable_mk_insert_result {c t} : is_searchable lt t none none → is_searchable lt (mk_insert_result c t) none none := begin cases c; cases t; simp [mk_insert_result], any_goals { exact id }, { intro h, is_searchable_tactic } end lemma is_searchable_insert {t x} [is_strict_weak_order α lt] : is_searchable lt t none none → is_searchable lt (insert lt t x) none none := begin intro h, simp [insert], apply is_searchable_mk_insert_result, apply is_searchable_ins; { assumption <|> simp } end end rbnode namespace rbnode section membership_lemmas parameters {α : Type u} (lt : α → α → Prop) [decidable_rel lt] local attribute [simp] mem balance1_node balance2_node local infix `∈` := mem lt lemma mem_balance1_node_of_mem_left {x s} (v) (t : rbnode α) : x ∈ s → x ∈ balance1_node s v t := begin cases s; simp [false_implies_iff], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp at *; blast_disjs; simp [*] } end lemma mem_balance2_node_of_mem_left {x s} (v) (t : rbnode α) : x ∈ s → x ∈ balance2_node s v t := begin cases s; simp [false_implies_iff], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp at *; blast_disjs; simp [*] } end lemma mem_balance1_node_of_mem_right {x t} (v) (s : rbnode α) : x ∈ t → x ∈ balance1_node s v t := begin intros, cases s; simp [*], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance2_node_of_mem_right {x t} (v) (s : rbnode α) : x ∈ t → x ∈ balance2_node s v t := begin intros, cases s; simp [*], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance1_node_of_incomp {x v} (s t) : (¬ lt x v ∧ ¬ lt v x) → s ≠ leaf → x ∈ balance1_node s v t := begin intros, cases s; simp, { contradiction }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma mem_balance2_node_of_incomp {x v} (s t) : (¬ lt v x ∧ ¬ lt x v) → s ≠ leaf → x ∈ balance2_node s v t := begin intros, cases s; simp, { contradiction }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] } end lemma ins_ne_leaf (t : rbnode α) (x : α) : t.ins lt x ≠ leaf := begin apply ins.induction lt t x, any_goals { intros, simp [ins, *] }, { intros, apply balance1_node_ne_leaf, assumption }, { intros, apply balance2_node_ne_leaf, assumption }, end lemma insert_ne_leaf (t : rbnode α) (x : α) : insert lt t x ≠ leaf := begin simp [insert], cases he : ins lt t x; cases get_color t; simp [mk_insert_result], { have := ins_ne_leaf lt t x, contradiction }, { exact absurd he (ins_ne_leaf _ _ _) } end lemma mem_ins_of_incomp (t : rbnode α) {x y : α} : ∀ h : ¬ lt x y ∧ ¬ lt y x, x ∈ t.ins lt y := begin with_cases { apply ins.induction lt t y; intros; simp [ins, *] }, case is_black_lt_red { have := ih h, apply mem_balance1_node_of_mem_left, assumption }, case is_black_gt_red { have := ih h, apply mem_balance2_node_of_mem_left, assumption } end lemma mem_ins_of_mem [is_strict_weak_order α lt] {t : rbnode α} (z : α) : ∀ {x} (h : x ∈ t), x ∈ t.ins lt z := begin with_cases { apply ins.induction lt t z; intros; simp [ins, *] at *; try { contradiction }; blast_disjs }, case is_red_eq or.inr or.inl { have := incomp_trans_of lt h ⟨hc.2, hc.1⟩, simp [this] }, case is_black_lt_red or.inl { apply mem_balance1_node_of_mem_left, apply ih h }, case is_black_lt_red or.inr or.inl { have := ins_ne_leaf lt a z, apply mem_balance1_node_of_incomp, cases h, all_goals { simp [*] } }, case is_black_lt_red or.inr or.inr { apply mem_balance1_node_of_mem_right, assumption }, case is_black_eq or.inr or.inl { have := incomp_trans_of lt hc ⟨h.2, h.1⟩, simp [this] }, case is_black_gt_red or.inl { apply mem_balance2_node_of_mem_right, assumption }, case is_black_gt_red or.inr or.inl { have := ins_ne_leaf lt a z, apply mem_balance2_node_of_incomp, cases h, simp [*], apply ins_ne_leaf }, case is_black_gt_red or.inr or.inr { apply mem_balance2_node_of_mem_left, apply ih h }, -- remaining cases are easy any_goals { intros, simp [h], done }, all_goals { intros, simp [ih h], done }, end lemma mem_mk_insert_result {a t} (c) : mem lt a t → mem lt a (mk_insert_result c t) := by intros; cases c; cases t; simp [mk_insert_result, mem, *] at * lemma mem_of_mem_mk_insert_result {a t c} : mem lt a (mk_insert_result c t) → mem lt a t := by cases t; cases c; simp [mk_insert_result, mem]; intros; assumption lemma mem_insert_of_incomp (t : rbnode α) {x y : α} : ∀ h : ¬ lt x y ∧ ¬ lt y x, x ∈ t.insert lt y := by intros; unfold insert; apply mem_mk_insert_result; apply mem_ins_of_incomp; assumption lemma mem_insert_of_mem [is_strict_weak_order α lt] {t x} (z) : x ∈ t → x ∈ t.insert lt z := by intros; apply mem_mk_insert_result; apply mem_ins_of_mem; assumption lemma of_mem_balance1_node [is_strict_weak_order α lt] {x s v t} : x ∈ balance1_node s v t → x ∈ s ∨ (¬ lt x v ∧ ¬ lt v x) ∨ x ∈ t := begin cases s; simp, { intros, simp [*] }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma of_mem_balance2_node [is_strict_weak_order α lt] {x s v t} : x ∈ balance2_node s v t → x ∈ s ∨ (¬ lt x v ∧ ¬ lt v x) ∨ x ∈ t := begin cases s; simp, { intros, simp [*] }, all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma equiv_or_mem_of_mem_ins [is_strict_weak_order α lt] {t : rbnode α} {x z} : ∀ (h : x ∈ t.ins lt z), x ≈[lt] z ∨ x ∈ t := begin with_cases { apply ins.induction lt t z; intros; simp [ins, strict_weak_order.equiv, *] at *; blast_disjs }, case is_black_lt_red { have h' := of_mem_balance1_node lt h, blast_disjs, have := ih h', blast_disjs, all_goals { simp [h, *] } }, case is_black_gt_red { have h' := of_mem_balance2_node lt h, blast_disjs, have := ih h', blast_disjs, all_goals { simp [h, *] }}, -- All other goals can be solved by the following tactics any_goals { intros, simp [h] }, all_goals { intros, have ih := ih h, cases ih; simp [*], done }, end lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {t : rbnode α} {x z} : ∀ (h : x ∈ t.insert lt z), x ≈[lt] z ∨ x ∈ t := begin simp [insert], intros, apply equiv_or_mem_of_mem_ins, exact mem_of_mem_mk_insert_result lt h end local attribute [simp] mem_exact lemma mem_exact_balance1_node_of_mem_exact {x s} (v) (t : rbnode α) : mem_exact x s → mem_exact x (balance1_node s v t) := begin cases s; simp [false_implies_iff], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma mem_exact_balance2_node_of_mem_exact {x s} (v) (t : rbnode α) : mem_exact x s → mem_exact x (balance2_node s v t) := begin cases s; simp [false_implies_iff], all_goals { apply balance.cases s_lchild s_val s_rchild; intros; simp [*] at *; blast_disjs; simp [*] } end lemma find_balance1_node [is_strict_weak_order α lt] {x y z t s} : ∀ {lo hi}, is_searchable lt t lo (some z) → is_searchable lt s (some z) hi → find lt t y = some x → y ≈[lt] x → find lt (balance1_node t z s) y = some x := begin intros _ _ hs₁ hs₂ heq heqv, have hs := is_searchable_balance1_node lt hs₁ hs₂, have := eq.trans (find_eq_find_of_eqv hs₁ heqv.symm) heq, have := iff.mpr (find_correct_exact hs₁) this, have := mem_exact_balance1_node_of_mem_exact z s this, have := iff.mp (find_correct_exact hs) this, exact eq.trans (find_eq_find_of_eqv hs heqv) this end lemma find_balance2_node [is_strict_weak_order α lt] {x y z s t} [is_trans α lt] : ∀ {lo hi}, is_searchable lt s lo (some z) → is_searchable lt t (some z) hi → find lt t y = some x → y ≈[lt] x → find lt (balance2_node t z s) y = some x := begin intros _ _ hs₁ hs₂ heq heqv, have hs := is_searchable_balance2_node lt hs₁ hs₂, have := eq.trans (find_eq_find_of_eqv hs₂ heqv.symm) heq, have := iff.mpr (find_correct_exact hs₂) this, have := mem_exact_balance2_node_of_mem_exact z s this, have := iff.mp (find_correct_exact hs) this, exact eq.trans (find_eq_find_of_eqv hs heqv) this end /- Auxiliary lemma -/ lemma ite_eq_of_not_lt [is_strict_order α lt] {a b} {β : Type v} (t s : β) (h : lt b a) : (if lt a b then t else s) = s := begin have := not_lt_of_lt h, simp [*] end local attribute [simp] ite_eq_of_not_lt private meta def simp_fi : tactic unit := `[simp [find, ins, *, cmp_using]] lemma find_ins_of_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (he : x ≈[lt] y) : ∀ {lo hi} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi), find lt (ins lt t x) y = some x := begin simp [strict_weak_order.equiv] at he, apply ins.induction lt t x; intros, { simp_fi }, all_goals { simp at hc, cases hs }, { have := lt_of_incomp_of_lt he.swap hc, have := ih hs_hs₁ hlt₁ hc, simp_fi }, { simp_fi }, { have := lt_of_lt_of_incomp hc he, have := ih hs_hs₂ hc hlt₂, simp_fi }, { simp_fi, have := is_searchable_ins lt hs_hs₁ hlt₁ hc, apply find_balance1_node lt this hs_hs₂ (ih hs_hs₁ hlt₁ hc) he.symm }, { have := lt_of_incomp_of_lt he.swap hc, have := ih hs_hs₁ hlt₁ hc, simp_fi }, { simp_fi }, { simp_fi, have := is_searchable_ins lt hs_hs₂ hc hlt₂, apply find_balance2_node lt hs_hs₁ this (ih hs_hs₂ hc hlt₂) he.symm }, { have := lt_of_lt_of_incomp hc he, have := ih hs_hs₂ hc hlt₂, simp_fi } end lemma find_mk_insert_result (c : color) (t : rbnode α) (x : α) : find lt (mk_insert_result c t) x = find lt t x := begin cases t; cases c; simp [mk_insert_result], { simp [find], cases cmp_using lt x t_val; simp [find] } end lemma find_insert_of_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (he : x ≈[lt] y) : is_searchable lt t none none → find lt (insert lt t x) y = some x := begin intro hs, simp [insert, find_mk_insert_result], apply find_ins_of_eqv lt he hs; simp end lemma weak_trichotomous (x y) {p : Prop} (is_lt : ∀ h : lt x y, p) (is_eqv : ∀ h : ¬ lt x y ∧ ¬ lt y x, p) (is_gt : ∀ h : lt y x, p) : p := begin by_cases lt x y; by_cases lt y x, any_goals { apply is_lt; assumption }, any_goals { apply is_gt; assumption }, any_goals { apply is_eqv, constructor; assumption } end section find_ins_of_not_eqv section simp_aux_lemmas lemma find_black_eq_find_red {l y r x} : find lt (black_node l y r) x = find lt (red_node l y r) x := begin simp [find], all_goals { cases cmp_using lt x y; simp [find] } end lemma find_red_of_lt {l y r x} (h : lt x y) : find lt (red_node l y r) x = find lt l x := by simp [find, cmp_using, *] lemma find_red_of_gt [is_strict_order α lt] {l y r x} (h : lt y x) : find lt (red_node l y r) x = find lt r x := begin have := not_lt_of_lt h, simp [find, cmp_using, *] end lemma find_red_of_incomp {l y r x} (h : ¬ lt x y ∧ ¬ lt y x) : find lt (red_node l y r) x = some y := by simp [find, cmp_using, *] end simp_aux_lemmas local attribute [simp] find_black_eq_find_red find_red_of_lt find_red_of_lt find_red_of_gt find_red_of_incomp variable [is_strict_weak_order α lt] lemma find_balance1_lt {l r t v x y lo hi} (h : lt x y) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt (red_node l v r) x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z r { apply weak_trichotomous lt z x; intros; simp [*] }, case red_right : l_left l_val l_right z r { with_cases { apply weak_trichotomous lt z x; intro h' }, case is_lt { have := trans_of lt (lo_lt_hi hr_hs₁) h', simp [*] }, case is_eqv { have : lt l_val x := lt_of_lt_of_incomp (lo_lt_hi hr_hs₁) h', simp [*] }, case is_gt { apply weak_trichotomous lt l_val x; intros; simp [*] } } end meta def ins_ne_leaf_tac := `[apply ins_ne_leaf] lemma find_balance1_node_lt {t s x y lo hi} (hlt : lt y x) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t x s) y = find lt t y := begin cases t; simp [balance1_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance1_lt, assumption' } end lemma find_balance1_gt {l r t v x y lo hi} (h : lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = find lt t x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z { have := trans_of lt (lo_lt_hi hr) h, simp [*] }, case red_right : _ _ _ z { have := trans_of lt (lo_lt_hi hr_hs₂) h, simp [*] } end lemma find_balance1_node_gt {t s x y lo hi} (h : lt x y) (ht : is_searchable lt t lo (some x)) (hs : is_searchable lt s (some x) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t x s) y = find lt s y := begin cases t; simp [balance1_node], all_goals { intros, is_searchable_tactic, apply find_balance1_gt, assumption' } end lemma find_balance1_eqv {l r t v x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (hl : is_searchable lt l lo (some v)) (hr : is_searchable lt r (some v) (some y)) (ht : is_searchable lt t (some y) hi) : find lt (balance1 l v r y t) x = some y := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ _ _ z { have : lt z x := lt_of_lt_of_incomp (lo_lt_hi hr) h.swap, simp [*] }, case red_right : _ _ _ z { have : lt z x := lt_of_lt_of_incomp (lo_lt_hi hr_hs₂) h.swap, simp [*] } end lemma find_balance1_node_eqv {t s x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (ht : is_searchable lt t lo (some y)) (hs : is_searchable lt s (some y) hi) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance1_node t y s) x = some y := begin cases t; simp [balance1_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance1_eqv, assumption' } end lemma find_balance2_lt {l v r t x y lo hi} (h : lt x y) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt t x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left { have := trans h (lo_lt_hi hl_hs₁), simp [*] }, case red_right { have := trans h (lo_lt_hi hl), simp [*] } end lemma find_balance2_node_lt {s t x y lo hi} (h : lt x y) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = find lt s x := begin cases t; simp [balance2_node], all_goals { intros, is_searchable_tactic, apply find_balance2_lt, assumption' } end lemma find_balance2_gt {l v r t x y lo hi} (h : lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = find lt (red_node l v r) x := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left : _ val _ z { with_cases { apply weak_trichotomous lt val x; intro h'; simp [*] }, case is_lt { apply weak_trichotomous lt z x; intros; simp [*] }, case is_eqv { have : lt x z := lt_of_incomp_of_lt h'.swap (lo_lt_hi hl_hs₂), simp [*] }, case is_gt { have := trans h' (lo_lt_hi hl_hs₂), simp [*] } }, case red_right : _ val { apply weak_trichotomous lt val x; intros; simp [*] } end lemma find_balance2_node_gt {s t x y lo hi} (h : lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = find lt t x := begin cases t; simp [balance2_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance2_gt, assumption' } end lemma find_balance2_eqv {l v r t x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (hl : is_searchable lt l (some y) (some v)) (hr : is_searchable lt r (some v) hi) (ht : is_searchable lt t lo (some y)) : find lt (balance2 l v r y t) x = some y := begin with_cases { revert hl hr ht, apply balance.cases l v r; intros; simp [*]; is_searchable_tactic }, case red_left { have := lt_of_incomp_of_lt h (lo_lt_hi hl_hs₁), simp [*] }, case red_right { have := lt_of_incomp_of_lt h (lo_lt_hi hl), simp [*] } end lemma find_balance2_node_eqv {t s x y lo hi} (h : ¬ lt x y ∧ ¬ lt y x) (ht : is_searchable lt t (some y) hi) (hs : is_searchable lt s lo (some y)) (hne : t ≠ leaf . ins_ne_leaf_tac) : find lt (balance2_node t y s) x = some y := begin cases t; simp [balance2_node], { contradiction }, all_goals { intros, is_searchable_tactic, apply find_balance2_eqv, assumption' } end lemma find_ins_of_disj {x y : α} {t : rbnode α} (hn : lt x y ∨ lt y x) : ∀ {lo hi} (hs : is_searchable lt t lo hi) (hlt₁ : lift lt lo (some x)) (hlt₂ : lift lt (some x) hi), find lt (ins lt t x) y = find lt t y := begin apply ins.induction lt t x; intros, { cases hn, all_goals { simp [find, ins, cmp_using, *] } }, all_goals { simp at hc, cases hs }, { have := ih hs_hs₁ hlt₁ hc, simp_fi }, { cases hn, { have := lt_of_incomp_of_lt hc.symm hn, simp_fi }, { have := lt_of_lt_of_incomp hn hc, simp_fi } }, { have := ih hs_hs₂ hc hlt₂, cases hn, { have := trans hc hn, simp_fi }, { simp_fi } }, { have ih := ih hs_hs₁ hlt₁ hc, cases hn, { cases hc' : cmp_using lt y y_1; simp at hc', { have hsi := is_searchable_ins lt hs_hs₁ hlt₁ (trans_of lt hn hc'), have := find_balance1_node_lt lt hc' hsi hs_hs₂, simp_fi }, { have hlt := lt_of_lt_of_incomp hn hc', have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hlt, have := find_balance1_node_eqv lt hc' hsi hs_hs₂, simp_fi }, { have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hc, have := find_balance1_node_gt lt hc' hsi hs_hs₂, simp [*], simp_fi } }, { have hlt := trans hn hc, have hsi := is_searchable_ins lt hs_hs₁ hlt₁ hc, have := find_balance1_node_lt lt hlt hsi hs_hs₂, simp_fi } }, { have := ih hs_hs₁ hlt₁ hc, simp_fi }, { cases hn, { have := lt_of_incomp_of_lt hc.swap hn, simp_fi }, { have := lt_of_lt_of_incomp hn hc, simp_fi } }, { have ih := ih hs_hs₂ hc hlt₂, cases hn, { have hlt := trans hc hn, simp_fi, have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_gt lt hlt hsi hs_hs₁, simp_fi }, { simp_fi, cases hc' : cmp_using lt y y_1; simp at hc', { have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_lt lt hc' hsi hs_hs₁, simp_fi }, { have hlt := lt_of_incomp_of_lt hc'.swap hn, have hsi := is_searchable_ins lt hs_hs₂ hlt hlt₂, have := find_balance2_node_eqv lt hc' hsi hs_hs₁, simp_fi }, { have hsi := is_searchable_ins lt hs_hs₂ hc hlt₂, have := find_balance2_node_gt lt hc' hsi hs_hs₁, simp_fi } } }, { cases hn, { have := trans hc hn, have := ih hs_hs₂ hc hlt₂, simp_fi }, { have ih := ih hs_hs₂ hc hlt₂, simp_fi } } end end find_ins_of_not_eqv lemma find_insert_of_disj [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (hd : lt x y ∨ lt y x) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := begin intro hs, simp [insert, find_mk_insert_result], apply find_ins_of_disj lt hd hs; simp end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {x y : α} {t : rbnode α} (hn : ¬ x ≈[lt] y) : is_searchable lt t none none → find lt (insert lt t x) y = find lt t y := begin intro hs, simp [insert, find_mk_insert_result], have he : lt x y ∨ lt y x, { simp [strict_weak_order.equiv, decidable.not_and_iff_or_not, decidable.not_not_iff] at hn, assumption }, apply find_ins_of_disj lt he hs; simp end end membership_lemmas section is_red_black variables {α : Type u} open nat color inductive is_bad_red_black : rbnode α → nat → Prop | bad_red {c₁ c₂ n l r v} (rb_l : is_red_black l c₁ n) (rb_r : is_red_black r c₂ n) : is_bad_red_black (red_node l v r) n lemma balance1_rb {l r t : rbnode α} {y v : α} {c_l c_r c_t n} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ c, is_red_black (balance1 l y r v t) c (succ n) := by intros h₁ h₂ _; cases h₁; cases h₂; repeat { assumption <|> constructor } lemma balance2_rb {l r t : rbnode α} {y v : α} {c_l c_r c_t n} : is_red_black l c_l n → is_red_black r c_r n → is_red_black t c_t n → ∃ c, is_red_black (balance2 l y r v t) c (succ n) := by intros h₁ h₂ _; cases h₁; cases h₂; repeat { assumption <|> constructor } lemma balance1_node_rb {t s : rbnode α} {y : α} {c n} : is_bad_red_black t n → is_red_black s c n → ∃ c, is_red_black (balance1_node t y s) c (succ n) := by intros h _; cases h; simp [balance1_node]; apply balance1_rb; assumption' lemma balance2_node_rb {t s : rbnode α} {y : α} {c n} : is_bad_red_black t n → is_red_black s c n → ∃ c, is_red_black (balance2_node t y s) c (succ n) := by intros h _; cases h; simp [balance2_node]; apply balance2_rb; assumption' def ins_rb_result : rbnode α → color → nat → Prop | t red n := is_bad_red_black t n | t black n := ∃ c, is_red_black t c n variables {lt : α → α → Prop} [decidable_rel lt] lemma of_get_color_eq_red {t : rbnode α} {c n} : get_color t = red → is_red_black t c n → c = red := begin intros h₁ h₂, cases h₂; simp [get_color] at h₁; contradiction end lemma of_get_color_ne_red {t : rbnode α} {c n} : get_color t ≠ red → is_red_black t c n → c = black := begin intros h₁ h₂, cases h₂; simp [get_color] at h₁; contradiction end variable (lt) lemma ins_rb {t : rbnode α} (x) : ∀ {c n} (h : is_red_black t c n), ins_rb_result (ins lt t x) c n := begin apply ins.induction lt t x; intros; cases h; simp [ins, *, ins_rb_result], { repeat { constructor } }, { specialize ih h_rb_l, cases ih, constructor; assumption }, { constructor; assumption }, { specialize ih h_rb_r, cases ih, constructor; assumption }, { specialize ih h_rb_l, have := of_get_color_eq_red hr h_rb_l, subst h_c₁, simp [ins_rb_result] at ih, apply balance1_node_rb; assumption }, { specialize ih h_rb_l, have := of_get_color_ne_red hnr h_rb_l, subst h_c₁, simp [ins_rb_result] at ih, cases ih, constructor, constructor; assumption }, { constructor, constructor; assumption }, { specialize ih h_rb_r, have := of_get_color_eq_red hr h_rb_r, subst h_c₂, simp [ins_rb_result] at ih, apply balance2_node_rb; assumption }, { specialize ih h_rb_r, have := of_get_color_ne_red hnr h_rb_r, subst h_c₂, simp [ins_rb_result] at ih, cases ih, constructor, constructor; assumption } end def insert_rb_result : rbnode α → color → nat → Prop | t red n := is_red_black t black (succ n) | t black n := ∃ c, is_red_black t c n lemma insert_rb {t : rbnode α} (x) {c n} (h : is_red_black t c n) : insert_rb_result (insert lt t x) c n := begin simp [insert], have hi := ins_rb lt x h, generalize he : ins lt t x = r, simp [he] at hi, cases h; simp [get_color, ins_rb_result, insert_rb_result, mk_insert_result] at *, assumption', { cases hi, simp [mk_insert_result], constructor; assumption } end lemma insert_is_red_black {t : rbnode α} {c n} (x) : is_red_black t c n → ∃ c n, is_red_black (insert lt t x) c n := begin intro h, have := insert_rb lt x h, cases c; simp [insert_rb_result] at this, { constructor, constructor, assumption }, { cases this, constructor, constructor, assumption } end end is_red_black end rbnode
4a2f3da6f3124e1f7de1fcdeed14ea3c0dbcea17
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/hom/monoid.lean
9d36f82d867ce3471aef08e592349f40ef1c6409
[ "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
21,650
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.pi.algebra import algebra.hom.group import algebra.order.group.instances import algebra.order.monoid.with_zero.defs import order.hom.basic /-! # Ordered monoid and group homomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines morphisms between (additive) ordered monoids. ## Types of morphisms * `order_add_monoid_hom`: Ordered additive monoid homomorphisms. * `order_monoid_hom`: Ordered monoid homomorphisms. * `order_monoid_with_zero_hom`: Ordered monoid with zero homomorphisms. ## Typeclasses * `order_add_monoid_hom_class` * `order_monoid_hom_class` * `order_monoid_with_zero_hom_class` ## Notation * `→+o`: Bundled ordered additive monoid homs. Also use for additive groups homs. * `→*o`: Bundled ordered monoid homs. Also use for groups homs. * `→*₀o`: Bundled ordered monoid with zero homs. Also use for groups with zero homs. ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `order_group_hom` -- the idea is that `order_monoid_hom` is used. The constructor for `order_monoid_hom` needs a proof of `map_one` as well as `map_mul`; a separate constructor `order_monoid_hom.mk'` will construct ordered group homs (i.e. ordered monoid homs between ordered groups) given only a proof that multiplication is preserved, Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `order_monoid_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags ordered monoid, ordered group, monoid with zero -/ open function variables {F α β γ δ : Type*} section add_monoid /-- `α →+o β` is the type of monotone functions `α → β` that preserve the `ordered_add_comm_monoid` structure. `order_add_monoid_hom` is also used for ordered group homomorphisms. When possible, instead of parametrizing results over `(f : α →+o β)`, you should parametrize over `(F : Type*) [order_add_monoid_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_add_monoid_hom_class`. -/ structure order_add_monoid_hom (α β : Type*) [preorder α] [preorder β] [add_zero_class α] [add_zero_class β] extends α →+ β := (monotone' : monotone to_fun) infixr ` →+o `:25 := order_add_monoid_hom section set_option old_structure_cmd true /-- `order_add_monoid_hom_class F α β` states that `F` is a type of ordered monoid homomorphisms. You should also extend this typeclass when you extend `order_add_monoid_hom`. -/ @[ancestor add_monoid_hom_class] class order_add_monoid_hom_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] [add_zero_class α] [add_zero_class β] extends add_monoid_hom_class F α β := (monotone (f : F) : monotone f) end -- Instances and lemmas are defined below through `@[to_additive]`. end add_monoid section monoid variables [preorder α] [preorder β] [mul_one_class α] [mul_one_class β] /-- `α →*o β` is the type of functions `α → β` that preserve the `ordered_comm_monoid` structure. `order_monoid_hom` is also used for ordered group homomorphisms. When possible, instead of parametrizing results over `(f : α →*o β)`, you should parametrize over `(F : Type*) [order_monoid_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_monoid_hom_class`. -/ @[to_additive] structure order_monoid_hom (α β : Type*) [preorder α] [preorder β] [mul_one_class α] [mul_one_class β] extends α →* β := (monotone' : monotone to_fun) infixr ` →*o `:25 := order_monoid_hom section set_option old_structure_cmd true /-- `order_monoid_hom_class F α β` states that `F` is a type of ordered monoid homomorphisms. You should also extend this typeclass when you extend `order_monoid_hom`. -/ @[ancestor monoid_hom_class, to_additive] class order_monoid_hom_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] [mul_one_class α] [mul_one_class β] extends monoid_hom_class F α β := (monotone (f : F) : monotone f) end @[priority 100, to_additive] -- See note [lower instance priority] instance order_monoid_hom_class.to_order_hom_class [order_monoid_hom_class F α β] : order_hom_class F α β := { map_rel := order_monoid_hom_class.monotone, .. ‹order_monoid_hom_class F α β› } @[to_additive] instance [order_monoid_hom_class F α β] : has_coe_t F (α →*o β) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_mul' := map_mul f, monotone' := order_monoid_hom_class.monotone _ }⟩ end monoid section monoid_with_zero variables [preorder α] [preorder β] [mul_zero_one_class α] [mul_zero_one_class β] /-- `order_monoid_with_zero_hom α β` is the type of functions `α → β` that preserve the `monoid_with_zero` structure. `order_monoid_with_zero_hom` is also used for group homomorphisms. When possible, instead of parametrizing results over `(f : α →+ β)`, you should parametrize over `(F : Type*) [order_monoid_with_zero_hom_class F α β] (f : F)`. When you extend this structure, make sure to extend `order_monoid_with_zero_hom_class`. -/ structure order_monoid_with_zero_hom (α β : Type*) [preorder α] [preorder β] [mul_zero_one_class α] [mul_zero_one_class β] extends α →*₀ β := (monotone' : monotone to_fun) infixr ` →*₀o `:25 := order_monoid_with_zero_hom section set_option old_structure_cmd true /-- `order_monoid_with_zero_hom_class F α β` states that `F` is a type of ordered monoid with zero homomorphisms. You should also extend this typeclass when you extend `order_monoid_with_zero_hom`. -/ class order_monoid_with_zero_hom_class (F : Type*) (α β : out_param $ Type*) [preorder α] [preorder β] [mul_zero_one_class α] [mul_zero_one_class β] extends monoid_with_zero_hom_class F α β := (monotone (f : F) : monotone f) end @[priority 100] -- See note [lower instance priority] instance order_monoid_with_zero_hom_class.to_order_monoid_hom_class [order_monoid_with_zero_hom_class F α β] : order_monoid_hom_class F α β := { .. ‹order_monoid_with_zero_hom_class F α β› } instance [order_monoid_with_zero_hom_class F α β] : has_coe_t F (α →*₀o β) := ⟨λ f, { to_fun := f, map_one' := map_one f, map_zero' := map_zero f, map_mul' := map_mul f, monotone' := order_monoid_with_zero_hom_class.monotone _ }⟩ end monoid_with_zero section ordered_add_comm_monoid variables [ordered_add_comm_monoid α] [ordered_add_comm_monoid β] [order_add_monoid_hom_class F α β] (f : F) {a : α} include β lemma map_nonneg (ha : 0 ≤ a) : 0 ≤ f a := by { rw ←map_zero f, exact order_hom_class.mono _ ha } lemma map_nonpos (ha : a ≤ 0) : f a ≤ 0 := by { rw ←map_zero f, exact order_hom_class.mono _ ha } end ordered_add_comm_monoid section ordered_add_comm_group variables [ordered_add_comm_group α] [ordered_add_comm_monoid β] [add_monoid_hom_class F α β] (f : F) lemma monotone_iff_map_nonneg : monotone (f : α → β) ↔ ∀ a, 0 ≤ a → 0 ≤ f a := ⟨λ h a, by { rw ←map_zero f, apply h }, λ h a b hl, by { rw [←sub_add_cancel b a, map_add f], exact le_add_of_nonneg_left (h _ $ sub_nonneg.2 hl) }⟩ lemma antitone_iff_map_nonpos : antitone (f : α → β) ↔ ∀ a, 0 ≤ a → f a ≤ 0 := monotone_to_dual_comp_iff.symm.trans $ monotone_iff_map_nonneg _ lemma monotone_iff_map_nonpos : monotone (f : α → β) ↔ ∀ a ≤ 0, f a ≤ 0 := antitone_comp_of_dual_iff.symm.trans $ antitone_iff_map_nonpos _ lemma antitone_iff_map_nonneg : antitone (f : α → β) ↔ ∀ a ≤ 0, 0 ≤ f a := monotone_comp_of_dual_iff.symm.trans $ monotone_iff_map_nonneg _ variable [covariant_class β β (+) (<)] lemma strict_mono_iff_map_pos : strict_mono (f : α → β) ↔ ∀ a, 0 < a → 0 < f a := ⟨λ h a, by { rw ←map_zero f, apply h }, λ h a b hl, by { rw [←sub_add_cancel b a, map_add f], exact lt_add_of_pos_left _ (h _ $ sub_pos.2 hl) }⟩ lemma strict_anti_iff_map_neg : strict_anti (f : α → β) ↔ ∀ a, 0 < a → f a < 0 := strict_mono_to_dual_comp_iff.symm.trans $ strict_mono_iff_map_pos _ lemma strict_mono_iff_map_neg : strict_mono (f : α → β) ↔ ∀ a < 0, f a < 0 := strict_anti_comp_of_dual_iff.symm.trans $ strict_anti_iff_map_neg _ lemma strict_anti_iff_map_pos : strict_anti (f : α → β) ↔ ∀ a < 0, 0 < f a := strict_mono_comp_of_dual_iff.symm.trans $ strict_mono_iff_map_pos _ end ordered_add_comm_group namespace order_monoid_hom section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] [mul_one_class α] [mul_one_class β] [mul_one_class γ] [mul_one_class δ] {f g : α →*o β} @[to_additive] instance : order_monoid_hom_class (α →*o β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', monotone := λ f, f.monotone' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ @[to_additive "Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly."] instance : has_coe_to_fun (α →*o β) (λ _, α → β) := fun_like.has_coe_to_fun -- Other lemmas should be accessed through the `fun_like` API @[ext, to_additive] lemma ext (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h @[to_additive] lemma to_fun_eq_coe (f : α →*o β) : f.to_fun = (f : α → β) := rfl @[simp, to_additive] lemma coe_mk (f : α →* β) (h) : (order_monoid_hom.mk f h : α → β) = f := rfl @[simp, to_additive] lemma mk_coe (f : α →*o β) (h) : order_monoid_hom.mk (f : α →* β) h = f := by { ext, refl } /-- Reinterpret an ordered monoid homomorphism as an order homomorphism. -/ @[to_additive "Reinterpret an ordered additive monoid homomorphism as an order homomorphism."] def to_order_hom (f : α →*o β) : α →o β := { ..f } @[simp, to_additive] lemma coe_monoid_hom (f : α →*o β) : ((f : α →* β) : α → β) = f := rfl @[simp, to_additive] lemma coe_order_hom (f : α →*o β) : ((f : α →o β) : α → β) = f := rfl @[to_additive] lemma to_monoid_hom_injective : injective (to_monoid_hom : _ → α →* β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h @[to_additive] lemma to_order_hom_injective : injective (to_order_hom : _ → α →o β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h /-- Copy of an `order_monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ @[to_additive "Copy of an `order_monoid_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities."] protected def copy (f : α →*o β) (f' : α → β) (h : f' = f) : α →*o β := { to_fun := f', monotone' := h.symm.subst f.monotone', ..f.to_monoid_hom.copy f' h } @[simp, to_additive] lemma coe_copy (f : α →*o β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl @[to_additive] lemma copy_eq (f : α →*o β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- The identity map as an ordered monoid homomorphism. -/ @[to_additive "The identity map as an ordered additive monoid homomorphism."] protected def id : α →*o α := { ..monoid_hom.id α, ..order_hom.id } @[simp, to_additive] lemma coe_id : ⇑(order_monoid_hom.id α) = id := rfl @[to_additive] instance : inhabited (α →*o α) := ⟨order_monoid_hom.id α⟩ variables {α} /-- Composition of `order_monoid_hom`s as an `order_monoid_hom`. -/ @[to_additive "Composition of `order_add_monoid_hom`s as an `order_add_monoid_hom`"] def comp (f : β →*o γ) (g : α →*o β) : α →*o γ := { ..f.to_monoid_hom.comp (g : α →* β), ..f.to_order_hom.comp (g : α →o β) } @[simp, to_additive] lemma coe_comp (f : β →*o γ) (g : α →*o β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp, to_additive] lemma comp_apply (f : β →*o γ) (g : α →*o β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp, to_additive] lemma coe_comp_monoid_hom (f : β →*o γ) (g : α →*o β) : (f.comp g : α →* γ) = (f : β →* γ).comp g := rfl @[simp, to_additive] lemma coe_comp_order_hom (f : β →*o γ) (g : α →*o β) : (f.comp g : α →o γ) = (f : β →o γ).comp g := rfl @[simp, to_additive] lemma comp_assoc (f : γ →*o δ) (g : β →*o γ) (h : α →*o β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp, to_additive] lemma comp_id (f : α →*o β) : f.comp (order_monoid_hom.id α) = f := ext $ λ a, rfl @[simp, to_additive] lemma id_comp (f : α →*o β) : (order_monoid_hom.id β).comp f = f := ext $ λ a, rfl @[to_additive] lemma cancel_right {g₁ g₂ : β →*o γ} {f : α →*o β} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ @[to_additive] lemma cancel_left {g : β →*o γ} {f₁ f₂ : α →*o β} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ /-- `1` is the homomorphism sending all elements to `1`. -/ @[to_additive "`1` is the homomorphism sending all elements to `1`."] instance : has_one (α →*o β) := ⟨{ monotone' := monotone_const, ..(1 : α →* β) }⟩ @[simp, to_additive] lemma coe_one : ⇑(1 : α →*o β) = 1 := rfl @[simp, to_additive] lemma one_apply (a : α) : (1 : α →*o β) a = 1 := rfl @[simp, to_additive] lemma one_comp (f : α →*o β) : (1 : β →*o γ).comp f = 1 := rfl @[simp, to_additive] lemma comp_one (f : β →*o γ) : f.comp (1 : α →*o β) = 1 := by { ext, exact map_one f } end preorder section mul variables [ordered_comm_monoid α] [ordered_comm_monoid β] [ordered_comm_monoid γ] /-- For two ordered monoid morphisms `f` and `g`, their product is the ordered monoid morphism sending `a` to `f a * g a`. -/ @[to_additive "For two ordered additive monoid morphisms `f` and `g`, their product is the ordered additive monoid morphism sending `a` to `f a + g a`."] instance : has_mul (α →*o β) := ⟨λ f g, { monotone' := f.monotone'.mul' g.monotone', ..(f * g : α →* β) }⟩ @[simp, to_additive] lemma coe_mul (f g : α →*o β) : ⇑(f * g) = f * g := rfl @[simp, to_additive] lemma mul_apply (f g : α →*o β) (a : α) : (f * g) a = f a * g a := rfl @[to_additive] lemma mul_comp (g₁ g₂ : β →*o γ) (f : α →*o β) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl @[to_additive] lemma comp_mul (g : β →*o γ) (f₁ f₂ : α →*o β) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := by { ext, exact map_mul g _ _ } end mul section ordered_comm_monoid variables {hα : ordered_comm_monoid α} {hβ : ordered_comm_monoid β} include hα hβ @[simp, to_additive] lemma to_monoid_hom_eq_coe (f : α →*o β) : f.to_monoid_hom = f := by { ext, refl } @[simp, to_additive] lemma to_order_hom_eq_coe (f : α →*o β) : f.to_order_hom = f := rfl end ordered_comm_monoid section ordered_comm_group variables {hα : ordered_comm_group α} {hβ : ordered_comm_group β} include hα hβ /-- Makes an ordered group homomorphism from a proof that the map preserves multiplication. -/ @[to_additive "Makes an ordered additive group homomorphism from a proof that the map preserves addition.", simps {fully_applied := ff}] def mk' (f : α → β) (hf : monotone f) (map_mul : ∀ a b : α, f (a * b) = f a * f b) : α →*o β := { monotone' := hf, ..monoid_hom.mk' f map_mul } end ordered_comm_group end order_monoid_hom namespace order_monoid_with_zero_hom section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] [mul_zero_one_class α] [mul_zero_one_class β] [mul_zero_one_class γ] [mul_zero_one_class δ] {f g : α →*₀o β} instance : order_monoid_with_zero_hom_class (α →*₀o β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_mul := λ f, f.map_mul', map_one := λ f, f.map_one', map_zero := λ f, f.map_zero', monotone := λ f, f.monotone' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →*₀o β) (λ _, α → β) := fun_like.has_coe_to_fun -- Other lemmas should be accessed through the `fun_like` API @[ext] lemma ext (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h lemma to_fun_eq_coe (f : α →*₀o β) : f.to_fun = (f : α → β) := rfl @[simp] lemma coe_mk (f : α →*₀ β) (h) : (order_monoid_with_zero_hom.mk f h : α → β) = f := rfl @[simp] lemma mk_coe (f : α →*₀o β) (h) : order_monoid_with_zero_hom.mk (f : α →*₀ β) h = f := by { ext, refl } /-- Reinterpret an ordered monoid with zero homomorphism as an order monoid homomorphism. -/ def to_order_monoid_hom (f : α →*₀o β) : α →*o β := { ..f } @[simp] lemma coe_monoid_with_zero_hom (f : α →*₀o β) : ⇑(f : α →*₀ β) = f := rfl @[simp] lemma coe_order_monoid_hom (f : α →*₀o β) : ⇑(f : α →*o β) = f := rfl lemma to_order_monoid_hom_injective : injective (to_order_monoid_hom : _ → α →*o β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h lemma to_monoid_with_zero_hom_injective : injective (to_monoid_with_zero_hom : _ → α →*₀ β) := λ f g h, ext $ by convert fun_like.ext_iff.1 h /-- Copy of an `order_monoid_with_zero_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : α →*₀o β) (f' : α → β) (h : f' = f) : α →*o β := { to_fun := f', .. f.to_order_monoid_hom.copy f' h, .. f.to_monoid_with_zero_hom.copy f' h } @[simp] lemma coe_copy (f : α →*₀o β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : α →*₀o β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- The identity map as an ordered monoid with zero homomorphism. -/ protected def id : α →*₀o α := { ..monoid_with_zero_hom.id α, ..order_hom.id } @[simp] lemma coe_id : ⇑(order_monoid_with_zero_hom.id α) = id := rfl instance : inhabited (α →*₀o α) := ⟨order_monoid_with_zero_hom.id α⟩ variables {α} /-- Composition of `order_monoid_with_zero_hom`s as an `order_monoid_with_zero_hom`. -/ def comp (f : β →*₀o γ) (g : α →*₀o β) : α →*₀o γ := { ..f.to_monoid_with_zero_hom.comp (g : α →*₀ β), ..f.to_order_monoid_hom.comp (g : α →*o β) } @[simp] lemma coe_comp (f : β →*₀o γ) (g : α →*₀o β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : β →*₀o γ) (g : α →*₀o β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_monoid_with_zero_hom (f : β →*₀o γ) (g : α →*₀o β) : (f.comp g : α →*₀ γ) = (f : β →*₀ γ).comp g := rfl @[simp] lemma coe_comp_order_monoid_hom (f : β →*₀o γ) (g : α →*₀o β) : (f.comp g : α →*o γ) = (f : β →*o γ).comp g := rfl @[simp] lemma comp_assoc (f : γ →*₀o δ) (g : β →*₀o γ) (h : α →*₀o β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : α →*₀o β) : f.comp (order_monoid_with_zero_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : α →*₀o β) : (order_monoid_with_zero_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : β →*₀o γ} {f : α →*₀o β} (hf : function.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 : β →*₀o γ} {f₁ f₂ : α →*₀o β} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end preorder section mul variables [linear_ordered_comm_monoid_with_zero α] [linear_ordered_comm_monoid_with_zero β] [linear_ordered_comm_monoid_with_zero γ] /-- For two ordered monoid morphisms `f` and `g`, their product is the ordered monoid morphism sending `a` to `f a * g a`. -/ instance : has_mul (α →*₀o β) := ⟨λ f g, { monotone' := f.monotone'.mul' g.monotone', ..(f * g : α →*₀ β) }⟩ @[simp] lemma coe_mul (f g : α →*₀o β) : ⇑(f * g) = f * g := rfl @[simp] lemma mul_apply (f g : α →*₀o β) (a : α) : (f * g) a = f a * g a := rfl lemma mul_comp (g₁ g₂ : β →*₀o γ) (f : α →*₀o β) : (g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl lemma comp_mul (g : β →*₀o γ) (f₁ f₂ : α →*₀o β) : g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ := ext $ λ _, map_mul g _ _ end mul section linear_ordered_comm_monoid_with_zero variables {hα : preorder α} {hα' : mul_zero_one_class α} {hβ : preorder β} {hβ' : mul_zero_one_class β} include hα hα' hβ hβ' @[simp] lemma to_monoid_with_zero_hom_eq_coe (f : α →*₀o β) : f.to_monoid_with_zero_hom = f := by { ext, refl } @[simp] lemma to_order_monoid_hom_eq_coe (f : α →*₀o β) : f.to_order_monoid_hom = f := rfl end linear_ordered_comm_monoid_with_zero end order_monoid_with_zero_hom
15103a32334fd461046562f2d78252e1b7b95d4b
80162757f50b09d3cad5564907e4c9b00742e045
/lattice.lean
b878ed3f326a24850f7a67c71500521574ff5543
[]
no_license
EdAyers/edlib
cc30d0a54fed347a85b6df6045f68e6b48bc71a3
78b8c5d91f023f939c102837d748868e2f3ed27d
refs/heads/master
1,586,459,758,216
1,571,322,179,000
1,571,322,179,000
160,538,917
2
0
null
null
null
null
UTF-8
Lean
false
false
6,605
lean
import .set .order set_option old_structure_cmd true -- stops errors for diamonds. universes u v section variables {α : Type u} {ι : Type v} {a b c: α} /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone [preorder α] [preorder ι] (f : α → ι) := ∀⦃a b⦄, a ≤ b → f a ≤ f b reserve infixl ` ⊓ `:70 reserve infixl ` ⊔ `:65 instance [partial_order α] : has_coe (a = b) (a ≤ b) := ⟨le_of_eq⟩ instance : has_coe (a = b) (b = a) := ⟨eq.symm⟩ infixl ` ◾ ` : 300 := le_trans /-- Typeclass for the `⊔` (`\lub`) notation -/ class has_join (α : Type u) := (join : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ class has_meet (α : Type u) := (meet : α → α → α) /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top _ notation `⊥` := has_bot.bot _ infix ⊔ := has_join.join infix ⊓ := has_meet.meet class has_Join (α : Type u) := (Join : set α → α) class has_Meet (α : Type u) := (Meet : set α → α) def iJoin [has_Join α] (s : ι → α) : α := has_Join.Join {a : α | ∃i : ι, a = s i} def iMeet [has_Meet α] (s : ι → α) : α := has_Meet.Meet {a : α | ∃i : ι, a = s i} notation `⨆` binders `, ` r:(scoped f, iJoin f) := r prefix `⨆₀`:120 := has_Join.Join notation `⨅` binders `, ` r:(scoped f, iMeet f) := r prefix `⨅₀`:120 := has_Meet.Meet end variables (α : Type u) [partial_order α] /-- Pairwise meets -/ class meet_semilattice extends has_meet α := (π₁ (a b : α) : a ⊓ b ≤ a) (π₂ (a b : α) : a ⊓ b ≤ b) (u_meet (a b c : α) : a ≤ b → a ≤ c → a ≤ b ⊓ c) class has_terminal extends has_top α := (le_top (a : α) : a ≤ ⊤) /--Setwise meets-/ class Meet_semilattice extends has_Meet α := (π : ∀s, ∀a∈s, Meet s ≤ a) (u_Meet : ∀s a, (∀b∈s, a ≤ b) → a ≤ Meet s) open Meet_semilattice instance meet_of_Meet [Meet_semilattice α] : meet_semilattice α := { meet := λ a b, ⨅₀ {a,b}, π₁ := λ a b, π {a,b} a set.pair₁, π₂ := λ a b, π {a,b} b set.pair₂, u_meet := λ a b c ab ac, u_Meet {b,c} a (λ x h, or.rec_on h (λ p, ac ◾ p) (λ h₂, or.rec_on h₂ (λ p, ab ◾ p) (λ q, false.rec_on _ q))), } instance top_of_Meet [Meet_semilattice α] : has_terminal α := { top := ⨅₀ ∅ , le_top := λ a, u_Meet ∅ a (λ b h, false.rec_on _ h) } class join_semilattice extends has_join α:= (ι₁ (a b : α) : a ≤ a ⊔ b) (ι₂ (a b : α) : b ≤ a ⊔ b) (u_join (a b c : α) : b ≤ a → c ≤ a → b ⊔ c ≤ a) class lattice extends meet_semilattice α, join_semilattice α class has_initial extends has_bot α := (bot_le (a : α) : ⊥ ≤ a) class bounded_lattice extends lattice α, has_terminal α, has_initial α class Join_semilattice extends has_Join α := (ι : ∀s, ∀a∈s, a ≤ Join s) (u_Join : ∀s a, (∀b∈s, b ≤ a) → Join s ≤ a) /-- A distributive lattice is a lattice that satisfies any of four equivalent distribution properties (of sup over inf or inf over sup, on the left or right). A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) /-- A lattice which has setwise joins and meets. You also must explicitly provide the meets and joins to make definitional equality nice. -/ class complete_lattice extends Meet_semilattice α, Join_semilattice α, meet_semilattice α, join_semilattice α, has_terminal α, has_initial α open complete_lattice def is_minimal [has_initial α] (a : α) : Prop := ∀ b : α, b < a → b = ⊥ def is_maximal [has_terminal α] (a : α) : Prop := ∀ b : α, a < b → b = ⊤ section order_dual instance [x : has_meet α] : has_join (order_dual α) := ⟨(@has_meet.meet _ x : α → α → α)⟩ instance [x : has_join α] : has_meet (order_dual α) := ⟨(@has_join.join _ x : α → α → α)⟩ instance [x : has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [x : has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [x : has_Join α] : has_Meet (order_dual α) := ⟨(@has_Join.Join _ x : set α → α)⟩ instance [x : has_Meet α] : has_Join (order_dual α) := ⟨(@has_Meet.Meet _ x : set α → α)⟩ -- instance dual [po : partial_order α] [cl : complete_lattice α] : @complete_lattice (order_dual α) (@order_dual.partial_order α po) := -- { π₁ := @complete_lattice.ι₁ α po cl -- , ι₁ := @complete_lattice.π₁ α po cl -- , π₂ := @complete_lattice.ι₂ α po cl -- , ι₂ := @complete_lattice.π₂ α po cl -- , π := @complete_lattice.ι α po cl -- , ι := @complete_lattice.π α po cl -- , u_Meet := @complete_lattice.u_Join α po cl -- , u_meet := @complete_lattice.u_join α po cl -- , u_Join := @complete_lattice.u_Meet α po cl -- , u_join := @complete_lattice.u_meet α po cl -- , bot_le := @complete_lattice.le_top α po cl -- , le_top := @complete_lattice.bot_le α po cl -- , ..order_dual.has_bot -- , ..order_dual.has_top -- , ..order_dual.has_meet -- , ..order_dual.has_join -- , ..order_dual.has_Join -- , ..order_dual.has_Meet -- } instance {α : Type u}: preorder (set α) := { le := λ A B, A ⊆ B , le_refl := λ A x, id , le_trans := λ A B C f g _ h, g (f h) } instance {α : Type u} : partial_order (set α) := { le_antisymm := λ A B p q, set.ext $ λ x, ⟨λ h, p h,λ h, q h⟩ , ..set.preorder } instance : complete_lattice (set α) := { meet := λ A B, A ∩ B , join := λ A B, A ∪ B , Meet := λ ℱ, ⋂₀ ℱ , Join := λ ℱ, ⋃₀ ℱ , top := set.univ , bot := ∅ , π₁ := λ A B, λ x a, a.1 , π₂ := λ A B, λ x a, a.2 , u_meet := λ A B C AB AC x xA, ⟨AB xA, AC xA⟩ , π := λ ℱ A h₁ x h₂, h₂ A h₁ , u_Meet := λ ℱ A h₁ x xA B h₂, h₁ B h₂ xA , ι₁ := λ A B, λ x a, or.inl a , ι₂ := λ A B, λ x a, or.inr a , u_join := λ A B C BA CA x h, or.rec_on h (λ q, BA q) (λ q, CA q) , ι := λ ℱ A h₁ x h₂, ⟨A,h₁,h₂⟩ , u_Join := λ ℱ A p x ⟨B,h₁,h₂⟩, p B h₁ h₂ , le_top := λ A x _, ⟨⟩ , bot_le := λ A x o, false.rec_on _ o } end order_dual
1355feeacb0bffcc13c228aa2c721d7ca230dacd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/quadratic_form/prod.lean
5b7d0039b76c5e514b6a1989c87bb42927dfc8d6
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,101
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.quadratic_form.isometry /-! # Quadratic form on product and pi types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `quadratic_form.prod Q₁ Q₂`: the quadratic form constructed elementwise on a product * `quadratic_form.pi Q`: the quadratic form constructed elementwise on a pi type ## Main results * `quadratic_form.equivalent.prod`, `quadratic_form.equivalent.pi`: quadratic forms are equivalent if their components are equivalent * `quadratic_form.nonneg_prod_iff`, `quadratic_form.nonneg_pi_iff`: quadratic forms are positive- semidefinite if and only if their components are positive-semidefinite. * `quadratic_form.pos_def_prod_iff`, `quadratic_form.pos_def_pi_iff`: quadratic forms are positive- definite if and only if their components are positive-definite. ## Implementation notes Many of the lemmas in this file could be generalized into results about sums of positive and non-negative elements, and would generalize to any map `Q` where `Q 0 = 0`, not just quadratic forms specifically. -/ universes u v w variables {ι : Type*} {R : Type*} {M₁ M₂ N₁ N₂ : Type*} {Mᵢ Nᵢ : ι → Type*} variables [semiring R] variables [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid N₁] [add_comm_monoid N₂] variables [module R M₁] [module R M₂] [module R N₁] [module R N₂] variables [Π i, add_comm_monoid (Mᵢ i)] [Π i, add_comm_monoid (Nᵢ i)] variables [Π i, module R (Mᵢ i)] [Π i, module R (Nᵢ i)] namespace quadratic_form /-- Construct a quadratic form on a product of two modules from the quadratic form on each module. -/ @[simps] def prod (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) : quadratic_form R (M₁ × M₂) := Q₁.comp (linear_map.fst _ _ _) + Q₂.comp (linear_map.snd _ _ _) /-- An isometry between quadratic forms generated by `quadratic_form.prod` can be constructed from a pair of isometries between the left and right parts. -/ @[simps to_linear_equiv] def isometry.prod {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₁' : quadratic_form R N₁} {Q₂' : quadratic_form R N₂} (e₁ : Q₁.isometry Q₁') (e₂ : Q₂.isometry Q₂') : (Q₁.prod Q₂).isometry (Q₁'.prod Q₂'):= { map_app' := λ x, congr_arg2 (+) (e₁.map_app x.1) (e₂.map_app x.2), to_linear_equiv := linear_equiv.prod e₁.to_linear_equiv e₂.to_linear_equiv} lemma equivalent.prod {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₁' : quadratic_form R N₁} {Q₂' : quadratic_form R N₂} (e₁ : Q₁.equivalent Q₁') (e₂ : Q₂.equivalent Q₂') : (Q₁.prod Q₂).equivalent (Q₁'.prod Q₂'):= nonempty.map2 isometry.prod e₁ e₂ /-- If a product is anisotropic then its components must be. The converse is not true. -/ lemma anisotropic_of_prod {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (h : (Q₁.prod Q₂).anisotropic) : Q₁.anisotropic ∧ Q₂.anisotropic := begin simp_rw [anisotropic, prod_apply, prod.forall, prod.mk_eq_zero] at h, split, { intros x hx, refine (h x 0 _).1, rw [hx, zero_add, map_zero] }, { intros x hx, refine (h 0 x _).2, rw [hx, add_zero, map_zero] }, end lemma nonneg_prod_iff {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : (∀ x, 0 ≤ (Q₁.prod Q₂) x) ↔ (∀ x, 0 ≤ Q₁ x) ∧ (∀ x, 0 ≤ Q₂ x) := begin simp_rw [prod.forall, prod_apply], split, { intro h, split, { intro x, simpa only [add_zero, map_zero] using h x 0 }, { intro x, simpa only [zero_add, map_zero] using h 0 x } }, { rintros ⟨h₁, h₂⟩ x₁ x₂, exact add_nonneg (h₁ x₁) (h₂ x₂), }, end lemma pos_def_prod_iff {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : (Q₁.prod Q₂).pos_def ↔ Q₁.pos_def ∧ Q₂.pos_def := begin simp_rw [pos_def_iff_nonneg, nonneg_prod_iff], split, { rintros ⟨⟨hle₁, hle₂⟩, ha⟩, obtain ⟨ha₁, ha₂⟩ := anisotropic_of_prod ha, refine ⟨⟨hle₁, ha₁⟩, ⟨hle₂, ha₂⟩⟩, }, { rintro ⟨⟨hle₁, ha₁⟩, ⟨hle₂, ha₂⟩⟩, refine ⟨⟨hle₁, hle₂⟩, _⟩, rintro ⟨x₁, x₂⟩ (hx : Q₁ x₁ + Q₂ x₂ = 0), rw [add_eq_zero_iff' (hle₁ x₁) (hle₂ x₂), ha₁.eq_zero_iff, ha₂.eq_zero_iff] at hx, rwa [prod.mk_eq_zero], } end lemma pos_def.prod {R} [ordered_ring R] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (h₁ : Q₁.pos_def) (h₂ : Q₂.pos_def) : (Q₁.prod Q₂).pos_def := pos_def_prod_iff.mpr ⟨h₁, h₂⟩ open_locale big_operators /-- Construct a quadratic form on a family of modules from the quadratic form on each module. -/ def pi [fintype ι] (Q : Π i, quadratic_form R (Mᵢ i)) : quadratic_form R (Π i, Mᵢ i) := ∑ i, (Q i).comp (linear_map.proj i : _ →ₗ[R] Mᵢ i) @[simp] lemma pi_apply [fintype ι] (Q : Π i, quadratic_form R (Mᵢ i)) (x : Π i, Mᵢ i) : pi Q x = ∑ i, Q i (x i) := sum_apply _ _ _ /-- An isometry between quadratic forms generated by `quadratic_form.prod` can be constructed from a pair of isometries between the left and right parts. -/ @[simps to_linear_equiv] def isometry.pi [fintype ι] {Q : Π i, quadratic_form R (Mᵢ i)} {Q' : Π i, quadratic_form R (Nᵢ i)} (e : Π i, (Q i).isometry (Q' i)) : (pi Q).isometry (pi Q') := { map_app' := λ x, by simp only [pi_apply, linear_equiv.Pi_congr_right_apply, linear_equiv.to_fun_eq_coe, isometry.coe_to_linear_equiv, isometry.map_app], to_linear_equiv := linear_equiv.Pi_congr_right (λ i, (e i : Mᵢ i ≃ₗ[R] Nᵢ i))} lemma equivalent.pi [fintype ι] {Q : Π i, quadratic_form R (Mᵢ i)} {Q' : Π i, quadratic_form R (Nᵢ i)} (e : ∀ i, (Q i).equivalent (Q' i)) : (pi Q).equivalent (pi Q') := ⟨isometry.pi (λ i, classical.choice (e i))⟩ /-- If a family is anisotropic then its components must be. The converse is not true. -/ lemma anisotropic_of_pi [fintype ι] {R} [ordered_ring R] [Π i, module R (Mᵢ i)] {Q : Π i, quadratic_form R (Mᵢ i)} (h : (pi Q).anisotropic) : ∀ i, (Q i).anisotropic := begin simp_rw [anisotropic, pi_apply, function.funext_iff, pi.zero_apply] at h, intros i x hx, classical, have := h (pi.single i x) _ i, { rw pi.single_eq_same at this, exact this, }, apply finset.sum_eq_zero, intros j _, by_cases hji : j = i, { subst hji, rw [pi.single_eq_same, hx] }, { rw [pi.single_eq_of_ne hji, map_zero] }, end lemma nonneg_pi_iff [fintype ι] {R} [ordered_ring R] [Π i, module R (Mᵢ i)] {Q : Π i, quadratic_form R (Mᵢ i)} : (∀ x, 0 ≤ pi Q x) ↔ (∀ i x, 0 ≤ Q i x) := begin simp_rw [pi, sum_apply, comp_apply, linear_map.proj_apply], dsimp only, split, -- TODO: does this generalize to a useful lemma independent of `quadratic_form`? { intros h i x, classical, convert h (pi.single i x) using 1, rw [finset.sum_eq_single_of_mem i (finset.mem_univ _) (λ j _ hji, _), pi.single_eq_same], rw [pi.single_eq_of_ne hji, map_zero], }, { rintros h x, exact finset.sum_nonneg (λ i hi, h i (x i)), }, end lemma pos_def_pi_iff [fintype ι] {R} [ordered_ring R] [Π i, module R (Mᵢ i)] {Q : Π i, quadratic_form R (Mᵢ i)} : (pi Q).pos_def ↔ (∀ i, (Q i).pos_def) := begin simp_rw [pos_def_iff_nonneg, nonneg_pi_iff], split, { rintros ⟨hle, ha⟩, intro i, exact ⟨hle i, anisotropic_of_pi ha i⟩, }, { intro h, refine ⟨λ i, (h i).1, λ x hx, funext $ λ i, (h i).2 _ _⟩, rw [pi_apply, finset.sum_eq_zero_iff_of_nonneg (λ j hj, _)] at hx, { exact hx _ (finset.mem_univ _) }, exact (h j).1 _ } end end quadratic_form
81bb1f13e9e5339b610a589f5c8abda88555d254
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/theories/action.lean
ca0719f4940c6add7964b52744b0dc5b27236770
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
1,754
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic namespace algebra signature left_action (α : Type*) (β : Type*) := (act : α → β → β) class left_action {α : Type*} {β : Type*} (s : left_action_sig α β) : Prop := intro [] :: namespace left_action variables {α : Type*} {β : Type*} (s : left_action_sig α β) abbreviation infer : left_action s := left_action.intro s definition fold : list α → β → β | [] x := x | (y::ys) x := s.act y (fold ys x) @[simp] theorem fold_nil (x) : fold s [] x = x := rfl @[simp] theorem fold_cons (x y ys) : fold s (y::ys) x = s.act y (fold s ys x) := rfl @[simp] theorem fold_append (x) : ∀ ys zs, fold s (ys ++ zs) x = fold s ys (fold s zs x) | [] zs := rfl | (y::ys) zs := show s.act y (fold s (ys ++ zs) x) = s.act y (fold s ys (fold s zs x)), by rw fold_append end left_action signature right_action (α : Type*) (β : Type*) := (act : β → α → β) class right_action {α : Type*} {β : Type*} (s : right_action_sig α β) : Prop := intro [] :: namespace right_action variables {α : Type*} {β : Type*} (s : right_action_sig α β) abbreviation infer : right_action s := right_action.intro s definition fold : β → list α → β | x [] := x | x (y::ys) := s.act (fold x ys) y @[simp] theorem fold_nil (x) : fold s x [] = x := rfl @[simp] theorem fold_cons (x y ys) : fold s x (y::ys) = s.act (fold s x ys) y := rfl @[simp] theorem fold_append (x) : ∀ ys zs, fold s x (ys ++ zs) = fold s (fold s x zs) ys | [] zs := rfl | (y::ys) zs := show s.act (fold s x (ys ++ zs)) y = s.act (fold s (fold s x zs) ys) y, by rw fold_append end right_action end algebra
6975ea8b675405e7cb15862104bc7eaaf0a34aa6
f4bff2062c030df03d65e8b69c88f79b63a359d8
/kb_solns/sets_level10.lean
1a2b7940f04cb9c317a443f981014932edf03144
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,129
lean
import data.real.basic /- # Chapter 1 : Sets ## Level 10 As a final test of your ability in working with sets, prove that the set of rational numbers is dense in the reals. This proof will, among other things, rely on several new axioms that appear in the left side bar. Note that you may need to change the type of some quantities from rationals to reals. Lean doesn't necessarily consider the rational $2$ to be the same at the real number $2$. Some of the axioms on the left make working with the casts from rationals to reals easier. -/ /- Axiom : inv_prod_self : ∀ n : ℕ, 0 < n → (1/n : ℝ) * (n : ℝ ) = 1 -/ /- Axiom : inv_prod_other : ∀ (m : ℤ), ∀ (n : ℕ), 0 < n → (1/n : ℝ) * (m : ℝ) = (m/n : ℝ) -/ /- Axiom : archimedean_R : ∀ x : ℝ, 0 < x → ∃ n : ℕ, 0 < n ∧ (1/n : ℝ) < x -/ /- Axiom : has_ceiling : ∀ x : ℝ, ∃ m : ℤ, ((m-1) : ℝ) ≤ x ∧ x < (m:ℝ) -/ -- one way to prove ℚ dense in ℝ def dense_in_R (A : set ℝ) := ∀ (x y : ℝ), x < y → ∃ a ∈ A, a ∈ set.Ioo x y def embedded_rationals : set ℝ := { x | ∃ r : ℚ, x = ↑r } -- begin hide axiom archimedean_R : ∀ x : ℝ, 0 < x → ∃ n : ℕ, 0 < n ∧ (1/n : ℝ) < x -- we might want to prove these below. Made into axioms just for ease. -- the problem is that the proofs are too hard for this level, IMO (DS) axiom has_ceiling : ∀ x : ℝ, ∃ m : ℤ, ((m-1) : ℝ) ≤ x ∧ x < (m:ℝ) axiom inv_prod_self : ∀ n : ℕ, 0 < n → (1/n : ℝ) * (n : ℝ ) = 1 axiom inv_prod_other : ∀ (m : ℤ), ∀ (n : ℕ), 0 < n → (1/n : ℝ) * (m : ℝ) = (m/n : ℝ) -- end hide /- Lemma Rationals are dense in the reals. -/ theorem rat_dense_in_R : dense_in_R embedded_rationals := begin intros x y hxy, have H := lt_trichotomy x 0, cases H with xL xr, swap, cases xr with x0 xR, -- case x = 0 rw x0 at hxy, have G := archimedean_R y hxy, cases G with n hn, cases hn with hnL hnR, use (1/n), split, existsi (1/n : ℚ), norm_num, split, swap, exact hnR, rw x0, norm_num, exact hnL, -- case 0 < x have H : 0 < y - x, linarith, have G := archimedean_R (y-x) H, cases G with n hn, cases hn with hnL hnR, have F := has_ceiling (n*x), cases F with m hm, cases hm with hmL hmR, use (m/n), split, existsi (m/n : ℚ), norm_num, have hnL1 : 0 < (n : ℝ), norm_cast, exact hnL, have hnL2 : 0 < (1/n : ℝ), exact one_div_pos_of_pos hnL1, split, exact (lt_div_iff' hnL1).mpr hmR, have h1 : (m : ℝ) ≤ n*x + 1, linarith, have h2 : (m/n : ℝ) ≤ x + (1/n : ℝ), have h21 := (mul_le_mul_left hnL2).mpr h1, rw mul_add (1/n : ℝ) _ _ at h21, rw mul_one at h21, rw ← mul_assoc at h21, have h22 := inv_prod_self n hnL, --cheating here rw h22 at h21, rw one_mul at h21, have h23 := inv_prod_other m n hnL, --and here rw h23 at h21, exact h21, have h3 : x + (1/n : ℝ) < x + (y-x), linarith, have h4 : x + (y-x) = y, norm_num, rw h4 at h3, linarith, -- case x < 0 -- reduces to the above have H : 0 < y - x, linarith, have G := archimedean_R (y-x) H, cases G with n hn, cases hn with hnL hnR, have F := has_ceiling (n*x), cases F with m hm, cases hm with hmL hmR, use (m/n), split, existsi (m/n : ℚ), norm_num, have hnL1 : 0 < (n : ℝ), norm_cast, exact hnL, have hnL2 : 0 < (1/n : ℝ), exact one_div_pos_of_pos hnL1, split, exact (lt_div_iff' hnL1).mpr hmR, have h1 : (m : ℝ) ≤ n*x + 1, linarith, have h1 : (m : ℝ) ≤ n*x + 1, linarith, have h2 : (m/n : ℝ) ≤ x + (1/n : ℝ), have h21 := (mul_le_mul_left hnL2).mpr h1, rw mul_add (1/n : ℝ) _ _ at h21, rw mul_one at h21, rw ← mul_assoc at h21, have h22 := inv_prod_self n hnL, --cheating here rw h22 at h21, rw one_mul at h21, have h23 := inv_prod_other m n hnL, --and here rw h23 at h21, exact h21, have h3 : x + (1/n : ℝ) < x + (y-x), linarith, have h4 : x + (y-x) = y, norm_num, rw h4 at h3, linarith, done end
b4ec47192e44747149dbc8613563d23ce16501c8
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/InferType.lean
14167a757ffe65851faea815358977bf5920e65f
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,230
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 (Expr × Nat) Expr Id Expr := if offset >= e.looseBVarRange then -- `e` doesn't have free variables return e else checkCache (e, 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 '{mkMVar 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 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
e10e524a5e12939f2ccf5d96e21fd056b921fa41
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Elab/Print.lean
070af7e0679e5367f4ec1e692be7357efc5c29f4
[ "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
5,721
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.Util.FoldConsts import Lean.Elab.Command namespace Lean.Elab.Command private def throwUnknownId (id : Name) : CommandElabM Unit := throwError "unknown identifier '{mkConst id}'" private def levelParamsToMessageData (levelParams : List Name) : MessageData := match levelParams with | [] => "" | u::us => do let mut m := m!".\{{u}" for u in us do m := m ++ ", " ++ toMessageData u return m ++ "}" private def mkHeader (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (safety : DefinitionSafety) : CommandElabM MessageData := do let m : MessageData := match safety with | DefinitionSafety.unsafe => "unsafe " | DefinitionSafety.partial => "partial " | DefinitionSafety.safe => "" let m := if isProtected (← getEnv) id then m ++ "protected " else m let (m, id) := match privateToUserName? id with | some id => (m ++ "private ", id) | none => (m, id) let m := m ++ kind ++ " " ++ id ++ levelParamsToMessageData levelParams ++ " : " ++ type pure m private def mkHeader' (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (isUnsafe : Bool) : CommandElabM MessageData := mkHeader kind id levelParams type (if isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe) private def printDefLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (value : Expr) (safety := DefinitionSafety.safe) : CommandElabM Unit := do let m ← mkHeader kind id levelParams type safety let m := m ++ " :=" ++ Format.line ++ value logInfo m private def printAxiomLike (kind : String) (id : Name) (levelParams : List Name) (type : Expr) (isUnsafe := false) : CommandElabM Unit := do logInfo (← mkHeader' kind id levelParams type isUnsafe) private def printQuot (kind : QuotKind) (id : Name) (levelParams : List Name) (type : Expr) : CommandElabM Unit := do printAxiomLike "Quotient primitive" id levelParams type private def printInduct (id : Name) (levelParams : List Name) (numParams : Nat) (numIndices : Nat) (type : Expr) (ctors : List Name) (isUnsafe : Bool) : CommandElabM Unit := do let mut m ← mkHeader' "inductive" id levelParams type isUnsafe m := m ++ Format.line ++ "constructors:" for ctor in ctors do let cinfo ← getConstInfo ctor m := m ++ Format.line ++ ctor ++ " : " ++ cinfo.type logInfo m private def printIdCore (id : Name) : CommandElabM Unit := do match (← getEnv).find? id with | ConstantInfo.axiomInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "axiom" id us t u | ConstantInfo.defnInfo { levelParams := us, type := t, value := v, safety := s, .. } => printDefLike "def" id us t v s | ConstantInfo.thmInfo { levelParams := us, type := t, value := v, .. } => printDefLike "theorem" id us t v | ConstantInfo.opaqueInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constant" id us t u | ConstantInfo.quotInfo { kind := kind, levelParams := us, type := t, .. } => printQuot kind id us t | ConstantInfo.ctorInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "constructor" id us t u | ConstantInfo.recInfo { levelParams := us, type := t, isUnsafe := u, .. } => printAxiomLike "recursor" id us t u | ConstantInfo.inductInfo { levelParams := us, numParams := numParams, numIndices := numIndices, type := t, ctors := ctors, isUnsafe := u, .. } => printInduct id us numParams numIndices t ctors u | none => throwUnknownId id private def printId (id : Syntax) : CommandElabM Unit := do let cs ← resolveGlobalConstWithInfos id cs.forM printIdCore @[builtinCommandElab «print»] def elabPrint : CommandElab | `(#print%$tk $id:ident) => withRef tk <| printId id | `(#print%$tk $s:strLit) => logInfoAt tk s.isStrLit?.get! | _ => throwError "invalid #print command" namespace CollectAxioms structure State where visited : NameSet := {} axioms : Array Name := #[] abbrev M := ReaderT Environment $ StateM State partial def collect (c : Name) : M Unit := do let collectExpr (e : Expr) : M Unit := e.getUsedConstants.forM collect let s ← get unless s.visited.contains c do modify fun s => { s with visited := s.visited.insert c } let env ← read match env.find? c with | some (ConstantInfo.axiomInfo _) => modify fun s => { s with axioms := s.axioms.push c } | some (ConstantInfo.defnInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.thmInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.opaqueInfo v) => collectExpr v.type *> collectExpr v.value | some (ConstantInfo.quotInfo _) => pure () | some (ConstantInfo.ctorInfo v) => collectExpr v.type | some (ConstantInfo.recInfo v) => collectExpr v.type | some (ConstantInfo.inductInfo v) => collectExpr v.type *> v.ctors.forM collect | none => pure () end CollectAxioms private def printAxiomsOf (constName : Name) : CommandElabM Unit := do let env ← getEnv let (_, s) := ((CollectAxioms.collect constName).run env).run {} if s.axioms.isEmpty then logInfo m!"'{constName}' does not depend on any axioms" else logInfo m!"'{constName}' depends on axioms: {s.axioms.toList}" @[builtinCommandElab «printAxioms»] def elabPrintAxioms : CommandElab | `(#print%$tk axioms $id) => withRef tk do let cs ← resolveGlobalConstWithInfos id cs.forM printAxiomsOf | _ => throwUnsupportedSyntax end Lean.Elab.Command
66a7ed9a87168a42cf7d05c3182bc4f4c0248533
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/eq25.lean
6ec2f1648c9d2a125705438f9787df0873e62ed1
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
152
lean
inductive N := | O : N | S : N → N definition Nat := N open N definition add : Nat → Nat → Nat | add O b := b | add (S a) b := S (add a b)
9573608159f1e02e9025ce732d8f01e2818346c3
883eaea6bef0d3c38f46c45d3454e0af631a6e61
/src/inClassNotes/langs/imp.lean
36a94416d01a366a38a71b0512cbbf43f2841dbb
[]
no_license
hannahbrooke720/complogic-s21
bd3c4981cfeb8642654d83ce874a5c50a3077948
3f4098b174c54e1699a07222662ffec7e14223f2
refs/heads/master
1,681,504,336,289
1,620,140,677,000
1,620,140,677,000
335,838,993
0
0
null
1,620,140,678,000
1,612,413,391,000
Lean
UTF-8
Lean
false
false
5,043
lean
import .arith_expr import .bool_expr /- A little PL in which we have mutable state and an update (assignment) operation. -/ /- We don't have mutable state in a pure functional language -/ def x := 1 -- def x := 2 -- structure avar : Type := (idx : nat) def X := avar.mk 0 def Y := avar.mk 1 def Z := avar.mk 2 def init : a_state := λ (v : avar), 0 /- { (X,0), (Y,0), (Z,0), ... } st X = 7; { (X,7), (Y,0), (Z,0), ... } st' Y = 8 { (X,7), (Y,8), (Z,0), ... } st'' Z = 9 { (X,7), (Y,8), (Z,9), ... } st''' X = 10 { (X,10), (Y,8), (Z,9), ... } st''' Π (v : avar), if v = X then st' v = 7 else st' v = st v -/ def var_eq : avar → avar → bool | (avar.mk n1) (avar.mk n2) := n1 = n2 def override : a_state → avar → aexp → a_state | st v exp := λ (v' : avar), if (var_eq v v') then (aeval exp st) else (st v') def st' := override init X [7] #eval st' X #eval st' Y #eval st' Z def st'' := override st' Y [8] #eval st'' X #eval st'' Y #eval st'' Z def st''' := override st'' Z [9] #eval st''' X #eval st''' Y #eval st''' Z def st'''' := override st''' X [10] #eval st'''' X #eval st'''' Y #eval st'''' Z inductive cmd : Type | skip | assn (v : avar) (e : aexp) | seq (c1 c2 : cmd) : cmd -- | cond (b : bool_expr) (c1 c2 : cmd) : cmd -- | while (b : bool_expr) (c : cmd) : cmd open cmd notation v = a := assn v a notation c1 ; c2 := seq c1 c2 def a1 : cmd := X = [7] def a2 := Y = [8] def a3 := Z = [9] def a4 := X = [10] def program : cmd := -- a1; a2; a3; a4 X = [7]; Y = [8]; Z = [9]; X = [10] def c_eval : cmd → a_state → a_state | skip st := st | (v = e) st := override st v e | (c1 ; c2) st := c_eval c2 (c_eval c1 st) /- We implement assignment using function override, converting a given (initial) state into a new state by binding a given variable to the value of a given arithmetic expression. We implement sequential composition of c1 and c2 by evaluating c2 in the state obtained by evaluating c1 in the given (initial) state. Note that c1 and c2 can each themselves be complex programs (in our little language). -/ def res := c_eval program init #reduce res X #reduce res Y #reduce res Z -- Yay! inductive c_sem : cmd → a_state → a_state → Prop | c_sem_skip : ∀ (st : a_state), c_sem skip st st | c_sem_assm : ∀ (pre post : a_state) (v : avar) (e : aexp), (override pre v e = post) → c_sem (v = e) pre post | c_sem_seq : ∀ (pre is post : a_state) (c1 c2 : cmd), c_sem c1 pre is → c_sem c2 is post → c_sem (c1 ; c2) pre post /- {pre} (c1 {is} c2) {post} -/ -- proof broken because we added skip at end of "program" theorem t1 : ∀ (post : a_state), c_sem program init post → post X = 10 := begin assume post, assume h, unfold program at h, cases h, cases h_ᾰ_1, rw <- h_ᾰ_1_ᾰ, apply rfl, end /- -- here we fix it theorem t2 : ∀ (post : a_state), c_sem program init post → post X = 10 := begin assume post, assume h, unfold program at h, cases h, cases h_ᾰ_1, cases h_ᾰ, cases h_ᾰ_ᾰ_1,86/ rw <- h_ᾰ_ᾰ_1_ᾰ, apply rfl, end -/ -- program broken because we added skip at end of "program" -- homework: you fix it example : ∀ (post : a_state), c_sem program init post → post Z = 9 := begin assume post, assume h, unfold program at h, cases h, cases h_ᾰ, cases h_ᾰ_ᾰ_1, cases h_ᾰ_1, rw <- h_ᾰ_1_ᾰ, rw <- h_ᾰ_ᾰ_1_ᾰ, apply rfl, end /- SPECIFICATION AND VERIFICATION -/ def Assertion := a_state → Prop /- Write an assertion that specifies the set of states in which X = 10 -/ def pre1 : Assertion := λ (st : a_state), st X = 10 /- An assertion that's satisfied by any state -/ def any : Assertion := λ (st : a_state), true /- Pre: X = 10 or Y = 8 -/ def pre2 : Assertion := λ (st : a_state), st X = 10 ∨ st Y = 8 def plus4 := λ (n : nat), 4 + n #eval plus4 7 -- 4 + 7 -- 11 /- {X = 10, Y =2, Z = 9} {X = 3, Y = 8, Z = 0} -/ /- res : state -- {X = 10, Y = 8, Z = 9} -/ /- pre2 res res X = 10 ∨ res Y = 8 -/ example : pre2 res := begin unfold pre2, apply or.inr, apply rfl, end /- What does it mean for a program, C, to satisfy a pre/post specification? -/ -- remember: Assertion def satisfies (c : cmd) (pre post : Assertion) := ∀ (st st' : a_state), pre st → c_sem c st st' → post st' notation pre {c} post := satisfies c pre post -- Hoare triple def prog2 := X = [10] lemma foo : satisfies prog2 any (λ st : a_state, st X = 10) := begin unfold satisfies, assume st st', assume trivial h, unfold prog2 at h, cases h, rw <- h_ᾰ, exact rfl, end example : ∀ (n m k : nat), m = n → k = m → n = k := begin intros n m k, assume h1 h2, rw <- h1, rw h2, end example : any { prog2 } (λ st' : a_state, st' X = 10 ∨ st' Y = 9) := begin unfold satisfies, -- COMPLETE THIS PROOF end
30943507544142f69ead85e5b997bdddf96e68b3
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/data/finsupp.lean
d2ad9e494f6f703bc36b2642eb76a6de430140fc
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
28,843
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 Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * ℕ →₀ α: Polynomials (where α is a ring) * (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names) * α →₀ ℕ: Multisets * α →₀ ℤ: Abelian groups freely generated by α * β →₀ α: Linear combinations over β where α is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use α →₀ β directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module open finset reserve infix ` →₀ `:25 universes u u₁ u₂ v v₁ v₂ v₃ w x y namespace finset variables {α : Type u} [decidable_eq α] protected def subtype (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.image $ λ⟨a, ha⟩, ⟨a, (mem_filter.1 ha).2⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] end finset /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type u) (β : Type v) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infix →₀ := finsupp namespace finsupp variables {α : Type u} {β : Type v} {γ : Type w} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), by simp⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff (f : α →₀ β) : ∀a:α, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[extensionality] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { simp [finset.ext, hf, hg] }, subst this end @[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by simp [finset.ext] at h; exact h a, by simp {contextual:=tt}⟩ instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨set.fintype_of_finset f.support f.mem_support_iff⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp [set.subset_def]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) end basic section single variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨(if b = 0 then ∅ else {a}), (λa', if a = a' then b else 0), begin intro a', by_cases hb : b = 0; by_cases a = a'; simp [h, hb], simp [ne.symm h, h] end⟩ lemma single_apply : (single a b : α →₀ β) a' = (if a = a' then b else 0) := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := by simp [single_apply] @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := by simp [single_apply, h] @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := by by_cases b = 0; simp [support_single_ne_zero, h] end single section on_finset variables [decidable_eq β] [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by simp [h]) (assume h : f a ≠ 0, by simp [h, hf])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := by simp [on_finset] end on_finset section map_range variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; simp [hf] {contextual := tt} @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset variables [decidable_eq α] [decidable_eq β₁] @[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} : map_range f hf (single a b) = single a (f b) := finsupp.ext $ λ a', by by_cases a = a'; [{subst a', simp}, simp [h, hf]] end map_range section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ assume a, classical.by_cases (assume h : g₁ a = 0, by simp [h]; rw [not_imp_not]; simp [hf] {contextual := tt}) (assume h : g₁ a ≠ 0, by simp [h]) @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with section erase variables [decidable_eq α] [decidable_eq β] def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by by_cases a' = a; simp [h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.sum (λa, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive finsupp.sum] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.prod (λa, g a (f a)) attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1 @[to_additive finsupp.sum_map_range_index] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ by simp [h0] {contextual := tt} @[to_additive finsupp.sum_zero_index] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := by simp [finsupp.prod] section decidable variables [decidable_eq α] [decidable_eq β] section add_monoid variables [add_monoid β] @[to_additive finsupp.sum_single_index] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [finsupp.prod, support_single_ne_zero h] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp else by simp [ne.symm h, h] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp else by simp [ne.symm h, h] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (by simp [h0] {contextual := tt}) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { simp }, { rw [← mem_support_iff _ a, hf], simp }, { apply ih _ _, simp [hf, has, finset.erase_insert] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (by simp [h0] {contextual := tt}) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { simp }, { rw [← mem_support_iff _ a, hf], simp }, { apply ih _ _, simp [hf, has, finset.erase_insert] } end end add_monoid instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } @[to_additive finsupp.sum_neg_index] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : by simp ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (finset.sum_hom (λf : α →₀ β, f a₂) rfl (assume a b, rfl)).symm lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, (f.mem_support_iff a).mp ha, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero {γ : Type w} [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add {γ : Type w} [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg {γ : Type w} [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) neg_zero (assume a b, neg_add _ _) @[simp] lemma sum_single [add_comm_monoid β] {f : α →₀ β} : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ({a} : finset α).sum (λa', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset α) ⊆ f.support, { simp [finset.subset_iff, *] at * }, refine (finset.sum_subset this _).symm, simp {contextual := tt} }, { transitivity (f.support.sum (λa, (0 : β))), { refine (finset.sum_congr rfl _), intros a' ha', have h: a' ≠ a, { assume eq, simp * at * }, simp * at * }, { simp * at * } } end, ext $ assume a, by simp [single_apply, this] @[to_additive finsupp.sum_add_index] lemma prod_add_index {γ : Type w} [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h, from (finset.prod_subset finset.subset_union_left $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h, from (finset.prod_subset finset.subset_union_right $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (λa, h a ((f + g) a)) = (f.support ∪ g.support).prod (λa, h a ((f + g) a)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support ∪ g.support).prod (λa, h a (f a)) * (f.support ∪ g.support).prod (λa, h a (g a)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index {γ : Type w} [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa [h_zero] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa [h_neg] using this, calc (f - g).sum h = (f + - g).sum h : by simp ... = f.sum h + - g.sum h : by simp [sum_add_index, sum_neg_index, h_add, h_zero, h_neg] ... = _ : by simp @[to_additive finsupp.sum_finset_sum_index] lemma prod_finset_sum_index {γ : Type w} {ι : Type x} [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive finsupp.sum_sum_index] lemma prod_sum_index {γ : Type w} [decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm section map_domain variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_id : map_domain id v = v := sum_single lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := by simp [map_domain, sum_sum_index, sum_single_index] lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index (by simp) lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ by simp [*] at * {contextual := tt} lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (by simp) (by simp) lemma map_domain_finset_sum {ι : Type x} [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) := by refine (sum_finset_sum_index _ _).symm; simp lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := by refine (sum_finset_sum_index _ _).symm; simp lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive finsupp.sum_map_domain_index] lemma prod_map_domain_index {γ : Type w} [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by simp [map_domain, prod_sum_index, h_zero, h_add, prod_single_index] end map_domain /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the monoid of monomial exponents.) -/ instance [has_add α] [semiring β] : has_mul (α →₀ β) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) := ⟨single 0 1⟩ lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl section filter -- TODO: remove filter? build upon subtype_domain? section has_zero variables [has_zero β] {p : α → Prop} [decidable_pred p] {f : α →₀ β} /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) (assume a, by by_cases (p a); simp [h]) @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, by by_cases p a; simp * end has_zero lemma filter_pos_add_filter_neg [add_monoid β] {f : α →₀ β} {p : α → Prop} [decidable_pred p] [decidable_pred (λa, ¬ p a)] : f.filter p + f.filter (λa, ¬ p a) = f := finsupp.ext $ assume a, by by_cases p a; simp * end filter section subtype_domain variables {α' : Type u₁} {δ : Type y} [has_zero δ] {p : α → Prop} [decidable_pred p] section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, by simp⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive finsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (begin simp; exact assume b hb, ⟨b, hp _ (by simp [hb]), by simp [hb]⟩ end) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ by simp end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _ subtype_domain_zero $ assume v v', subtype_domain_add) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ by simp @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ by simp end group end subtype_domain section variables [add_monoid α] [semiring β] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp [mul_def, sum_zero_index] private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp [mul_def, sum_zero_index] private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c := by simp [mul_def, sum_add_index, mul_add] private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c := by simp [mul_def, sum_add_index, add_mul] def to_semiring : semiring (α →₀ β) := { one := 1, mul := (*), one_mul := assume f, by simp [mul_def, one_def, sum_single_index], mul_one := assume f, by simp [mul_def, one_def, sum_single_index], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, add_mul, mul_add, mul_assoc], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end local attribute [instance] to_semiring def to_comm_semiring [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) := { mul_comm := assume f g, begin simp [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp end, .. finsupp.to_semiring } local attribute [instance] to_comm_semiring def to_ring [add_monoid α] [ring β] : ring (α →₀ β) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.to_semiring } def to_comm_ring [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) := { mul_comm := mul_comm, .. finsupp.to_ring} lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}: single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := by simp [mul_def, sum_single_index] lemma prod_single {ι : Type x} [decidable_eq ι] [add_comm_monoid α] [comm_semiring β] {s : finset ι} {a : ι → α} {b : ι → β} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s (by simp [one_def]) (by simp [single_mul_single] {contextual := tt}) section variable (β) def to_has_scalar' [ring γ] [module γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero)⟩ local attribute [instance] to_has_scalar' @[simp] lemma smul_apply' [ring γ] [module γ β] {a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) := rfl def to_module [ring γ] [module γ β] : module γ (α →₀ β) := { smul := (•), smul_add := assume a x y, finsupp.ext $ by simp [smul_add], add_smul := assume a x y, finsupp.ext $ by simp [add_smul], one_smul := assume x, finsupp.ext $ by simp, mul_smul := assume r s x, finsupp.ext $ by simp [smul_smul], .. finsupp.add_comm_group } end def to_has_scalar [ring β] : has_scalar β (α →₀ β) := to_has_scalar' β local attribute [instance] to_has_scalar @[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b • (v a) := rfl lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 end decidable section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp [finsupp.sum, finset.sum_mul] lemma mul_sum [semiring β] [semiring γ] (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp [finsupp.sum, finset.mul_sum] end end finsupp
1648866fb2cc40c93b3a2ab72eb45201eeedf015
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/multiset/basic.lean
8be28fdcbfbed825681ec2ee95b16fda567886b7
[ "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
94,879
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.bool.all_any import data.list.perm /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /-! ### Empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance inhabited_multiset : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl @[simp] theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /-! ### `multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a ::ₘ l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) /-- Companion to `multiset.rec` with more convenient argument order. -/ @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)} {C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end lemma empty_or_exists_mem (s : multiset α) : s = 0 ∨ ∃ a, a ∈ s := or_iff_not_imp_left.mpr multiset.exists_mem_of_ne_zero @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs], have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /-! ### Singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ theorem singleton_eq_cons (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : multiset α) ↔ b = a := by simp only [singleton_eq_cons, mem_cons, iff_self, or_false, not_mem_zero] theorem mem_singleton_self (a : α) : a ∈ ({a} : multiset α) := by { rw singleton_eq_cons, exact mem_cons_self _ _ } theorem singleton_inj {a b : α} : ({a} : multiset α) = {b} ↔ a = b := by { simp_rw [singleton_eq_cons], exact cons_inj_left _ } theorem pair_comm (x y : α) : ({x, y} : multiset α) = {y, x} := cons_swap x y 0 /-! ### `multiset.subset` -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ instance : has_ssubset (multiset α) := ⟨λ s t, s ⊆ t ∧ ¬ t ⊆ s⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim lemma subset_cons (s : multiset α) (a : α) : s ⊆ a ::ₘ s := λ _, mem_cons_of_mem lemma ssubset_cons {s : multiset α} {a : α} (ha : a ∉ s) : s ⊂ a ::ₘ s := ⟨subset_cons _ _, λ h, ha $ h $ mem_cons_self _ _⟩ @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] lemma cons_subset_cons {a : α} {s t : multiset α} : s ⊆ t → a ::ₘ s ⊆ a ::ₘ t := quotient.induction_on₂ s t $ λ _ _, cons_subset_cons _ theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ lemma induction_on' {p : multiset α → Prop} (S : multiset α) (h₁ : p 0) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S := @multiset.induction_on α (λ T, T ⊆ S → p T) S (λ _, h₁) (λ a s hps hs, let ⟨hS, sS⟩ := cons_subset.1 hs in h₂ hS sS (hps sS)) (subset.refl S) end subset /-! ### `multiset.to_list` -/ section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) @[simp, norm_cast] lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) @[simp] lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /-! ### Partial order on `multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } section variables {s t : multiset α} {a : α} lemma subset_of_le : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset alias subset_of_le ← le.subset lemma mem_of_le (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) lemma not_mem_mono (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ @h _ @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm instance : order_bot (multiset α) := ⟨0, zero_le⟩ /-- This is a `rfl` and `simp` version of `bot_eq_zero`. -/ @[simp] theorem bot_eq_zero : (⊥ : multiset α) = 0 := rfl lemma le_zero : s ≤ 0 ↔ s = 0 := le_bot_iff theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt $ lt_cons_self _ _ lemma cons_le_cons_iff (a : α) : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a lemma cons_le_cons (a : α) : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 lemma le_cons_of_not_mem (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end @[simp] theorem singleton_ne_zero (a : α) : ({a} : multiset α) ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : {a} ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ end /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl theorem singleton_add (a : α) (s : multiset α) : {a} + s = a ::ₘ s := rfl private theorem add_le_add_iff_left' {s t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ instance : covariant_class (multiset α) (multiset α) (+) (≤) := ⟨λ s t u, add_le_add_iff_left'.2⟩ instance : contravariant_class (multiset α) (multiset α) (+) (≤) := ⟨λ s t u, add_le_add_iff_left'.1⟩ instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := λ s t, quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := λ s, quot.induction_on s $ λ l, rfl, add_zero := λ s, quotient.induction_on s $ λ l, congr_arg coe $ append_nil l, add_left_cancel := λ a b c, add_left_cancel'', add_le_add_left := λ s₁ s₂, add_le_add_left, le_of_add_le_add_left := λ s₁ s₂ s₃, le_of_add_le_add_left, ..@multiset.partial_order α } theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩ instance : canonically_ordered_add_monoid (multiset α) := { le_self_add := le_add_right, exists_add_of_le := λ a b h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, ..multiset.order_bot, ..multiset.ordered_cancel_add_comm_monoid } @[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append lemma mem_of_mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h : a ∈ n • s) : a ∈ s := begin induction n with n ih, { rw zero_nsmul at h, exact absurd h (not_mem_zero _) }, { rw [succ_nsmul, mem_add] at h, exact h.elim id ih }, end @[simp] lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n • s ↔ a ∈ s := begin refine ⟨mem_of_mem_nsmul, λ h, _⟩, obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero h0, rw [succ_nsmul, mem_add], exact or.inl h end lemma nsmul_cons {s : multiset α} (n : ℕ) (a : α) : n • (a ::ₘ s) = n • {a} + n • s := by rw [←singleton_add, nsmul_add] /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card : multiset α →+ ℕ := { to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq, map_zero' := rfl, map_add' := λ s t, quotient.induction_on₂ s t length_append } @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl theorem card_add (s t : multiset α) : card (s + t) = card s + card t := card.map_add s t lemma card_nsmul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by rw [card.map_nsmul s n, nat.nsmul_eq_mul] @[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card ({a} : multiset α) = 1 := by simp only [singleton_eq_cons, card_zero, eq_self_iff_true, zero_add, card_cons] lemma card_pair (a b : α) : ({a, b} : multiset α).card = 2 := by rw [insert_eq_cons, card_cons, card_singleton] theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = {a} := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist @[mono] theorem card_mono : monotone (@card α) := λ a b, card_le_of_le theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem lemma card_eq_two {s : multiset α} : s.card = 2 ↔ ∃ x y, s = {x, y} := ⟨quot.induction_on s (λ l h, (list.length_eq_two.mp h).imp (λ a, Exists.imp (λ b, congr_arg coe))), λ ⟨a, b, e⟩, e.symm ▸ rfl⟩ lemma card_eq_three {s : multiset α} : s.card = 3 ↔ ∃ x y z, s = {x, y, z} := ⟨quot.induction_on s (λ l h, (list.length_eq_three.mp h).imp (λ a, Exists.imp (λ b, Exists.imp (λ c, congr_arg coe)))), λ ⟨a, b, c, e⟩, e.symm ▸ rfl⟩ /-! ### Induction principles -/ /-- A strong induction principle for multisets: If you construct a value for a particular multiset given values for all strictly smaller multisets, you can construct a value for any multiset. -/ @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all multisets `s` of cardinality less than `n`, starting from multisets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strong_downward_induction {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ (s : multiset α), s.card ≤ n → p s | s := H s (λ t ht h, have n - card t < n - card s, from (tsub_lt_tsub_iff_left_of_le ht).2 (card_lt_of_lt h), strong_downward_induction t ht) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : multiset α), n - t.card)⟩]} lemma strong_downward_induction_eq {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : multiset α) : strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) := by rw strong_downward_induction /-- Analogue of `strong_downward_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_downward_induction_on {p : multiset α → Sort*} {n : ℕ} : ∀ (s : multiset α), (∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) → s.card ≤ n → p s := λ s H, strong_downward_induction H s lemma strong_downward_induction_on_eq {p : multiset α → Sort*} (s : multiset α) {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) := by { dunfold strong_downward_induction_on, rw strong_downward_induction } /-- Another way of expressing `strong_induction_on`: the `(<)` relation is well-founded. -/ lemma well_founded_lt : well_founded ((<) : multiset α → multiset α → Prop) := subrelation.wf (λ _ _, multiset.card_lt_of_lt) (measure_wf multiset.card) /-! ### `multiset.repeat` -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = {a} := by simp only [repeat_succ, singleton_eq_cons, eq_self_iff_true, repeat_zero, cons_inj_right] @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat lemma mem_repeat {a b : α} {n : ℕ} : b ∈ repeat a n ↔ n ≠ 0 ∧ b = a := mem_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) : function.injective (λ a : α, repeat a n) := λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩ @[simp] lemma repeat_left_inj {a b : α} {n : ℕ} (h : n ≠ 0) : repeat a n = repeat b n ↔ a = b := (repeat_left_injective h).eq_iff theorem repeat_injective (a : α) : function.injective (repeat a) := λ m n h, by rw [← (eq_repeat.1 h).1, card_repeat] theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ {a} := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ theorem nsmul_singleton (a : α) (n) : n • ({a} : multiset α) = repeat a n := begin refine eq_repeat.mpr ⟨_, λ b hb, mem_singleton.mp (mem_of_mem_nsmul hb)⟩, rw [card_nsmul, card_singleton, mul_one] end lemma nsmul_repeat {a : α} (n m : ℕ) : n • (repeat a m) = repeat a (n * m) := begin rw eq_repeat, split, { rw [card_nsmul, card_repeat] }, { exact λ b hb, eq_of_mem_repeat (mem_of_mem_nsmul hb) }, end /-! ### Erasing one copy of an element -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_singleton (a : α) : ({a} : multiset α).erase a = 0 := erase_cons_head a 0 @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self lemma add_singleton_eq_iff {s t : multiset α} {a : α} : s + {a} = t ↔ a ∈ t ∧ s = t.erase a := begin rw [add_comm, singleton_add], split, { rintro rfl, exact ⟨s.mem_cons_self a, (s.erase_cons_head a).symm⟩ }, { rintro ⟨h, rfl⟩, exact cons_erase h }, end theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem @[simp] lemma card_erase_add_one {a : α} {s : multiset α} : a ∈ s → (s.erase a).card + 1 = s.card := quot.induction_on s $ λ l, length_erase_add_one theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) theorem card_erase_eq_ite {a : α} {s : multiset α} : card (s.erase a) = if a ∈ s then pred (card s) else card s := begin by_cases h : a ∈ s, { rwa [card_erase_of_mem h, if_pos] }, { rwa [erase_of_not_mem h, if_neg] } end end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /-! ### `multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) @[congr] theorem map_congr {f g : α → β} {s t : multiset α} : s = t → (∀ x ∈ t, f x = g x) → map f s = map g t := begin rintros rfl h, induction s using quot.induction_on, exact congr_arg coe (map_congr h) end lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr rfl hf] end theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s $ λ l, rfl theorem map_comp_cons (f : α → β) (t) : map f ∘ cons t = cons (f t) ∘ map f := by { ext, simp } @[simp] theorem map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ /-- If each element of `s : multiset α` can be lifted to `β`, then `s` can be lifted to `multiset β`. -/ instance [can_lift α β] : can_lift (multiset α) (multiset β) := { cond := λ s, ∀ x ∈ s, can_lift.cond β x, coe := map can_lift.coe, prf := by { rintro ⟨l⟩ hl, lift l to list β using hl, exact ⟨l, coe_map _ _⟩ } } /-- `multiset.map` as an `add_monoid_hom`. -/ def map_add_monoid_hom (f : α → β) : multiset α →+ multiset β := { to_fun := map f, map_zero' := map_zero _, map_add' := map_add _ } @[simp] lemma coe_map_add_monoid_hom (f : α → β) : (map_add_monoid_hom f : multiset α → multiset β) = map f := rfl theorem map_nsmul (f : α → β) (n : ℕ) (s) : map f (n • s) = n • (map f s) := (map_add_monoid_hom f).map_nsmul _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ lemma map_eq_singleton {f : α → β} {s : multiset α} {b : β} : map f s = {b} ↔ ∃ a : α, s = {a} ∧ f a = b := begin split, { intro h, obtain ⟨a, ha⟩ : ∃ a, s = {a}, { rw [←card_eq_one, ←card_map, h, card_singleton] }, refine ⟨a, ha, _⟩, rw [←mem_singleton, ←h, ha, map_singleton, mem_singleton] }, { rintro ⟨a, rfl, rfl⟩, simp } end lemma map_eq_cons [decidable_eq α] (f : α → β) (s : multiset α) (t : multiset β) (b : β) : (∃ a ∈ s, f a = b ∧ (s.erase a).map f = t) ↔ s.map f = b ::ₘ t := begin split, { rintro ⟨a, ha, rfl, rfl⟩, rw [←map_cons, multiset.cons_erase ha] }, { intro h, have : b ∈ s.map f, { rw h, exact mem_cons_self _ _ }, obtain ⟨a, h1, rfl⟩ := mem_map.mp this, obtain ⟨u, rfl⟩ := exists_cons_of_mem h1, rw [map_cons, cons_inj_right] at h, refine ⟨a, mem_cons_self _ _, rfl, _⟩, rw [multiset.erase_cons_head, h] } end theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] lemma map_lt_map {f : α → β} {s t : multiset α} (h : s < t) : s.map f < t.map f := begin refine (map_le_map h.le).lt_of_not_le (λ H, h.ne $ eq_of_le_of_card_le h.le _), rw [←s.card_map f, ←t.card_map f], exact card_le_of_le H, end lemma map_mono (f : α → β) : monotone (map f) := λ _ _, map_le_map lemma map_strict_mono (f : α → β) : strict_mono (map f) := λ _ _, map_lt_map @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ lemma map_erase [decidable_eq α] [decidable_eq β] (f : α → β) (hf : function.injective f) (x : α) (s : multiset α) : (s.erase x).map f = (s.map f).erase (f x) := begin induction s using multiset.induction_on with y s ih, { simp }, by_cases hxy : y = x, { cases hxy, simp }, { rw [s.erase_cons_tail hxy, map_cons, map_cons, (s.map f).erase_cons_tail (hf.ne hxy), ih] } end lemma map_surjective_of_surjective {f : α → β} (hf : function.surjective f) : function.surjective (map f) := begin intro s, induction s using multiset.induction_on with x s ih, { exact ⟨0, map_zero _⟩ }, { obtain ⟨y, rfl⟩ := hf x, obtain ⟨t, rfl⟩ := ih, exact ⟨y ::ₘ t, map_cons _ _ _⟩ } end /-! ### `multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_singleton (f : α → β → β) (H b a) : foldr f H b ({a} : multiset α) = f a b := rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm lemma foldr_induction' (f : α → β → β) (H : left_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldr f H x s) := begin revert s, refine multiset.induction (by simp [px]) _, intros a s hs hsa, rw foldr_cons, have hps : ∀ (x : α), x ∈ s → q x, from λ x hxs, hsa x (mem_cons_of_mem hxs), exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps), end lemma foldr_induction (f : α → α → α) (H : left_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldr f H x s) := foldr_induction' f H x p p s p_f px p_s lemma foldl_induction' (f : β → α → β) (H : right_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldl f H x s) := begin rw foldl_swap, exact foldr_induction' (λ x y, f y x) (λ x y z, (H _ _ _).symm) x q p s hpqf px q_s, end lemma foldl_induction (f : α → α → α) (H : right_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldl f H x s) := foldl_induction' f H x p p s p_f px p_s /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} /-- If `p` is a decidable predicate, so is the predicate that all elements of a multiset satisfy `p`. -/ protected def decidable_forall_multiset {p : α → Prop} [hp : ∀ a, decidable (p a)] : decidable (∀ a ∈ m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a ∈ l, p a) $ by simp) instance decidable_dforall_multiset {p : Π a ∈ m, Prop} [hp : ∀ a (h : a ∈ m), decidable (p a h)] : decidable (∀ a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀ a, decidable_eq (β a)] : decidable_eq (Π a ∈ m, β a) := assume f g, decidable_of_iff (∀ a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) /-- If `p` is a decidable predicate, so is the existence of an element in a multiset satisfying `p`. -/ protected def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∃ a ∈ l, p a) $ by simp) instance decidable_dexists_multiset {p : Π a ∈ m, Prop} [hp : ∀ a (h : a ∈ m), decidable (p a h)] : decidable (∃ a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /-! ### Subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a` (note that it is truncated subtraction, so it is `0` if `count a t ≥ count a s`). -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl /-- This is a special case of `tsub_zero`, which should be used instead of this. This is needed to prove `has_ordered_sub (multiset α)`. -/ protected theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ /-- This is a special case of `tsub_le_iff_right`, which should be used instead of this. This is needed to prove `has_ordered_sub (multiset α)`. -/ protected theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp [multiset.sub_zero]) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) instance : has_ordered_sub (multiset α) := ⟨λ n m k, multiset.sub_le_iff_le_add⟩ lemma cons_sub_of_le (a : α) {s t : multiset α} (h : t ≤ s) : a ::ₘ s - t = a ::ₘ (s - t) := by rw [←singleton_add, ←singleton_add, add_tsub_assoc_of_le h] theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (tsub_eq_of_eq_add_rev $ by rw [add_comm, ← card_add, tsub_add_cancel_of_le h]).symm /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_tsub_add theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := tsub_add_cancel_of_le theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (tsub_le_tsub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le tsub_le_self), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, tsub_add_eq_tsub_tsub, add_tsub_cancel_right] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) := by simpa using add_union_distrib (a ::ₘ 0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, tsub_add_cancel_of_le (inter_le_left s t)] end /-! ### `multiset.filter` -/ section variables (p : α → Prop) [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero : filter p 0 = 0 := rfl lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr' h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ _ theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (h.filter p).subperm lemma monotone_filter_left : monotone (filter p) := λ s t, filter_le_filter p lemma monotone_filter_right (s : multiset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := quotient.induction_on s (λ l, (l.monotone_filter_right h).subperm) variable {p} @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩ theorem filter_cons {a : α} (s : multiset α) : filter p (a ::ₘ s) = (if p a then {a} else 0) + filter p s := begin split_ifs with h, { rw [filter_cons_of_pos _ h, singleton_add] }, { rw [filter_cons_of_neg _ h, zero_add] }, end lemma filter_singleton {a : α} (p : α → Prop) [decidable_pred p] : filter p {a} = if p a then {a} else ∅ := by simp only [singleton, filter_cons, filter_zero, add_zero, empty_eq_zero] lemma filter_nsmul (s : multiset α) (n : ℕ) : filter p (n • s) = n • filter p s := begin refine s.induction_on _ _, { simp only [filter_zero, nsmul_zero] }, { intros a ha ih, rw [nsmul_cons, filter_add, ih, filter_cons, nsmul_add], congr, split_ifs with hp; { simp only [filter_eq_self, nsmul_zero, filter_eq_nil], intros b hb, rwa (mem_singleton.mp (mem_of_mem_nsmul hb)) } } end variable (p) @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter _ $ inter_le_left _ _) (filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _ _) (filter_le _ _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] theorem map_filter (f : β → α) (s : multiset β) : filter p (map f s) = map f (filter (p ∘ f) s) := quot.induction_on s (λ l, by simp [map_filter]) /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero : countp p 0 = 0 := rfl variable {p} @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s $ countp_cons_of_pos p @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s $ countp_cons_of_neg p variable (p) theorem countp_cons (b : α) (s) : countp p (b ::ₘ s) = countp p s + (if p b then 1 else 0) := quot.induction_on s $ by simp [list.countp_cons] theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, l.countp_eq_length_filter p theorem countp_le_card (s) : countp p s ≤ card s := quot.induction_on s $ λ l, countp_le_length p @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] @[simp] theorem countp_nsmul (s) (n : ℕ) : countp p (n • s) = n * countp p s := by induction n; simp [*, succ_nsmul', succ_mul, zero_nsmul] theorem card_eq_countp_add_countp (s) : card s = countp p s + countp (λ x, ¬ p x) s := quot.induction_on s $ λ l, by simp [l.length_eq_countp_add_countp p] /-- `countp p`, the number of elements of a multiset satisfying `p`, promoted to an `add_monoid_hom`. -/ def countp_add_monoid_hom : multiset α →+ ℕ := { to_fun := countp p, map_zero' := countp_zero _, map_add' := countp_add _ } @[simp] lemma coe_countp_add_monoid_hom : (countp_add_monoid_hom p : multiset α → ℕ) = countp p := rfl @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h) @[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] theorem countp_eq_countp_filter_add (s) (p q : α → Prop) [decidable_pred p] [decidable_pred q] : countp p s = (filter q s).countp p + (filter (λ a, ¬ q a) s).countp p := quot.induction_on s $ λ l, l.countp_eq_countp_filter_add _ _ @[simp] lemma countp_true {s : multiset α} : countp (λ _, true) s = card s := quot.induction_on s $ λ l, list.countp_true @[simp] lemma countp_false {s : multiset α} : countp (λ _, false) s = 0 := quot.induction_on s $ λ l, list.countp_false theorem countp_map (f : α → β) (s : multiset α) (p : β → Prop) [decidable_pred p] : countp p (map f s) = (s.filter (λ a, p (f a))).card := begin refine multiset.induction_on s _ (λ a t IH, _), { rw [map_zero, countp_zero, filter_zero, card_zero] }, { rw [map_cons, countp_cons, IH, filter_cons, card_add, apply_ite card, card_zero, card_singleton, add_comm] }, end variable {p} theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := quot.induction_on s $ λ l, list.countp_pos p theorem countp_eq_zero {s} : countp p s = 0 ↔ ∀ a ∈ s, ¬ p a := quot.induction_on s $ λ l, list.countp_eq_zero p theorem countp_eq_card {s} : countp p s = card s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, list.countp_eq_length p theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_congr {s s' : multiset α} (hs : s = s') {p p' : α → Prop} [decidable_pred p] [decidable_pred p'] (hp : ∀ x ∈ s, p x = p' x) : s.countp p = s'.countp p' := quot.induction_on₂ s s' (λ l l' hs hp, begin simp only [quot_mk_to_coe'', coe_eq_coe] at hs, exact hs.countp_congr hp, end) hs hp end /-! ### Multiplicity of an element -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ h theorem count_le_card (a : α) (s) : count a s ≤ card s := countp_le_card _ _ theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le _ theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) theorem count_cons (a b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) := countp_cons _ _ _ @[simp] theorem count_singleton_self (a : α) : count a ({a} : multiset α) = 1 := by simp only [count_cons_self, singleton_eq_cons, eq_self_iff_true, count_zero] theorem count_singleton (a b : α) : count a ({b} : multiset α) = if a = b then 1 else 0 := by simp only [count_cons, singleton_eq_cons, count_zero, zero_add] @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add _ /-- `count a`, the multiplicity of `a` in a multiset, promoted to an `add_monoid_hom`. -/ def count_add_monoid_hom (a : α) : multiset α →+ ℕ := countp_add_monoid_hom (eq a) @[simp] lemma coe_count_add_monoid_hom {a : α} : (count_add_monoid_hom a : multiset α → ℕ) = count a := rfl @[simp] theorem count_nsmul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul, zero_nsmul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] theorem one_le_count_iff_mem {a : α} {s : multiset α} : 1 ≤ count a s ↔ a ∈ s := by rw [succ_le_iff, count_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') @[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] theorem count_eq_card {a : α} {s} : count a s = card s ↔ ∀ (x ∈ s), a = x := countp_eq_card @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, tsub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, tsub_add_min], end theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} : count a (filter p s) = if p a then count a s else 0 := begin split_ifs with h, { exact count_filter_of_pos h }, { exact count_filter_of_neg h }, end theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } theorem repeat_inf (s : multiset α) (a : α) (n : ℕ) : (repeat a n) ⊓ s = repeat a (min (s.count a) n) := begin ext x, rw [inf_eq_inter, count_inter, count_repeat, count_repeat], by_cases x = a, simp only [min_comm, h, if_true, eq_self_iff_true], simp only [h, if_false, zero_min], end theorem count_map {α β : Type*} (f : α → β) (s : multiset α) [decidable_eq β] (b : β) : count b (map f s) = (s.filter (λ a, b = f a)).card := countp_map _ _ _ /-- `multiset.map f` preserves `count` if `f` is injective on the set of elements contained in the multiset -/ theorem count_map_eq_count [decidable_eq β] (f : α → β) (s : multiset α) (hf : set.inj_on f {x : α | x ∈ s}) (x ∈ s) : (s.map f).count (f x) = s.count x := begin suffices : (filter (λ (a : α), f x = f a) s).count x = card (filter (λ (a : α), f x = f a) s), { rw [count, countp_map, ← this], exact count_filter_of_pos rfl }, { rw eq_repeat.2 ⟨rfl, λ b hb, eq_comm.1 ((hf H (mem_filter.1 hb).left) (mem_filter.1 hb).right)⟩, simp only [count_repeat, eq_self_iff_true, if_true, card_repeat]}, end /-- `multiset.map f` preserves `count` if `f` is injective -/ theorem count_map_eq_count' [decidable_eq β] (f : α → β) (s : multiset α) (hf : function.injective f) (x : α) : (s.map f).count (f x) = s.count x := begin by_cases H : x ∈ s, { exact count_map_eq_count f _ (set.inj_on_of_injective hf _) _ H, }, { rw [count_eq_zero_of_not_mem H, count_eq_zero, mem_map], rintro ⟨k, hks, hkx⟩, rw hf hkx at *, contradiction } end lemma filter_eq' (s : multiset α) (b : α) : s.filter (= b) = repeat b (count b s) := begin ext a, rw [count_repeat, count_filter], exact if_ctx_congr iff.rfl (λ h, congr_arg _ h) (λ h, rfl), end lemma filter_eq (s : multiset α) (b : α) : s.filter (eq b) = repeat b (count b s) := by simp_rw [←filter_eq', eq_comm] @[simp] lemma repeat_inter (x : α) (n : ℕ) (s : multiset α) : repeat x n ∩ s = repeat x (min n (s.count x)) := begin refine le_antisymm _ _, { simp only [le_iff_count, count_inter, count_repeat], intro a, split_ifs with h, { rw h }, { rw [nat.zero_min] } }, simp only [le_inter_iff, ← le_count_iff_repeat_le, count_inter, count_repeat_self], end @[simp] lemma inter_repeat (s : multiset α) (x : α) (n : ℕ) : s ∩ repeat x n = repeat x (min (s.count x) n) := by rw [inter_comm, repeat_inter, min_comm] end section embedding @[simp] lemma map_le_map_iff {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f ≤ t.map f ↔ s ≤ t := begin classical, refine ⟨λ h, le_iff_count.mpr (λ a, _), map_le_map⟩, simpa [count_map_eq_count' f _ hf] using le_iff_count.mp h (f a), end /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a multiset to its image under `f`. -/ @[simps] def map_embedding (f : α ↪ β) : multiset α ↪o multiset β := order_embedding.of_map_le_iff (map f) (λ _ _, map_le_map_iff f.inj') end embedding lemma count_eq_card_filter_eq [decidable_eq α] (s : multiset α) (a : α) : s.count a = (s.filter (eq a)).card := by rw [count, countp_eq_card_filter] /-- Mapping a multiset through a predicate and counting the `true`s yields the cardinality of the set filtered by the predicate. Note that this uses the notion of a multiset of `Prop`s - due to the decidability requirements of `count`, the decidability instance on the LHS is different from the RHS. In particular, the decidability instance on the left leaks `classical.dec_eq`. See [here](https://github.com/leanprover-community/mathlib/pull/11306#discussion_r782286812) for more discussion. -/ @[simp] lemma map_count_true_eq_filter_card (s : multiset α) (p : α → Prop) [decidable_pred p] : (s.map p).count true = (s.filter p).card := by simp only [count_eq_card_filter_eq, map_filter, card_map, function.comp.left_id, eq_true_eq_id] /-! ### Lift a relation to `multiset`s -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ @[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs) variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_refl_of_refl_on {m : multiset α} {r : α → α → Prop} : (∀ x ∈ m, r x x) → rel r m m := begin apply m.induction_on, { intros, apply rel.zero }, { intros a m ih h, exact rel.cons (h _ (mem_cons_self _ _)) (ih (λ _ ha, h _ (mem_cons_of_mem ha))) } end lemma rel_eq_refl {s : multiset α} : rel (=) s s := rel_refl_of_refl_on (λ x hx, rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {r p : α → β → Prop} {s t} (hst : rel r s t) (h : ∀(a ∈ s) (b ∈ t), r a b → p a b) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { apply rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab), exact ih (λ a' ha' b' hb' h', h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h') } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') := begin split, { generalize hm : a ::ₘ as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') := begin rw [← rel_flip, rel_cons_left], refine exists₂_congr (λ a as', _), rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_map {s : multiset α} {t : multiset β} {f : α → γ} {g : β → δ} : rel p (s.map f) (t.map g) ↔ rel (λa b, p (f a) (g b)) s t := rel_map_left.trans rel_map_right lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end lemma rel_of_forall {m1 m2 : multiset α} {r : α → α → Prop} (h : ∀ a b, a ∈ m1 → b ∈ m2 → r a b) (hc : card m1 = card m2) : m1.rel r m2 := begin revert m1, apply m2.induction_on, { intros m h hc, rw [rel_zero_right, ← card_eq_zero, hc, card_zero] }, { intros a t ih m h hc, rw card_cons at hc, obtain ⟨b, hb⟩ := card_pos_iff_exists_mem.1 (show 0 < card m, from hc.symm ▸ (nat.succ_pos _)), obtain ⟨m', rfl⟩ := exists_cons_of_mem hb, refine rel_cons_right.mpr ⟨b, m', h _ _ hb (mem_cons_self _ _), ih _ _, rfl⟩, { exact λ _ _ ha hb, h _ _ (mem_cons_of_mem ha) (mem_cons_of_mem hb) }, { simpa using hc } } end lemma rel_repeat_left {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : (repeat a n).rel r m ↔ m.card = n ∧ ∀ x, x ∈ m → r a x := ⟨λ h, ⟨(card_eq_card_of_rel h).symm.trans (card_repeat _ _), λ x hx, begin obtain ⟨b, hb1, hb2⟩ := exists_mem_of_rel_of_mem (rel_flip.2 h) hx, rwa eq_of_mem_repeat hb1 at hb2, end⟩, λ h, rel_of_forall (λ x y hx hy, (eq_of_mem_repeat hx).symm ▸ (h.2 _ hy)) (eq.trans (card_repeat _ _) h.1.symm)⟩ lemma rel_repeat_right {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : m.rel r (repeat a n) ↔ m.card = n ∧ ∀ x, x ∈ m → r x a := by { rw [← rel_flip], exact rel_repeat_left } lemma rel.trans (r : α → α → Prop) [is_trans α r] {s t u : multiset α} (r1 : rel r s t) (r2 : rel r t u) : rel r s u := begin induction t using multiset.induction_on with x t ih generalizing s u, { rw [rel_zero_right.mp r1, rel_zero_left.mp r2, rel_zero_left] }, { obtain ⟨a, as, ha1, ha2, rfl⟩ := rel_cons_right.mp r1, obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp r2, exact multiset.rel.cons (trans ha1 hb1) (ih ha2 hb2) } end lemma rel.countp_eq (r : α → α → Prop) [is_trans α r] [is_symm α r] {s t : multiset α} (x : α) [decidable_pred (r x)] (h : rel r s t) : countp (r x) s = countp (r x) t := begin induction s using multiset.induction_on with y s ih generalizing t, { rw rel_zero_left.mp h, }, { obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp h, rw [countp_cons, countp_cons, ih hb2], exact congr_arg _ (if_congr ⟨λ h, trans h hb1, λ h, trans h (symm hb1)⟩ rfl rfl) }, end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by { rw [← rel_eq, ← rel_eq, rel_map], simp only [hf.eq_iff] } theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /-! ### Disjoint multisets -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint {a} l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l {a} ↔ a ∉ l := by rw [disjoint_comm, singleton_disjoint] @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ {a} s t).trans $ by rw singleton_disjoint @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma add_eq_union_iff_disjoint [decidable_eq α] {s t : multiset α} : s + t = s ∪ t ↔ disjoint s t := by simp_rw [←inter_eq_zero_iff_disjoint, ext, count_add, count_union, count_inter, count_zero, nat.min_eq_zero_iff, nat.add_eq_max_iff] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := by { simp [disjoint, @eq_comm _ (f _) (g _)], refl } /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r @[simp] lemma pairwise_nil (r : α → α → Prop) : multiset.pairwise r 0 := ⟨[], rfl, list.pairwise.nil⟩ lemma pairwise_coe_iff {r : α → α → Prop} {l : list α} : multiset.pairwise r l ↔ ∃ l' : list α, l ~ l' ∧ l'.pairwise r := exists_congr $ by simp lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } variable {α} @[simp] lemma coe_subsingleton_equiv [subsingleton α] : (subsingleton_equiv α : list α → multiset α) = coe := rfl end multiset
67bb2b8e96a4753b0d7a2b032c5eb3a51a3d6901
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/data/real/ennreal.lean
e55f2ca1a5ae20204a49a9efbe70100b4dbe09cb
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,697
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 -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ennreal` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ennreal`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ennreal` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ennreal` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ennreal`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ennreal // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ennreal ℝ≥0` instance, so one of the ways to prove theorems about an `ennreal` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ennreal) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0`: type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ennreal` for `⊤ : ennreal`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal 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, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : ℝ≥0} instance : inhabited ennreal := ⟨0⟩ instance : has_coe ℝ≥0 ennreal := ⟨ option.some ⟩ instance : can_lift ennreal ℝ≥0 := { 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) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → ℝ≥0 | (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 : ℝ} (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 to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl 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 : ℝ≥0) : (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 : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ennreal _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (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:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ennreal → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ennreal → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none 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:ℝ≥0) = (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 of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[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 : ℝ≥0 → 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:ℝ≥0) : 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 zero_lt_two : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of `ennreal` numbers that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ennreal → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ennreal → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ennreal → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ennreal → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, 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⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ennreal := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ennreal) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ennreal).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := of_nnreal_hom.map_pow r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ennreal} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] 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 = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ennreal} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] 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 : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑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 : ℝ≥0) : 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) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ennreal)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl 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}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), 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 exists_between 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:ℝ≥0, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 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 : ℝ≥0 := ⟨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 lift r to ℝ≥0 using h, 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 exists_between 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 exists_between 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:ℝ≥0):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ennreal) = max r p := coe_mono.map_max end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : 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 ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} 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 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 $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ennreal} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ennreal` as `nnreal` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 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⁻¹:ℝ≥0):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.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_lt_top {x : ennreal} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, zero_lt_iff_ne_zero] } lemma div_lt_top {x y : ennreal} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[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] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_def, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 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 : ℝ≥0) : ennreal) * ∞ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : ℝ≥0) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), linarith, 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 = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff : 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 ℝ≥0 using ht, have h : (2 : ennreal) = ((2 : ℝ≥0) : ennreal), from rfl, have h' : (2 : ℝ≥0) ≠ 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 ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ennreal), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ennreal)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ennreal) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 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] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 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 ℝ≥0 using ha, lift b to ℝ≥0 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] lemma of_real_le_of_le_to_real {a : ℝ} {b : ennreal} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[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 ℝ≥0 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 ℝ≥0 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 ℝ≥0 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 ℝ≥0 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_nnreal_mul_top (a : ennreal) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ennreal) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[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 (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ennreal →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ennreal →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ennreal) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ 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 /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ennreal` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ennreal} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] end ennreal
17428e660c0304f7325adf09da0a4d5c19133631
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/hex_char.lean
bc2f732dae4a0418dbd89c3eed099a62c3442429
[ "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
39
lean
#eval '\x41' #eval '\x42' #eval '\x43'
9f5e0d2e527c115db985be7eb0dee25cf04778d6
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/group_theory/sylow.lean
853bd5f2b0dee5630a0e08dab9865f02a7b6c272
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
11,386
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 group_theory.quotient_group import group_theory.order_of_element data.zmod.basic open equiv fintype finset mul_action function open equiv.perm is_subgroup list quotient_group universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 0] 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 : nat.prime p) (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 (equiv_fib (@quotient.mk' _ (orbit_rel G α))) ... = univ.sum (λ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a}) : card_sigma _ ... ≡ (@univ (fixed_points G α) _).sum (λ _, 1) [MOD p] : begin rw [← zmodp.eq_iff_modeq_nat hp, 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, ← zmodp.eq_iff_modeq_nat hp, 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 _, by simp [zero_ne_one], rfl⟩ } 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 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_inj (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) 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_right_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]⟩ 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.1, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ+) : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := λ v, subtype.eq $ vector.eq _ _ $ rotate_zero v.1.to_list, 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.add_val, rotate_rotate, ← rotate_mod _ (b.1 + a.1), 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 : ℕ+) : (⟨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 _ _ $ by haveI : nonempty G := ⟨1⟩; exact 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 : nat.prime p) (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.gt_one⟩ in let p' : ℕ+ := ⟨p, hp.pos⟩ in have hn : p' = n + 1 := subtype.eq (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_inj _), card_vector], have hzmod : fintype.card (multiplicative (zmod p')) = (p' : ℕ) ^ 1 := (nat.pow_one p').symm ▸ card_fin _, 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')) := nat.dvd_of_mod_eq_zero (hmodeq ▸ hn.symm ▸ nat.mod_eq_zero_of_dvd 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.gt_one ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_card_gt_one 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 nG : nonempty G, from ⟨1⟩, 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_right H (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ lemma 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 : nat.prime p) (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_right_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, is_submonoid.one_mem H⟩⟩)).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 hp 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
6298463c826624a9d57bf39dbfbeb7d7d2d151b7
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/box_integral/partition/additive.lean
ff36bec2ed7405346131b9b84c7779dbf9ec3f20
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,500
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.box_integral.partition.split import analysis.normed_space.operator_norm import data.set.intervals.proj_Icc /-! # Box additive functions We say that a function `f : box ι → M` from boxes in `ℝⁿ` to a commutative additive monoid `M` is *box additive* on subboxes of `I₀ : with_top (box ι)` if for any box `J`, `↑J ≤ I₀`, and a partition `π` of `J`, `f J = ∑ J' in π.boxes, f J'`. We use `I₀ : with_top (box ι)` instead of `I₀ : box ι` to use the same definition for functions box additive on subboxes of a box and for functions box additive on all boxes. Examples of box-additive functions include the measure of a box and the integral of a fixed integrable function over a box. In this file we define box-additive functions and prove that a function such that `f J = f (J ∩ {x | x i < y}) + f (J ∩ {x | y ≤ x i})` is box-additive. ### Tags rectangular box, additive function -/ noncomputable theory open_locale classical big_operators open function set namespace box_integral variables {ι M : Type*} {n : ℕ} /-- A function on `box ι` is called box additive if for every box `J` and a partition `π` of `J` we have `f J = ∑ Ji in π.boxes, f Ji`. A function is called box additive on subboxes of `I : box ι` if the same property holds for `J ≤ I`. We formalize these two notions in the same definition using `I : with_bot (box ι)`: the value `I = ⊤` corresponds to functions box additive on the whole space. -/ structure box_additive_map (ι M : Type*) [add_comm_monoid M] (I : with_top (box ι)) := (to_fun : box ι → M) (sum_partition_boxes' : ∀ J : box ι, ↑J ≤ I → ∀ π : prepartition J, π.is_partition → ∑ Ji in π.boxes, to_fun Ji = to_fun J) localized "notation ι ` →ᵇᵃ `:25 M := box_integral.box_additive_map ι M ⊤" in box_integral localized "notation ι ` →ᵇᵃ[`:25 I `] ` M := box_integral.box_additive_map ι M I" in box_integral namespace box_additive_map open box prepartition finset variables {N : Type*} [add_comm_monoid M] [add_comm_monoid N] {I₀ : with_top (box ι)} {I J : box ι} {i : ι} instance : has_coe_to_fun (ι →ᵇᵃ[I₀] M) := ⟨_, to_fun⟩ initialize_simps_projections box_integral.box_additive_map (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : ι →ᵇᵃ[I₀] M) : f.to_fun = f := rfl @[simp] lemma coe_mk (f h) : ⇑(mk f h : ι →ᵇᵃ[I₀] M) = f := rfl lemma coe_injective : injective (λ (f : ι →ᵇᵃ[I₀] M) x, f x) := by { rintro ⟨f, hf⟩ ⟨g, hg⟩ (rfl : f = g), refl } @[simp] lemma coe_inj {f g : ι →ᵇᵃ[I₀] M} : (f : box ι → M) = g ↔ f = g := coe_injective.eq_iff lemma sum_partition_boxes (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π : prepartition I} (h : π.is_partition) : ∑ J in π.boxes, f J = f I := f.sum_partition_boxes' I hI π h @[simps { fully_applied := ff }] instance : has_zero (ι →ᵇᵃ[I₀] M) := ⟨⟨0, λ I hI π hπ, sum_const_zero⟩⟩ instance : inhabited (ι →ᵇᵃ[I₀] M) := ⟨0⟩ instance : has_add (ι →ᵇᵃ[I₀] M) := ⟨λ f g, ⟨f + g, λ I hI π hπ, by simp only [pi.add_apply, sum_add_distrib, sum_partition_boxes _ hI hπ]⟩⟩ instance : add_comm_monoid (ι →ᵇᵃ[I₀] M) := function.injective.add_comm_monoid _ coe_injective rfl (λ _ _, rfl) @[simp] lemma map_split_add (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) (i : ι) (x : ℝ) : (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I := by rw [← f.sum_partition_boxes hI (is_partition_split I i x), sum_split_boxes] /-- If `f` is box-additive on subboxes of `I₀`, then it is box-additive on subboxes of any `I ≤ I₀`. -/ @[simps] def restrict (f : ι →ᵇᵃ[I₀] M) (I : with_top (box ι)) (hI : I ≤ I₀) : ι →ᵇᵃ[I] M := ⟨f, λ J hJ, f.2 J (hJ.trans hI)⟩ /-- If `f : box ι → M` is box additive on partitions of the form `split I i x`, then it is box additive. -/ def of_map_split_add [fintype ι] (f : box ι → M) (I₀ : with_top (box ι)) (hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ {i x}, x ∈ Ioo (I.lower i) (I.upper i) → (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I) : ι →ᵇᵃ[I₀] M := begin refine ⟨f, _⟩, replace hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ s, ∑ J in (split_many I s).boxes, f J = f I, { intros I hI s, induction s using finset.induction_on with a s ha ihs, { simp }, rw [split_many_insert, inf_split, ← ihs, bUnion_boxes, sum_bUnion_boxes], refine finset.sum_congr rfl (λ J' hJ', _), by_cases h : a.2 ∈ Ioo (J'.lower a.1) (J'.upper a.1), { rw sum_split_boxes, exact hf _ ((with_top.coe_le_coe.2 $ le_of_mem _ hJ').trans hI) h }, { rw [split_of_not_mem_Ioo h, top_boxes, finset.sum_singleton] } }, intros I hI π hπ, have Hle : ∀ J ∈ π, ↑J ≤ I₀, from λ J hJ, (with_top.coe_le_coe.2 $ π.le_of_mem hJ).trans hI, rcases hπ.exists_split_many_le with ⟨s, hs⟩, rw [← hf _ hI, ← inf_of_le_right hs, inf_split_many, bUnion_boxes, sum_bUnion_boxes], exact finset.sum_congr rfl (λ J hJ, (hf _ (Hle _ hJ) _).symm) end /-- If `g : M → N` is an additive map and `f` is a box additive map, then `g ∘ f` is a box additive map. -/ @[simps { fully_applied := ff }] def map (f : ι →ᵇᵃ[I₀] M) (g : M →+ N) : ι →ᵇᵃ[I₀] N := { to_fun := g ∘ f, sum_partition_boxes' := λ I hI π hπ, by rw [← g.map_sum, f.sum_partition_boxes hI hπ] } /-- If `f` is a box additive function on subboxes of `I` and `π₁`, `π₂` are two prepartitions of `I` that cover the same part of `I`, then `∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J`. -/ lemma sum_boxes_congr [fintype ι] (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π₁ π₂ : prepartition I} (h : π₁.Union = π₂.Union) : ∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J := begin rcases exists_split_many_inf_eq_filter_of_finite {π₁, π₂} ((finite_singleton _).insert _) with ⟨s, hs⟩, simp only [inf_split_many] at hs, rcases ⟨hs _ (or.inl rfl), hs _ (or.inr rfl)⟩ with ⟨h₁, h₂⟩, clear hs, rw h at h₁, calc ∑ J in π₁.boxes, f J = ∑ J in π₁.boxes, ∑ J' in (split_many J s).boxes, f J' : finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _)).symm) ... = ∑ J in (π₁.bUnion (λ J, split_many J s)).boxes, f J : (sum_bUnion_boxes _ _ _).symm ... = ∑ J in (π₂.bUnion (λ J, split_many J s)).boxes, f J : by rw [h₁, h₂] ... = ∑ J in π₂.boxes, ∑ J' in (split_many J s).boxes, f J' : sum_bUnion_boxes _ _ _ ... = ∑ J in π₂.boxes, f J : finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _))), exacts [(with_top.coe_le_coe.2 $ π₁.le_of_mem hJ).trans hI, (with_top.coe_le_coe.2 $ π₂.le_of_mem hJ).trans hI] end section to_smul variables {E : Type*} [normed_group E] [normed_space ℝ E] /-- If `f` is a box-additive map, then so is the map sending `I` to the scalar multiplication by `f I` as a continuous linear map from `E` to itself. -/ def to_smul (f : ι →ᵇᵃ[I₀] ℝ) : ι →ᵇᵃ[I₀] (E →L[ℝ] E) := f.map (continuous_linear_map.lsmul ℝ ℝ).to_linear_map.to_add_monoid_hom @[simp] lemma to_smul_apply (f : ι →ᵇᵃ[I₀] ℝ) (I : box ι) (x : E) : f.to_smul I x = f I • x := rfl end to_smul /-- Given a box `I₀` in `ℝⁿ⁺¹`, `f x : box (fin n) → G` is a family of functions indexed by a real `x` and for `x ∈ [I₀.lower i, I₀.upper i]`, `f x` is box-additive on subboxes of the `i`-th face of `I₀`, then `λ J, f (J.upper i) (J.face i) - f (J.lower i) (J.face i)` is box-additive on subboxes of `I₀`. -/ @[simps] def {u} upper_sub_lower {G : Type u} [add_comm_group G] (I₀ : box (fin (n + 1))) (i : fin (n + 1)) (f : ℝ → box (fin n) → G) (fb : Icc (I₀.lower i) (I₀.upper i) → fin n →ᵇᵃ[I₀.face i] G) (hf : ∀ x (hx : x ∈ Icc (I₀.lower i) (I₀.upper i)) J, f x J = fb ⟨x, hx⟩ J) : fin (n + 1) →ᵇᵃ[I₀] G := of_map_split_add (λ J : box (fin (n + 1)), f (J.upper i) (J.face i) - f (J.lower i) (J.face i)) I₀ begin intros J hJ j, rw with_top.coe_le_coe at hJ, refine i.succ_above_cases _ _ j, { intros x hx, simp only [box.split_lower_def hx, box.split_upper_def hx, update_same, ← with_bot.some_eq_coe, option.elim, box.face, (∘), update_noteq (fin.succ_above_ne _ _)], abel }, { clear j, intros j x hx, have : (J.face i : with_top (box (fin n))) ≤ I₀.face i, from with_top.coe_le_coe.2 (face_mono hJ i), rw [le_iff_Icc, @box.Icc_eq_pi _ I₀] at hJ, rw [hf _ (hJ J.upper_mem_Icc _ trivial), hf _ (hJ J.lower_mem_Icc _ trivial), ← (fb _).map_split_add this j x, ← (fb _).map_split_add this j x], have hx' : x ∈ Ioo ((J.face i).lower j) ((J.face i).upper j) := hx, simp only [box.split_lower_def hx, box.split_upper_def hx, box.split_lower_def hx', box.split_upper_def hx', ← with_bot.some_eq_coe, option.elim, box.face_mk, update_noteq (fin.succ_above_ne _ _).symm, sub_add_comm, update_comp_eq_of_injective _ i.succ_above.injective j x, ← hf], simp only [box.face] } end end box_additive_map end box_integral
9d43680ad1fe81ebdf03cfb788217c52193cd51f
28be2ab6091504b6ba250b367205fb94d50ab284
/src/game/world10/level14.lean
c26d53421104214b3ae2b5e67ee5cb8eebbdae5a
[ "Apache-2.0" ]
permissive
postmasters/natural_number_game
87304ac22e5e1c5ac2382d6e523d6914dd67a92d
38a7adcdfdb18c49c87b37831736c8f15300d821
refs/heads/master
1,649,856,819,031
1,586,444,676,000
1,586,444,676,000
255,006,061
0
0
Apache-2.0
1,586,664,599,000
1,586,664,598,000
null
UTF-8
Lean
false
false
777
lean
import game.world10.level13 -- hide namespace mynat -- hide /- # Inequality world. ## Level 14: `add_le_add_left` I know these are easy and we've done several already, but this is one of the axioms for an ordered commutative monoid! The nature of formalising is that we should formalise all "obvious" lemmas, and then when we're actually using $\le$ in real life, everything will be there. Note also, of course, that all of these lemmas are already formalised in Lean's maths library already, for Lean's inbuilt natural numbers. -/ /- Lemma If $a\le b$ then for all $t$, $t+a\le t+b$. -/ theorem add_le_add_left (a b : mynat) (h : a ≤ b) (t : mynat) : t + a ≤ t + b := begin [nat_num_game] cases h with c hc, use c, rw hc, ring, end end mynat -- hide
00ed7eeb750678fc0659f305f4b30418626ecb7c
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/universal/comparisons.lean
78668210d49d3a50c9f5941a3798dab3b2da0c6f
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
5,992
lean
import category_theory.limits open category_theory namespace category_theory.limits universes u v variables {C : Type u} [𝒞 : category.{u v} C] {Y Y₁ Y₂ Z : C} include 𝒞 @[reducible] def binary_product_comparison (t : span Y Z) (X' : C) : (X' ⟶ t.X) → (X' ⟶ Y) × (X' ⟶ Z) := λ φ, (φ ≫ t.π₁, φ ≫ t.π₂) def is_binary_product.comparison {t : span Y Z} (h : is_binary_product t) (X' : C) : is_equiv (binary_product_comparison t X') := { inv := λ p, h.lift ⟨ ⟨ X' ⟩, p.1, p.2 ⟩, hom_inv_id' := begin tidy, symmetry, have := h.uniq {to_shape := {X := X'}, π₁ := x ≫ t.π₁, π₂ := x ≫ t.π₂} x, apply this, -- TODO why can't we just `apply`? tidy, end } def is_binary_product.of_comparison {t : span Y Z} (w : Π X' : C, is_equiv (binary_product_comparison t X')) : is_binary_product t := { lift := λ s, @inv _ _ _ _ _ (w s.X) (s.π₁, s.π₂), fac₁' := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p (s.π₁, s.π₂), tidy, end, fac₂' := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p (s.π₁, s.π₂), tidy, end, uniq' := λ s m w₁ w₂, begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, obviously, end } @[reducible] def equalizer_comparison {f g : Y ⟶ Z} (t : fork f g) (X' : C) : (X' ⟶ t.X) → { h : X' ⟶ Y // h ≫ f = h ≫ g } := λ φ, ⟨ φ ≫ t.ι, by obviously ⟩ def is_equalizer.comparison {f g : Y ⟶ Z} {t : fork f g} (h : is_equalizer t) (X' : C) : is_equiv (equalizer_comparison t X') := { inv := λ p, h.lift ⟨ ⟨ X' ⟩, p.1, p.2 ⟩, hom_inv_id' := begin tidy, symmetry, apply h.uniq {to_shape := {X := X'}, ι := x ≫ t.ι} x, tidy, end } def is_equalizer.of_comparison {f g : Y ⟶ Z} {t : fork f g} (w : Π X' : C, is_equiv (equalizer_comparison t X')) : is_equalizer t := { lift := λ s, @is_iso.inv _ _ _ _ _ (w s.X) ⟨ s.ι, s.w ⟩, fac := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ s.ι, s.w ⟩, tidy, end, uniq := λ s m w', begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, tidy, unfold equalizer_comparison at q, rw ← q, congr, exact w', end } @[reducible] def pullback_comparison {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} (t : square r₁ r₂) (X' : C) : (X' ⟶ t.X) → { c : (X' ⟶ Y₁) × (X' ⟶ Y₂) // c.1 ≫ r₁ = c.2 ≫ r₂ } := λ φ, ⟨ (φ ≫ t.π₁, φ ≫ t.π₂), by obviously ⟩ def is_pullback.comparison {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} {t : square r₁ r₂} (h : is_pullback t) (X' : C) : is_equiv (pullback_comparison t X') := { inv := λ p, h.lift ⟨ ⟨ X' ⟩, p.val.1, p.val.2 ⟩, hom_inv_id' := begin tidy, symmetry, apply h.uniq {to_shape := {X := X'}, π₁ := x ≫ t.π₁, π₂ := x ≫ t.π₂} x, tidy, end } def is_pullback.of_comparison {r₁ : Y₁ ⟶ Z} {r₂ : Y₂ ⟶ Z} {t : square r₁ r₂} (w : Π X' : C, is_equiv (pullback_comparison t X')) : is_pullback t := { lift := λ s, @is_iso.inv _ _ _ _ _ (w s.X) ⟨ (s.π₁, s.π₂), s.w ⟩, fac₁ := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ (s.π₁, s.π₂), s.w ⟩, tidy, end, fac₂ := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ (s.π₁, s.π₂), s.w ⟩, tidy, end, uniq := λ s m w₁ w₂, begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, tidy, unfold pullback_comparison at q, rw ← q, congr, tidy, end } variables {J : Type v} [𝒥 : small_category J] include 𝒥 @[reducible] def limit_comparison {F : J ⥤ C} (t : cone F) (X' : C) : (X' ⟶ t.X) → { c : Π j : J, (X' ⟶ F j) // ∀ {j j' : J} (f : j ⟶ j'), c j ≫ F.map f = c j' } := λ φ, ⟨ λ j, φ ≫ t.π j, by obviously ⟩ def is_limit.comparison {F : J ⥤ C} {t : cone F} (h : is_limit t) (X' : C) : is_equiv (limit_comparison t X') := { inv := λ p, h.lift ⟨ ⟨ X' ⟩, p.val, p.property ⟩, hom_inv_id' := begin tidy, symmetry, apply is_limit.uniq _ {to_shape := {X := X'}, π := λ j, x ≫ t.π j, w := by obviously } x, tidy, end } def is_limit.of_comparison {F : J ⥤ C} {t : cone F} (w : Π X' : C, is_equiv (limit_comparison t X')) : is_limit t := { lift := λ s, @is_iso.inv _ _ _ _ _ (w s.X) ⟨ s.π, s.w ⟩, fac' := λ s, begin have p := @is_iso.inv_hom_id _ _ _ _ _ (w s.X), have q := congr_fun p ⟨ s.π, s.w ⟩, tidy, exact congr_fun q j -- TODO fix automation end, uniq' := λ s m w', begin have p := @is_iso.hom_inv_id _ _ _ _ _ (w s.X), have q := congr_fun p m, tidy, unfold limit_comparison at q, rw ← q, congr, tidy, end } end category_theory.limits
e6aed7dd9e6128b5eea9d20150d151be57650541
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/category/omega_complete_partial_order.lean
dffcf5b9076fa70fd525c8380420c143f82c1f28
[ "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
4,195
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import order.omega_complete_partial_order import order.category.Preorder import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # Category of types with a omega complete partial order In this file, we bundle the class `omega_complete_partial_order` into a concrete category and prove that continuous functions also form a `omega_complete_partial_order`. ## Main definitions * `ωCPO` * an instance of `category` and `concrete_category` -/ open category_theory universes u v /-- The category of types with a omega complete partial order. -/ def ωCPO : Type (u+1) := bundled omega_complete_partial_order namespace ωCPO open omega_complete_partial_order instance : bundled_hom @continuous_hom := { to_fun := @continuous_hom.simps.apply, id := @continuous_hom.id, comp := @continuous_hom.comp, hom_ext := @continuous_hom.coe_inj } attribute [derive [large_category, concrete_category]] ωCPO instance : has_coe_to_sort ωCPO Type* := bundled.has_coe_to_sort /-- Construct a bundled ωCPO from the underlying type and typeclass. -/ def of (α : Type*) [omega_complete_partial_order α] : ωCPO := bundled.of α @[simp] lemma coe_of (α : Type*) [omega_complete_partial_order α] : ↥(of α) = α := rfl instance : inhabited ωCPO := ⟨of punit⟩ instance (α : ωCPO) : omega_complete_partial_order α := α.str section open category_theory.limits namespace has_products /-- The pi-type gives a cone for a product. -/ def product {J : Type v} (f : J → ωCPO.{v}) : fan f := fan.mk (of (Π j, f j)) (λ j, continuous_hom.of_mono (pi.eval_order_hom j) (λ c, rfl)) /-- The pi-type is a limit cone for the product. -/ def is_product (J : Type v) (f : J → ωCPO) : is_limit (product f) := { lift := λ s, ⟨⟨λ t j, s.π.app ⟨j⟩ t, λ x y h j, (s.π.app ⟨j⟩).monotone h⟩, λ x, funext (λ j, (s.π.app ⟨j⟩).continuous x)⟩, uniq' := λ s m w, begin ext t j, change m t j = s.π.app ⟨j⟩ t, rw ← w ⟨j⟩, refl, end, fac' := λ s j, by { cases j, tidy, } }. instance (J : Type v) (f : J → ωCPO.{v}) : has_product f := has_limit.mk ⟨_, is_product _ f⟩ end has_products instance omega_complete_partial_order_equalizer {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : omega_complete_partial_order {a : α // f a = g a} := omega_complete_partial_order.subtype _ $ λ c hc, begin rw [f.continuous, g.continuous], congr' 1, ext, apply hc _ ⟨_, rfl⟩, end namespace has_equalizers /-- The equalizer inclusion function as a `continuous_hom`. -/ def equalizer_ι {α β : Type*} [omega_complete_partial_order α] [omega_complete_partial_order β] (f g : α →𝒄 β) : {a : α // f a = g a} →𝒄 α := continuous_hom.of_mono (order_hom.subtype.val _) (λ c, rfl) /-- A construction of the equalizer fork. -/ def equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : fork f g := @fork.of_ι _ _ _ _ _ _ (ωCPO.of {a // f a = g a}) (equalizer_ι f g) (continuous_hom.ext _ _ (λ x, x.2)) /-- The equalizer fork is a limit. -/ def is_equalizer {X Y : ωCPO.{v}} (f g : X ⟶ Y) : is_limit (equalizer f g) := fork.is_limit.mk' _ $ λ s, ⟨{ to_fun := λ x, ⟨s.ι x, by apply continuous_hom.congr_fun s.condition⟩, monotone' := λ x y h, s.ι.monotone h, cont := λ x, subtype.ext (s.ι.continuous x) }, by { ext, refl }, λ m hm, begin ext, apply continuous_hom.congr_fun hm, end⟩ end has_equalizers instance : has_products.{v} ωCPO.{v} := λ J, { has_limit := λ F, has_limit_of_iso discrete.nat_iso_functor.symm } instance {X Y : ωCPO.{v}} (f g : X ⟶ Y) : has_limit (parallel_pair f g) := has_limit.mk ⟨_, has_equalizers.is_equalizer f g⟩ instance : has_equalizers ωCPO.{v} := has_equalizers_of_has_limit_parallel_pair _ instance : has_limits ωCPO.{v} := limits_from_equalizers_and_products end end ωCPO
1da7d40e1604eb3fcee05b1f757ba925e04730e2
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/category/Group/basic.lean
f0412f448328544396dcb951bdda260008100d7f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
9,500
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.category.Mon.basic import category_theory.endomorphism /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := bundled group /-- The category of additive groups and group morphisms -/ add_decl_doc AddGroup namespace Group @[to_additive] instance : bundled_hom.parent_projection group.to_monoid := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Group AddGroup /-- Construct a bundled `Group` from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X /-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/ add_decl_doc AddGroup.of @[to_additive] instance (G : Group) : group G := G.str @[simp, to_additive] lemma coe_of (R : Type u) [group R] : (Group.of R : Type u) = R := rfl @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : inhabited Group := ⟨1⟩ @[to_additive] instance : unique (1 : Group) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : Group) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive, ext] lemma ext (G H : Group) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddGroup.ext @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := bundled_hom.forget₂ _ _ end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := bundled comm_group /-- The category of additive commutative groups and group morphisms. -/ add_decl_doc AddCommGroup /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ abbreviation Ab := AddCommGroup namespace CommGroup @[to_additive] instance : bundled_hom.parent_projection comm_group.to_group := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommGroup AddCommGroup /-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G /-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/ add_decl_doc AddCommGroup.of @[to_additive] instance comm_group_instance (G : CommGroup) : comm_group G := G.str @[simp, to_additive] lemma coe_of (R : Type u) [comm_group R] : (CommGroup.of R : Type u) = R := rfl @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : inhabited CommGroup := ⟨1⟩ @[to_additive] instance : unique (1 : CommGroup) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : CommGroup) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive,ext] lemma ext (G H : CommGroup) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddCommGroup.ext @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := bundled_hom.forget₂ _ _ @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. @[to_additive] example {R S : CommGroup} (i : R ⟶ S) (r : R) (h : r = 1) : i r = 1 := by simp [h] namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`, -- so we write this explicitly to be clear. -- TODO generalize this, requiring a `ulift_instances.lean` file def as_hom {G : AddCommGroup.{0}} (g : G) : (AddCommGroup.of ℤ) ⟶ G := gmultiples_hom G g @[simp] lemma as_hom_apply {G : AddCommGroup.{0}} (g : G) (i : ℤ) : (as_hom g) i = i • g := rfl lemma as_hom_injective {G : AddCommGroup.{0}} : function.injective (@as_hom G) := λ h k w, by convert congr_arg (λ k : (AddCommGroup.of ℤ) ⟶ G, (k : ℤ → G) (1 : ℤ)) w; simp @[ext] lemma int_hom_ext {G : AddCommGroup.{0}} (f g : (AddCommGroup.of ℤ) ⟶ G) (w : f (1 : ℤ) = g (1 : ℤ)) : f = g := add_monoid_hom.ext_int w -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. lemma injective_of_mono {G H : AddCommGroup.{0}} (f : G ⟶ H) [mono f] : function.injective f := λ g₁ g₂ h, begin have t0 : as_hom g₁ ≫ f = as_hom g₂ ≫ f := begin ext, simpa [as_hom_apply] using h, end, have t1 : as_hom g₁ = as_hom g₂ := (cancel_mono _).1 t0, apply as_hom_injective t1, end end AddCommGroup variables {X Y : Type u} /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ @[to_additive add_equiv.to_AddGroup_iso] def mul_equiv.to_Group_iso [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/ add_decl_doc add_equiv.to_AddGroup_iso attribute [simps] mul_equiv.to_Group_iso add_equiv.to_AddGroup_iso /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ @[to_additive add_equiv.to_AddCommGroup_iso] def mul_equiv.to_CommGroup_iso [comm_group X] [comm_group Y] (e : X ≃* Y) : CommGroup.of X ≅ CommGroup.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s. -/ add_decl_doc add_equiv.to_AddCommGroup_iso attribute [simps] mul_equiv.to_CommGroup_iso add_equiv.to_AddCommGroup_iso namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddGroup`."] def Group_iso_to_mul_equiv {X Y : Group} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] Group_iso_to_mul_equiv AddGroup_iso_to_add_equiv /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommGroup`."] def CommGroup_iso_to_mul_equiv {X Y : CommGroup} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. attribute [simps] CommGroup_iso_to_mul_equiv AddCommGroup_iso_to_add_equiv end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ @[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same as (isomorphic to) isomorphisms in `AddGroup`"] def mul_equiv_iso_Group_iso {X Y : Type u} [group X] [group Y] : (X ≃* Y) ≅ (Group.of X ≅ Group.of Y) := { hom := λ e, e.to_Group_iso, inv := λ i, i.Group_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ @[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are the same as (isomorphic to) isomorphisms in `AddCommGroup`"] def mul_equiv_iso_CommGroup_iso {X Y : Type u} [comm_group X] [comm_group Y] : (X ≃* Y) ≅ (CommGroup.of X ≅ CommGroup.of Y) := { hom := λ e, e.to_CommGroup_iso, inv := λ i, i.CommGroup_iso_to_mul_equiv, } namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := { hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩, inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ } /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso_perm.Group_iso_to_mul_equiv end category_theory.Aut @[to_additive] instance Group.forget_reflects_isos : reflects_isomorphisms (forget Group.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Group).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_Group_iso }, end } @[to_additive] instance CommGroup.forget_reflects_isos : reflects_isomorphisms (forget CommGroup.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget CommGroup).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_CommGroup_iso }, end }
84cfbc85a36c13d35dac50c0c7e3f7c26d4ad409
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/class_bug1.lean
d085d603e279c75f450a1e26e13b34e7c6b9153d
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
980
lean
import logic inductive category (ob : Type) (mor : ob → ob → Type) : Type := mk : Π (comp : Π⦃A B C : ob⦄, mor B C → mor A B → mor A C) (id : Π {A : ob}, mor A A), (Π {A B C D : ob} {f : mor A B} {g : mor B C} {h : mor C D}, comp h (comp g f) = comp (comp h g) f) → (Π {A B : ob} {f : mor A B}, comp f id = f) → (Π {A B : ob} {f : mor A B}, comp id f = f) → category ob mor attribute category [class] namespace category context sec_cat parameter A : Type inductive foo := mk : A → foo attribute foo [class] parameters {ob : Type} {mor : ob → ob → Type} {Cat : category ob mor} definition compose := category.rec (λ comp id assoc idr idl, comp) Cat definition id := category.rec (λ comp id assoc idr idl, id) Cat infixr ∘ := compose inductive is_section {A B : ob} (f : mor A B) : Type := mk : ∀g, g ∘ f = id → is_section f end sec_cat end category
4aa7915d73f50be11ca84a005d10e00e31a36853
6b9f7292f079a781a1e11aec2932248bf70a9ac0
/src/problems/day1.lean
b40d9baf298576021d1f9e03d9935b987bd02a9e
[]
no_license
cipher1024/advent-of-lean
f3abe5069f638b60ae2f5dd901e5688d21c9486c
f16bc92afe6e836bbde1a1172c571c7680dddc73
refs/heads/master
1,587,691,910,350
1,550,637,443,000
1,550,637,443,000
171,601,681
1
0
null
null
null
null
UTF-8
Lean
false
false
980
lean
import data.buffer.parser import system.io import category.basic namespace day1 def fn := "input/day1.txt" open parser def sign : parser (ℤ → ℤ) := id <$ ch '+' <|> has_neg.neg <$ ch '-' def digit : parser ℤ := (λ c, char.to_nat c - '0'.to_nat) <$> sat (∈ "0123456789".to_list) def parse_nat : parser ℤ := do ds ← many1 digit, pure $ ds.foldl (λ acc d, acc * 10 + d) 0 def num : parser ℤ := sign <*> parse_nat def WS := () <$ many (sat char.is_whitespace) def parse_all_the_stuff : parser (list ℤ) := many (num <* WS) def pp_i (i : ℤ) : string := if i > 0 then "+" ++ to_string i else to_string i def sum.to_io {α} : string ⊕ α → io α | (sum.inl e) := monad_fail.fail $ "\n" ++ e | (sum.inr r) := pure r instance {α} : has_coe (string ⊕ α) (io α) := ⟨ sum.to_io ⟩ def main : io unit := do bs ← io.fs.read_file fn, r ← parser.run parse_all_the_stuff bs, io.print $ sformat!"day1:\n{r.foldl (+) 0}" end day1
84a89729d0b0dc47568aa96e363837970126021d
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finsupp/interval.lean
e82f01c069ac3a04e85fb88e0a36bbb5cc70ef2b
[ "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
3,049
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.finsupp import data.finset.locally_finite import data.finsupp.order /-! # Finite intervals of finitely supported functions This file provides the `locally_finite_order` instance for `ι →₀ α` when `α` itself is locally finite and calculates the cardinality of its finite intervals. ## Main declarations * `finsupp.range_singleton`: Postcomposition with `has_singleton.singleton` on `finset` as a `finsupp`. * `finsupp.range_Icc`: Postcomposition with `finset.Icc` as a `finsupp`. Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely supported. -/ noncomputable theory open finset finsupp function open_locale big_operators classical pointwise variables {ι α : Type*} namespace finsupp section range_singleton variables [has_zero α] {f : ι →₀ α} {i : ι} {a : α} /-- Pointwise `finset.singleton` bundled as a `finsupp`. -/ @[simps] def range_singleton (f : ι →₀ α) : ι →₀ finset α := { to_fun := λ i, {f i}, support := f.support, mem_support_to_fun := λ i, begin rw [←not_iff_not, not_mem_support_iff, not_ne_iff], exact singleton_injective.eq_iff.symm, end } lemma mem_range_singleton_apply_iff : a ∈ f.range_singleton i ↔ a = f i := mem_singleton end range_singleton section range_Icc variables [has_zero α] [partial_order α] [locally_finite_order α] {f g : ι →₀ α} {i : ι} {a : α} /-- Pointwise `finset.Icc` bundled as a `finsupp`. -/ @[simps] def range_Icc (f g : ι →₀ α) : ι →₀ finset α := { to_fun := λ i, Icc (f i) (g i), support := f.support ∪ g.support, mem_support_to_fun := λ i, begin rw [mem_union, ←not_iff_not, not_or_distrib, not_mem_support_iff, not_mem_support_iff, not_ne_iff], exact Icc_eq_singleton_iff.symm, end } lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc end range_Icc variables [partial_order α] [has_zero α] [locally_finite_order α] (f g : ι →₀ α) instance : locally_finite_order (ι →₀ α) := locally_finite_order.of_Icc (ι →₀ α) (λ f g, (f.support ∪ g.support).finsupp $ f.range_Icc g) (λ f g x, begin refine (mem_finsupp_iff_of_support_subset $ subset.rfl).trans _, simp_rw mem_range_Icc_apply_iff, exact forall_and_distrib, end) lemma card_Icc : (Icc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card := card_finsupp _ _ lemma card_Ico : (Ico f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc : (Ioc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo : (Ioo f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end finsupp
010174a2ce13bc4b2e8ff8cd5e048e4f1015f935
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/convex/caratheodory.lean
a8bb59d48e0cbde7a2e30c0d9643529780a9a055
[ "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
8,369
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import analysis.convex.combination import linear_algebra.affine_space.independent /-! # Carathéodory's convexity theorem Convex hull can be regarded as a refinement of affine span. Both are closure operators but whereas convex hull takes values in the lattice of convex subsets, affine span takes values in the much coarser sublattice of affine subspaces. The cost of this refinement is that one no longer has bases. However Carathéodory's convexity theorem offers some compensation. Given a set `s` together with a point `x` in its convex hull, Carathéodory says that one may find an affine-independent family of elements `s` whose convex hull contains `x`. Thus the difference from the case of affine span is that the affine-independent family depends on `x`. In particular, in finite dimensions Carathéodory's theorem implies that the convex hull of a set `s` in `ℝᵈ` is the union of the convex hulls of the `(d+1)`-tuples in `s`. ## Main results * `convex_hull_eq_union`: Carathéodory's convexity theorem ## Implementation details This theorem was formalized as part of the Sphere Eversion project. ## Tags convex hull, caratheodory -/ universes u open set finset open_locale big_operators variables {E : Type u} [add_comm_group E] [module ℝ E] namespace caratheodory /-- If `x` is in the convex hull of some finset `t` whose elements are not affine-independent, then it is in the convex hull of a strict subset of `t`. -/ lemma mem_convex_hull_erase [decidable_eq E] {t : finset E} (h : ¬ affine_independent ℝ (coe : t → E)) {x : E} (m : x ∈ convex_hull (↑t : set E)) : ∃ (y : (↑t : set E)), x ∈ convex_hull (↑(t.erase y) : set E) := begin simp only [finset.convex_hull_eq, mem_set_of_eq] at m ⊢, obtain ⟨f, fpos, fsum, rfl⟩ := m, obtain ⟨g, gcombo, gsum, gpos⟩ := exists_nontrivial_relation_sum_zero_of_not_affine_ind h, replace gpos := exists_pos_of_sum_zero_of_exists_nonzero g gsum gpos, clear h, let s := t.filter (λ z : E, 0 < g z), obtain ⟨i₀, mem, w⟩ : ∃ i₀ ∈ s, ∀ i ∈ s, f i₀ / g i₀ ≤ f i / g i, { apply s.exists_min_image (λ z, f z / g z), obtain ⟨x, hx, hgx⟩ : ∃ x ∈ t, 0 < g x := gpos, exact ⟨x, mem_filter.mpr ⟨hx, hgx⟩⟩ }, have hg : 0 < g i₀ := by { rw mem_filter at mem, exact mem.2 }, have hi₀ : i₀ ∈ t := filter_subset _ _ mem, let k : E → ℝ := λ z, f z - (f i₀ / g i₀) * g z, have hk : k i₀ = 0 := by field_simp [k, ne_of_gt hg], have ksum : ∑ e in t.erase i₀, k e = 1, { calc ∑ e in t.erase i₀, k e = ∑ e in t, k e : by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_add] } ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) : rfl ... = 1 : by rw [sum_sub_distrib, fsum, ← mul_sum, gsum, mul_zero, sub_zero] }, refine ⟨⟨i₀, hi₀⟩, k, _, ksum, _⟩, { simp only [and_imp, sub_nonneg, mem_erase, ne.def, subtype.coe_mk], intros e hei₀ het, by_cases hes : e ∈ s, { have hge : 0 < g e := by { rw mem_filter at hes, exact hes.2 }, rw ← le_div_iff hge, exact w _ hes }, { calc _ ≤ 0 : mul_nonpos_of_nonneg_of_nonpos _ _ -- prove two goals below ... ≤ f e : fpos e het, { apply div_nonneg (fpos i₀ (mem_of_subset (filter_subset _ t) mem)) (le_of_lt hg) }, { simpa only [mem_filter, het, true_and, not_lt] using hes } } }, { simp only [subtype.coe_mk, center_mass_eq_of_sum_1 _ id ksum, id], calc ∑ e in t.erase i₀, k e • e = ∑ e in t, k e • e : sum_erase _ (by rw [hk, zero_smul]) ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) • e : rfl ... = t.center_mass f id : _, simp only [sub_smul, mul_smul, sum_sub_distrib, ← smul_sum, gcombo, smul_zero, sub_zero, center_mass, fsum, inv_one, one_smul, id.def] } end variables {s : set E} {x : E} (hx : x ∈ convex_hull s) include hx /-- Given a point `x` in the convex hull of a set `s`, this is a finite subset of `s` of minimum cardinality, whose convex hull contains `x`. -/ noncomputable def min_card_finset_of_mem_convex_hull : finset E := function.argmin_on finset.card nat.lt_wf { t | ↑t ⊆ s ∧ x ∈ convex_hull (t : set E) } (by simpa only [convex_hull_eq_union_convex_hull_finite_subsets s, exists_prop, mem_Union] using hx) lemma min_card_finset_of_mem_convex_hull_subseteq : ↑(min_card_finset_of_mem_convex_hull hx) ⊆ s := (function.argmin_on_mem _ _ { t : finset E | ↑t ⊆ s ∧ x ∈ convex_hull (t : set E) } _).1 lemma mem_min_card_finset_of_mem_convex_hull : x ∈ convex_hull (min_card_finset_of_mem_convex_hull hx : set E) := (function.argmin_on_mem _ _ { t : finset E | ↑t ⊆ s ∧ x ∈ convex_hull (t : set E) } _).2 lemma min_card_finset_of_mem_convex_hull_nonempty : (min_card_finset_of_mem_convex_hull hx).nonempty := begin rw [← finset.coe_nonempty, ← convex_hull_nonempty_iff], exact ⟨x, mem_min_card_finset_of_mem_convex_hull hx⟩, end lemma min_card_finset_of_mem_convex_hull_card_le_card {t : finset E} (ht₁ : ↑t ⊆ s) (ht₂ : x ∈ convex_hull (t : set E)) : (min_card_finset_of_mem_convex_hull hx).card ≤ t.card := function.argmin_on_le _ _ _ ⟨ht₁, ht₂⟩ lemma affine_independent_min_card_finset_of_mem_convex_hull : affine_independent ℝ (coe : min_card_finset_of_mem_convex_hull hx → E) := begin let k := (min_card_finset_of_mem_convex_hull hx).card - 1, have hk : (min_card_finset_of_mem_convex_hull hx).card = k + 1, { exact (nat.succ_pred_eq_of_pos (finset.card_pos.mpr (min_card_finset_of_mem_convex_hull_nonempty hx))).symm }, classical, by_contra, obtain ⟨p, hp⟩ := mem_convex_hull_erase h (mem_min_card_finset_of_mem_convex_hull hx), have contra := min_card_finset_of_mem_convex_hull_card_le_card hx (set.subset.trans (finset.erase_subset ↑p (min_card_finset_of_mem_convex_hull hx)) (min_card_finset_of_mem_convex_hull_subseteq hx)) hp, rw [← not_lt] at contra, apply contra, erw [card_erase_of_mem p.2, hk], exact lt_add_one _, end end caratheodory variables {s : set E} /-- **Carathéodory's convexity theorem** -/ lemma convex_hull_eq_union : convex_hull s = ⋃ (t : finset E) (hss : ↑t ⊆ s) (hai : affine_independent ℝ (coe : t → E)), convex_hull ↑t := begin apply set.subset.antisymm, { intros x hx, simp only [exists_prop, set.mem_Union], exact ⟨caratheodory.min_card_finset_of_mem_convex_hull hx, caratheodory.min_card_finset_of_mem_convex_hull_subseteq hx, caratheodory.affine_independent_min_card_finset_of_mem_convex_hull hx, caratheodory.mem_min_card_finset_of_mem_convex_hull hx⟩ }, { iterate 3 { convert set.Union_subset _, intro }, exact convex_hull_mono ‹_› } end /-- A more explicit version of `convex_hull_eq_union`. -/ theorem eq_pos_convex_span_of_mem_convex_hull {x : E} (hx : x ∈ convex_hull s) : ∃ (ι : Sort (u+1)) (_ : fintype ι), by exactI ∃ (z : ι → E) (w : ι → ℝ) (hss : set.range z ⊆ s) (hai : affine_independent ℝ z) (hw : ∀ i, 0 < w i), ∑ i, w i = 1 ∧ ∑ i, w i • z i = x := begin rw convex_hull_eq_union at hx, simp only [exists_prop, set.mem_Union] at hx, obtain ⟨t, ht₁, ht₂, ht₃⟩ := hx, simp only [t.convex_hull_eq, exists_prop, set.mem_set_of_eq] at ht₃, obtain ⟨w, hw₁, hw₂, hw₃⟩ := ht₃, let t' := t.filter (λ i, w i ≠ 0), refine ⟨t', t'.fintype_coe_sort, (coe : t' → E), w ∘ (coe : t' → E), _, _, _, _, _⟩, { rw subtype.range_coe_subtype, exact subset.trans (finset.filter_subset _ t) ht₁ }, { exact ht₂.comp_embedding ⟨_, inclusion_injective (finset.filter_subset (λ i, w i ≠ 0) t)⟩ }, { exact λ i, (hw₁ _ (finset.mem_filter.mp i.2).1).lt_of_ne (finset.mem_filter.mp i.property).2.symm }, { erw [finset.sum_attach, finset.sum_filter_ne_zero, hw₂] }, { change ∑ (i : t') in t'.attach, (λ e, w e • e) ↑i = x, erw [finset.sum_attach, finset.sum_filter_of_ne], { rw t.center_mass_eq_of_sum_1 id hw₂ at hw₃, exact hw₃ }, { intros e he hwe contra, apply hwe, rw [contra, zero_smul] } } end
76938c8d2de1b3971913d56a996e56ea098ec7ca
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/measure_theory/integral/interval_integral.lean
1c6c22436579314ac35e65e7146b82124d8c1c9b
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
105,700
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import measure_theory.integral.set_integral import measure_theory.measure.lebesgue import analysis.calculus.fderiv_measurable import analysis.calculus.extend_deriv /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and many versions of the first part of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that it states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ### FTC-2 and corollaries We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming scheme as for the versions of FTC-1. They include: * `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` - most general version, for functions with a right derivative * `interval_integral.integral_eq_sub_of_has_deriv_at'` - version for functions with a derivative on an open set * `interval_integral.integral_deriv_eq_sub'` - version that is easiest to use when computing the integral of a specific function We then derive additional integration techniques from FTC-2: * `interval_integral.integral_mul_deriv_eq_deriv_mul` - integration by parts * `interval_integral.integral_comp_mul_deriv'` - integration by substitution Many applications of these theorems can be found in the file `analysis.special_functions.integrals`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `Ioo` and `Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ## Tags integral, fundamental theorem of calculus -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter open_locale classical topological_space filter ennreal big_operators variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α] [measurable_space E] [normed_group E] open_locale interval /-! ### Almost everywhere on an interval -/ section variables {μ : measure α} {a b : α} {P : α → Prop} lemma ae_interval_oc_iff : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂μ, x ∈ Ioc a b → P x) ∧ (∀ᵐ x ∂μ, x ∈ Ioc b a → P x) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } lemma ae_measurable_interval_oc_iff {μ : measure α} {β : Type*} [measurable_space β] {f : α → β} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] } variables [topological_space α] [opens_measurable_space α] [order_closed_topology α] lemma ae_interval_oc_iff' : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂ (μ.restrict $ Ioc a b), P x) ∧ (∀ᵐ x ∂ (μ.restrict $ Ioc b a), P x) := begin simp_rw ae_interval_oc_iff, rw [ae_restrict_eq, eventually_inf_principal, ae_restrict_eq, eventually_inf_principal] ; exact measurable_set_Ioc end end /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : α → E) (μ : measure α) (a b : α) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ /-- A function is interval integrable with respect to a given measure `μ` on `interval a b` if and only if it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. This is an equivalent defintion of `interval_integrable`. -/ lemma interval_integrable_iff {f : α → E} {a b : α} {μ : measure α} : interval_integrable f μ a b ↔ integrable_on f (Ioc (min a b) (max a b)) μ := by cases le_total a b; simp [h, interval_integrable] /-- If a function is interval integrable with respect to a given measure `μ` on `interval a b` then it is integrable on `Ioc (min a b) (max a b)` with respect to `μ`. -/ lemma interval_integrable.def {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) : integrable_on f (Ioc (min a b) (max a b)) μ := interval_integrable_iff.mp h /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `interval a b`. -/ lemma measure_theory.integrable.interval_integrable {f : α → E} {a b : α} {μ : measure α} (hf : integrable f μ) : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ namespace interval_integrable section variables {f : α → E} {a b c d : α} {μ ν : measure α} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma trans_iterate {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a 0) (a n) := begin induction n with n hn, { simp }, { exact (hn (λ k hk, hint k (hk.trans n.lt_succ_self))).trans (hint n n.lt_succ_self) } end lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ lemma norm [opens_measurable_space E] (h : interval_integrable f μ a b) : interval_integrable (λ x, ∥f x∥) μ a b := ⟨h.1.norm, h.2.norm⟩ lemma abs {f : α → ℝ} (h : interval_integrable f μ a b) : interval_integrable (λ x, abs (f x)) μ a b := h.norm lemma mono (hf : interval_integrable f ν a b) (h1 : interval c d ⊆ interval a b) (h2 : μ ≤ ν) : interval_integrable f μ c d := let ⟨h1₁, h1₂⟩ := interval_subset_interval_iff_le.mp h1 in interval_integrable_iff.mpr $ hf.def.mono (Ioc_subset_Ioc h1₁ h1₂) h2 lemma mono_set (hf : interval_integrable f μ a b) (h : interval c d ⊆ interval a b) : interval_integrable f μ c d := hf.mono h rfl.le lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) : interval_integrable f μ a b := hf.mono rfl.subset h lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ioc (min c d) (max c d) ≤ᵐ[μ] Ioc (min a b) (max a b)) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono_set_ae h protected lemma ae_measurable (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc a b)):= h.1.ae_measurable protected lemma ae_measurable' (h : interval_integrable f μ a b) : ae_measurable f (μ.restrict (Ioc b a)):= h.2.ae_measurable end variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ @[simp] lemma add [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ end interval_integrable section variables {μ : measure ℝ} [locally_finite_measure μ] lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := begin split, all_goals { refine measure_theory.integrable_on.mono_set _ Ioc_subset_Icc_self, refine continuous_on.integrable_on_compact is_compact_Icc (hu.mono _) }, exacts [Icc_subset_interval, Icc_subset_interval'] end lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end section variables {ι : Type*} [topological_space ι] [conditionally_complete_linear_order ι] [order_topology ι] [measurable_space ι] [borel_space ι] {μ : measure ι} [locally_finite_measure μ] [conditionally_complete_linear_order E] [order_topology E] [second_countable_topology E] [borel_space E] lemma interval_integrable_of_monotone_on {u : ι → E} {a b : ι} (hu : ∀ ⦃x y⦄, x ∈ interval a b → y ∈ interval a b → x ≤ y → u x ≤ u y) : interval_integrable u μ a b := begin rw interval_integrable_iff, exact (integrable_on_compact_of_monotone_on is_compact_interval hu).mono_set Ioc_subset_Icc_self, end lemma interval_integrable_of_antimono_on {u : ι → E} {a b : ι} (hu : ∀ ⦃x y⦄, x ∈ interval a b → y ∈ interval a b → x ≤ y → u y ≤ u x) : interval_integrable u μ a b := @interval_integrable_of_monotone_on (order_dual E) _ ‹_› ι _ _ _ _ _ _ _ _ _ ‹_› ‹_› u a b hu lemma interval_integrable_of_monotone {u : ι → E} {a b : ι} (hu : monotone u) : interval_integrable u μ a b := interval_integrable_of_monotone_on (λ x y _ _ hxy, hu hxy) alias interval_integrable_of_monotone ← monotone.interval_integrable lemma interval_integrable_of_antimono {u : ι → E} {a b : ι} (hu : ∀ ⦃x y⦄, x ≤ y → u y ≤ u x) : interval_integrable u μ a b := @interval_integrable_of_monotone (order_dual E) _ ‹_› ι _ _ _ _ _ _ _ _ _ ‹_› ‹_› u a b hu end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α} {l l' : filter α} (hfm : measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [second_countable_topology E] [complete_space E] [normed_space ℝ E] [borel_space E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : α → E) (a b : α) (μ : measure α) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section basic variables {a b : α} {f g : α → E} {μ : measure α} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma integral_cases (f : α → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ioc (min a b) (max a b), f x ∂μ, -∫ x in Ioc (min a b) (max a b), f x ∂μ} : set E) := (le_total a b).imp (λ h, by simp [h, integral_of_le]) (λ h, by simp [h, integral_of_ge]) lemma integral_undef (h : ¬ interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b with hab hab; simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero]; refine integral_undef (not_imp_not.mpr integrable.integrable_on' _); simpa [hab] using not_and_distrib.mp h lemma integral_non_ae_measurable (hf : ¬ ae_measurable f (μ.restrict (Ioc (min a b) (max a b)))) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b; simpa [integral_of_le, integral_of_ge, h] using integral_non_ae_measurable hf lemma integral_non_ae_measurable_of_le (h : a ≤ b) (hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_ae_measurable $ by simpa [h] using hf lemma norm_integral_eq_norm_integral_Ioc : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ := (integral_cases f a b).elim (congr_arg _) (λ h, (congr_arg _ h).trans (norm_neg _)) lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ioc (min a b) (max a b), f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc ... ≤ ∫ x in Ioc (min a b) (max a b), ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ abs (∫ x in a..b, ∥f x∥ ∂μ) := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ioc (min a b) (max a b) → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ioc (min a b) (max a b), ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * abs (b - a) := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h @[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by { simp only [interval_integral, integral_add hf.1 hg.1, integral_add hf.2 hg.2], abel } @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } @[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) @[simp] lemma integral_smul (r : ℝ) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] @[simp] lemma integral_const {a b : ℝ} (c : E) : ∫ x in a..b, c = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ℝ≥0∞) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] end basic section comp variables {a b c d : ℝ} (f : ℝ → E) @[simp] lemma integral_comp_mul_right (hc : c ≠ 0) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : closed_embedding (λ x, x * c) := (homeomorph.mul_right' c hc).closed_embedding, conv_rhs { rw [← real.smul_map_volume_mul_right hc] }, simp_rw [integral_smul_measure, interval_integral, set_integral_map_of_closed_embedding measurable_set_Ioc A, ennreal.to_real_of_real (abs_nonneg c)], cases lt_or_gt_of_ne hc, { simp [h, mul_div_cancel, hc, abs_of_neg, restrict_congr_set Ico_ae_eq_Ioc] }, { simp [(show 0 < c, from h), mul_div_cancel, hc, abs_of_pos] } end @[simp] lemma smul_integral_comp_mul_right (c) : c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_left (hc : c ≠ 0) : ∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] lemma smul_integral_comp_mul_left (c) : c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div (hc : c ≠ 0) : ∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x := by simpa only [inv_inv'] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] lemma inv_smul_integral_comp_div (c) : c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_right (d) : ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x := have A : closed_embedding (λ x, x + d) := (homeomorph.add_right d).closed_embedding, calc ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume) : by simp [interval_integral, set_integral_map_of_closed_embedding _ A] ... = ∫ x in a+d..b+d, f x : by rw [real.map_volume_add_right] @[simp] lemma integral_comp_add_left (d) : ∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x := by simpa only [add_comm] using integral_comp_add_right f d @[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_mul_add (c d) : c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_add_mul (c d) : c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_add (c d) : c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_add_div (c d) : c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] lemma smul_integral_comp_mul_sub (c d) : c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x := begin simp only [sub_eq_add_neg, neg_mul_eq_neg_mul], rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm], simp only [inv_neg, smul_neg, neg_neg, neg_smul], end @[simp] lemma smul_integral_comp_sub_mul (c d) : c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_sub (c d) : c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x := by simpa only [div_eq_inv_mul, inv_inv'] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_sub_div (c d) : c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_right (d) : ∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] lemma integral_comp_sub_left (d) : ∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end comp /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ section order_closed_topology variables [topological_space α] [order_closed_topology α] [opens_measurable_space α] {a b c d : α} {f g : α → E} {μ : measure α} lemma integral_Icc_eq_integral_Ioc {f : α → E} {a b : α} (ha : μ {a} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := begin cases le_or_lt a b with hab hab, { have : μ.restrict (Icc a b) = μ.restrict (Ioc a b), { rw [← Ioc_union_left hab, measure_theory.measure.restrict_union _ measurable_set_Ioc (measurable_set_singleton a)], { simp [measure_theory.measure.restrict_zero_set ha] }, { simp } }, rw this }, { simp [hab, hab.le] } end /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : α} (h : eq_on f g (interval a b)) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge] using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self) lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, ← add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma sum_integral_adjacent_intervals {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := begin induction n with n hn, { simp }, { rw [finset.sum_range_succ, hn (λ k hk, hint k (hk.trans n.lt_succ_self))], exact integral_add_adjacent_intervals (interval_integrable.trans_iterate $ λ k hk, hint k (hk.trans n.lt_succ_self)) (hint n n.lt_succ_self) } end lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc (le_refl _)), Iic_union_Ioc_eq_Iic hab], exacts [measurable_set_Iic, measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : function.support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, function.support_eq_empty_iff] at h, simp [h] } end lemma integral_congr_ae' {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h, set_integral_congr_ae (measurable_set_Ioc) h'] lemma integral_congr_ae {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ := integral_congr_ae' (ae_interval_oc_iff.mp h).1 (ae_interval_oc_iff.mp h).2 lemma integral_zero_ae {f : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ (x : α) in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h ... = 0 : integral_zero lemma integral_indicator {a₁ a₂ a₃ : α} (h : a₂ ∈ Icc a₁ a₃) {f : α → E} : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ := begin have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2, rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, measure.restrict_restrict, this], exact measurable_set_Iic, all_goals { apply measurable_set_Iic }, end end order_closed_topology section continuity_wrt_parameter open topological_space variables {X : Type*} [topological_space X] [first_countable_topology X] variables {μ : measure α} /-- Continuity of interval integral with respect to a parameter, at a point within a set. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)` is continuous at `x₀` within `s` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_within_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} {s : set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (hF_meas₀ : ae_measurable (F x₀) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_within_at (λ x, F x t) s x₀) : continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ := begin have gcs := is_countably_generated_nhds_within x₀ s, cases bound_integrable, cases le_or_lt a b with hab hab; [{ rw interval_oc_of_le hab at *, simp_rw interval_integral.integral_of_le hab }, { rw interval_oc_of_lt hab at *, simp_rw interval_integral.integral_of_ge hab.le, refine tendsto.neg _ }]; apply tendsto_integral_filter_of_dominated_convergence bound gcs hF_meas hF_meas₀ h_bound, exacts [bound_integrable_left, h_cont, bound_integrable_right, h_cont] end /-- Continuity of interval integral with respect to a parameter at a point. Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)` is continuous at `x₀` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_at_of_dominated_interval {F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous_at (λ x, F x t) x₀) : continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ := begin rw ← continuous_within_at_univ, apply continuous_within_at_of_dominated_interval ; try { rw nhds_within_univ}, exacts [hF_meas, (mem_of_mem_nhds hF_meas : _), h_bound, bound_integrable, h_cont.mono (λ a, (continuous_within_at_univ (λ x, F x a) x₀).mpr)] end /-- Continuity of interval integral with respect to a parameter. Given `F : X → α → E`, assume each `F x` is ae-measurable on `[a, b]`, and assume it is bounded by a function integrable on `[a, b]` independent of `x`. If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_of_dominated_interval {F : X → α → E} {bound : α → ℝ} {a b : α} (hF_meas : ∀ x, ae_measurable (F x) $ μ.restrict $ Ι a b) (h_bound : ∀ x, ∀ᵐ t ∂(μ.restrict $ Ι a b), ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂(μ.restrict $ Ι a b), continuous (λ x, F x t)) : continuous (λ x, ∫ t in a..b, F x t ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval (eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $ λ _, continuous.continuous_at) end continuity_wrt_parameter section continuous_primitive open topological_space variables [topological_space α] [order_topology α] [opens_measurable_space α] [first_countable_topology α] {a b : α} {μ : measure α} lemma continuous_within_at_primitive {f : α → E} {a b₀ b₁ b₂ : α} (hb₀ : μ {b₀} = 0) (h_int : interval_integrable f μ (min a b₁) (max a b₂)) : continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ := begin by_cases h₀ : b₀ ∈ Icc b₁ b₂, { have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2, have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂, have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x, { rintros x ⟨h₁, h₂⟩, apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_right a b₁), h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ }, { exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁, le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } }, have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ, { rintros b ⟨h₁, h₂⟩, rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩), apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ }, { exact ⟨min_le_of_left_le (min_le_right _ _), le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } }, apply continuous_within_at.congr _ this (this _ h₀), clear this, refine continuous_within_at_const.add _, have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀] λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ, { apply eventually_eq_of_mem self_mem_nhds_within, exact λ b b_in, (integral_indicator b_in).symm }, apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm, have : interval_integrable (λ x, ∥f x∥) μ b₁ b₂, from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂), refine continuous_within_at_of_dominated_interval _ _ _ this _ ; clear this, { apply eventually.mono (self_mem_nhds_within), intros x hx, erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' hx).1.ae_measurable }, { exact le_max_of_le_right hx.2 }, exacts [measurable_set_Iic, measurable_set_Iic] }, { erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' h₀).1.ae_measurable }, { exact le_max_of_le_right h₀.2 }, exact measurable_set_Iic, exact measurable_set_Iic }, { refine eventually_of_forall (λ (x : α), eventually_of_forall (λ (t : α), _)), dsimp [indicator], split_ifs ; simp }, { have : ∀ᵐ t ∂μ.restrict (Ι b₁ b₂), t < b₀ ∨ b₀ < t, { apply ae_restrict_of_ae, apply eventually.mono (compl_mem_ae_iff.mpr hb₀), intros x hx, exact ne.lt_or_lt hx }, apply this.mono, rintros x₀ (hx₀ | hx₀), { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = f x₀, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Ioi_mem_nhds hx₀), intros x hx, simp [hx.le] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀.le] }, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = 0, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Iio_mem_nhds hx₀), intros x hx, simp [hx] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀] } } }, { apply continuous_within_at_of_not_mem_closure, rwa [closure_Icc] } end lemma continuous_on_primitive {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) := begin by_cases h : a ≤ b, { have : ∀ x ∈ Icc a b, ∫ (t : α) in Ioc a x, f t ∂μ = ∫ (t : α) in a..x, f t ∂μ, { intros x x_in, simp_rw [← interval_oc_of_le h, integral_of_le x_in.1] }, rw continuous_on_congr this, intros x₀ hx₀, refine continuous_within_at_primitive (measure_singleton x₀) _, rw interval_integrable_iff, simp only [h, max_eq_right, min_eq_left], exact h_int.mono Ioc_subset_Icc_self le_rfl }, { rw Icc_eq_empty h, exact continuous_on_empty _ }, end lemma continuous_on_primitive' {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) := begin rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ, by { ext x, exact integral_Icc_eq_integral_Ioc (measure_singleton a) }, exact continuous_on_primitive h_int end lemma continuous_on_primitive'' {f : α → E} {a b : α} [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (Icc a b) := (continuous_on_primitive h_int).congr (λ x₀ hx₀, integral_of_le hx₀.1) variables [no_bot_order α] [no_top_order α] [has_no_atoms μ] lemma continuous_primitive {f : α → E} (h_int : ∀ a b : α, interval_integrable f μ a b) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := begin rw continuous_iff_continuous_at, intro b₀, cases no_bot b₀ with b₁ hb₁, cases no_top b₀ with b₂ hb₂, apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂), exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _) end lemma _root_.measure_theory.integrable.continuous_primitive {f : α → E} (h_int : integrable f μ) (a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := continuous_primitive (λ _ _, h_int.interval_integrable) a end continuous_primitive section variables {f g : α → ℝ} {a b : α} {μ : measure α} lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] } end lemma integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (function.support f ∩ Ioc a b) := begin obtain hab | hab := le_total b a; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { rw [←not_iff_not, not_and_distrib, not_lt, not_lt, integral_of_ge hab, neg_nonpos], exact iff_of_true (integral_nonneg_of_ae hf) (or.intro_left _ hab) }, rw [integral_of_le hab, set_integral_pos_iff_support_of_nonneg_ae hf hfi.1, iff.comm, and_iff_right_iff_imp], contrapose!, intro h, rw [Ioc_eq_empty h.not_lt, inter_empty, measure_empty], exact le_refl 0, end lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (function.support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi variable (hab : a ≤ b) include hab lemma integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H lemma integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf lemma integral_nonneg_of_forall (hf : ∀ u, 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae hab $ eventually_of_forall hf lemma integral_nonneg [topological_space α] [opens_measurable_space α] [order_closed_topology α] (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf lemma norm_integral_le_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in a..b, ∥f x∥ ∂μ := norm_integral_le_abs_integral_norm.trans_eq $ abs_of_nonneg $ integral_nonneg_of_forall hab $ λ x, norm_nonneg _ lemma abs_integral_le_integral_abs : abs (∫ x in a..b, f x ∂μ) ≤ ∫ x in a..b, abs (f x) ∂μ := norm_integral_le_integral_norm hab section mono variables (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) include hf hg lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H lemma integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h lemma integral_mono_on [topological_space α] [opens_measurable_space α] [order_closed_topology α] (h : ∀ x ∈ Icc a b, f x ≤ g x) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := λ x hx, h x $ Ioc_subset_Icc_self hx in by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H lemma integral_mono (h : f ≤ g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg $ ae_of_all _ h end mono end /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a] a, 𝓝[Ioi a] a)`, `(a, 𝓝[Iic a] a, 𝓝[Iic a] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. There are four instances: `(a, pure a, ⊥)`, `(a, 𝓝[Ici a], 𝓝[Ioi a])`, `(a, 𝓝[Iic a], 𝓝[Iic a])`, and `(a, 𝓝 a, 𝓝 a)`. -/ class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β] (a : out_param β) (outer : filter β) (inner : out_param $ filter β) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter variables [linear_order β] [measurable_space β] [topological_space β] instance pure (a : β) : FTC_filter a (pure a) ⊥ := { pure_le := le_refl _, le_nhds := bot_le } instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l'] {μ : measure β} [locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds variables [opens_measurable_space β] [order_topology β] instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_refl _ } instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : β) : FTC_filter a (𝓝[Iic a] a) (𝓝[Iic a] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : β) : FTC_filter a (𝓝[Ici a] a) (𝓝[Ioi a] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } end FTC_filter open asymptotics section variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β} {μ : measure α} {u v ua va ub vb : β → α} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[locally_finite_measure μ]`. If `l` is one of `𝓝[Ici a] a`, `𝓝[Iic a] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] variables [topological_space α] section variables [locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end variables [order_topology α] [borel_space α] local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ eventually_eq.rfl, have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'], intros t ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β} {a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- **First Fundamental Theorem of Calculus**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s.prod t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s.prod t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s.prod t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[Iic a] a` | `Iic b` | `𝓝[Iic b] b` | | `Ici a` | `𝓝[Ioi a] a` | `Ici b` | `𝓝[Ioi b] b` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s.prod t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals. -/ variable {f' : ℝ → E} /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.measurable.ae_measurable.measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-- The integral of a continuous function is continuous on a real set `s`. This is true even without the assumption of continuity, but a proof of that fact does not yet exist in mathlib. -/ theorem continuous_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : continuous_on (λ u, ∫ x in a..u, f x) s := (differentiable_on_integral_of_continuous hintg hcont).continuous_on /-- **Second Fundamental Theorem of Calculus**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (Icc a b)) : ∫ y in a..b, f' y = f b - f a := begin have hmeas' : ae_measurable f' (volume.restrict (Icc a b)), from hcont'.ae_measurable measurable_set_Icc, refine eq_sub_of_add_eq (eq_of_has_deriv_right_eq (λ y hy, _) hderiv (λ y hy, _) hcont (by simp) _ (right_mem_Icc.2 hab)), { refine (integral_has_deriv_within_at_right _ _ _).add_const _, { refine (hcont'.mono _).interval_integrable, simp only [hy.left, Icc_subset_Icc_right hy.right.le, interval_of_le] }, { exact ⟨_, Icc_mem_nhds_within_Ioi hy, hmeas'⟩, }, { exact (hcont' _ (mem_Icc_of_Ico hy)).mono_of_mem (Icc_mem_nhds_within_Ioi hy) } }, { -- TODO: prove that the integral of any integrable function is continuous and use here letI : tendsto_Ixx_class Ioc (𝓟 (Icc a b)) (𝓟 (Ioc a b)) := tendsto_Ixx_class_principal.2 (λ x hx y hy, Ioc_subset_Ioc hx.1 hy.2), haveI : is_measurably_generated (𝓝[Ioc a b] y) := measurable_set_Ioc.nhds_within_is_measurably_generated y, letI : FTC_filter y (𝓝[Icc a b] y) (𝓝[Ioc a b] y) := ⟨pure_le_nhds_within hy, inf_le_left⟩, refine (integral_has_deriv_within_at_right _ _ _).continuous_within_at.add continuous_within_at_const, { exact (hcont'.mono $ Icc_subset_Icc_right hy.2).interval_integrable_of_Icc hy.1 }, { exact ⟨_, mem_of_superset self_mem_nhds_within Ioc_subset_Icc_self, hmeas'⟩ }, { exact (hcont' y hy).mono Ioc_subset_Icc_self } } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is continuous on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ico (min a b) (max a b), has_deriv_within_at f (f' x) (Ici x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hcont' hderiv, exact integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont' }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hcont' hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hcont', neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at' (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin refine integral_eq_sub_of_has_deriv_right hcont _ hcont', intros y hy', obtain (hy | hy) : y ∈ Ioo (min a b) (max a b) ∨ min a b = y ∧ y < max a b, { simpa only [le_iff_lt_or_eq, or_and_distrib_right, mem_Ioo, mem_Ico] using hy' }, { exact (hderiv y hy).has_deriv_within_at }, { refine has_deriv_at_interval_left_endpoint_of_tendsto_deriv (λ x hx, (hderiv x hx).has_deriv_within_at.differentiable_within_at) _ _ _, { exact (hcont y (Ico_subset_Icc_self hy')).mono Ioo_subset_Icc_self }, { exact Ioo_mem_nhds_within_Ioi hy' }, { have : tendsto f' (𝓝[Ioi y] y) (𝓝 (f' y)), { refine tendsto.mono_left _ (nhds_within_mono y Ioi_subset_Ici_self), have h := hcont'.continuous_within_at (left_mem_Icc.mpr min_le_max), simpa only [← nhds_within_Icc_eq_nhds_within_Ici hy.2, interval, hy.1] using h }, have h := eventually_of_mem (Ioo_mem_nhds_within_Ioi hy') (λ x hx, (hderiv x hx).deriv), rwa tendsto_congr' h } }, end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at'_of_le (hab : a ≤ b) (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_at' hcont (by rwa [min_eq_left hab, max_eq_right hab]) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is continuous on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_at' (has_deriv_at.continuous_on hderiv) (λ x hx, hderiv _ (mem_Icc_of_Ioo hx)) hcont' /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is continuous on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont' : continuous_on (deriv f) (interval a b)) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hcont' theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f') (hdiff : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont' : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := by rw [← hderiv, integral_deriv_eq_sub hdiff]; cc /-! ### Integration by parts -/ theorem integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hcu' : continuous_on u' (interval a b)) (hcv' : continuous_on v' (interval a b)) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_eq_sub_of_has_deriv_at (λ x hx, (hu x hx).mul (hv x hx)) $ (hcu'.mul (has_deriv_at.continuous_on hv)).add ((has_deriv_at.continuous_on hu).mul hcv') theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hcu' : continuous_on u' (interval a b)) (hcv' : continuous_on v' (interval a b)) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x := begin have hcv := has_deriv_at.continuous_on hv, rw [← integral_deriv_mul_eq_sub hu hv hcu' hcv', ← integral_sub], { exact integral_congr (λ x hx, by simp only [mul_comm, add_sub_cancel']) }, { exact ((hcu'.mul hcv).add ((has_deriv_at.continuous_on hu).mul hcv')).interval_integrable }, { exact (hcv.mul hcu').interval_integrable }, end /-! ### Integration by substitution / Change of variables -/ theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hf' : continuous_on f' (interval a b)) (hg : ∀ x ∈ f '' (interval a b), continuous_at g x) (hgm : ∀ x ∈ f '' (interval a b), measurable_at_filter g (𝓝 x)) : -- TODO: prove that the integral of any integrable function is continuous and use here to remove -- assumption `hgm` ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := let hg' := continuous_at.continuous_on hg in have h : ∀ x ∈ interval a b, has_deriv_at (λ u, ∫ t in f a..f u, g t) ((g ∘ f) x * f' x) x, { intros x hx, have hs := interval_subset_interval_left hx, exact (integral_has_deriv_at_right (hg'.mono $ trans (intermediate_value_interval $ has_deriv_at.continuous_on $ λ y hy, hf y $ hs hy) $ image_subset f hs).interval_integrable (hgm (f x) ⟨x, hx, rfl⟩) $ hg (f x) ⟨x, hx, rfl⟩).comp _ (hf x hx) }, by simp_rw [integral_eq_sub_of_has_deriv_at h $ (hg'.comp (has_deriv_at.continuous_on hf) $ subset_preimage_image f _).mul hf', integral_same, sub_zero] theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := integral_comp_mul_deriv' h h' (λ x h, hg.continuous_at) (λ x h, hg.measurable.measurable_at_filter) theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval (f a) (f b), has_deriv_at g (g' x) x) (hf' : continuous_on f' (interval a b)) (hg1 : continuous_on g' (interval (f a) (f b))) (hg2 : ∀ x ∈ f '' (interval a b), continuous_at g' x) (hgm : ∀ x ∈ f '' (interval a b), measurable_at_filter g' (𝓝 x)) : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by rw [integral_comp_mul_deriv' hf hf' hg2 hgm, integral_eq_sub_of_has_deriv_at hg hg1] theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := integral_eq_sub_of_has_deriv_at (λ x hx, (hg x hx).comp x $ hf x hx) $ (hg'.comp_continuous_on $ has_deriv_at.continuous_on hf).mul hf' end interval_integral
59ad9ac53d16055755d44fea9fa6f7d84e2ab943
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/perm/sign.lean
e4bf4b0d7c664e7923004d371159217d9adc71e0
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,249
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 data.fintype.basic import data.finset.sort import data.nat.parity import group_theory.perm.support import group_theory.order_of_element import tactic.norm_swap import group_theory.quotient_group /-! # Sign of a permutation The main definition of this file is `equiv.perm.sign`, associating a `units ℤ` sign with a permutation. This file also contains miscellaneous lemmas about `equiv.perm` and `equiv.swap`, building on top of those in `data/equiv/basic` and other files in `group_theory/perm/*`. -/ universes u v open equiv function fintype finset open_locale big_operators variables {α : Type u} {β : Type v} namespace equiv.perm /-- `mod_swap i j` contains permutations up to swapping `i` and `j`. We use this to partition permutations in `matrix.det_zero_of_row_eq`, such that each partition sums up to `0`. -/ def mod_swap [decidable_eq α] (i j : α) : setoid (perm α) := ⟨λ σ τ, σ = τ ∨ σ = swap i j * τ, λ σ, or.inl (refl σ), λ σ τ h, or.cases_on h (λ h, or.inl h.symm) (λ h, or.inr (by rw [h, swap_mul_self_mul])), λ σ τ υ hστ hτυ, by cases hστ; cases hτυ; try {rw [hστ, hτυ, swap_mul_self_mul]}; finish⟩ instance {α : Type*} [fintype α] [decidable_eq α] (i j : α) : decidable_rel (mod_swap i j).r := λ σ τ, or.decidable lemma perm_inv_on_of_perm_on_finset {s : finset α} {f : perm α} (h : ∀ x ∈ s, f x ∈ s) {y : α} (hy : y ∈ s) : f⁻¹ y ∈ s := begin have h0 : ∀ y ∈ s, ∃ x (hx : x ∈ s), y = (λ i (hi : i ∈ s), f i) x hx := finset.surj_on_of_inj_on_of_card_le (λ x hx, (λ i hi, f i) x hx) (λ a ha, h a ha) (λ a₁ a₂ ha₁ ha₂ heq, (equiv.apply_eq_iff_eq f).mp heq) rfl.ge, obtain ⟨y2, hy2, heq⟩ := h0 y hy, convert hy2, rw heq, simp only [inv_apply_self] end lemma perm_inv_maps_to_of_maps_to (f : perm α) {s : set α} [fintype s] (h : set.maps_to f s s) : set.maps_to (f⁻¹ : _) s s := λ x hx, set.mem_to_finset.mp $ perm_inv_on_of_perm_on_finset (λ a ha, set.mem_to_finset.mpr (h (set.mem_to_finset.mp ha))) (set.mem_to_finset.mpr hx) @[simp] lemma perm_inv_maps_to_iff_maps_to {f : perm α} {s : set α} [fintype s] : set.maps_to (f⁻¹ : _) s s ↔ set.maps_to f s s := ⟨perm_inv_maps_to_of_maps_to f⁻¹, perm_inv_maps_to_of_maps_to f⟩ lemma perm_inv_on_of_perm_on_fintype {f : perm α} {p : α → Prop} [fintype {x // p x}] (h : ∀ x, p x → p (f x)) {x : α} (hx : p x) : p (f⁻¹ x) := begin letI : fintype ↥(show set α, from p) := ‹fintype {x // p x}›, exact perm_inv_maps_to_of_maps_to f h hx end /-- If the permutation `f` maps `{x // p x}` into itself, then this returns the permutation on `{x // p x}` induced by `f`. Note that the `h` hypothesis is weaker than for `equiv.perm.subtype_perm`. -/ abbreviation subtype_perm_of_fintype (f : perm α) {p : α → Prop} [fintype {x // p x}] (h : ∀ x, p x → p (f x)) : perm {x // p x} := f.subtype_perm (λ x, ⟨h x, λ h₂, f.inv_apply_self x ▸ perm_inv_on_of_perm_on_fintype h h₂⟩) @[simp] lemma subtype_perm_of_fintype_apply (f : perm α) {p : α → Prop} [fintype {x // p x}] (h : ∀ x, p x → p (f x)) (x : {x // p x}) : subtype_perm_of_fintype f h x = ⟨f x, h x x.2⟩ := rfl @[simp] lemma subtype_perm_of_fintype_one (p : α → Prop) [fintype {x // p x}] (h : ∀ x, p x → p ((1 : perm α) x)) : @subtype_perm_of_fintype α 1 p _ h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl lemma perm_maps_to_inl_iff_maps_to_inr {m n : Type*} [fintype m] [fintype n] (σ : equiv.perm (m ⊕ n)) : set.maps_to σ (set.range sum.inl) (set.range sum.inl) ↔ set.maps_to σ (set.range sum.inr) (set.range sum.inr) := begin split; id { intros h, classical, rw ←perm_inv_maps_to_iff_maps_to at h, intro x, cases hx : σ x with l r, }, { rintros ⟨a, rfl⟩, obtain ⟨y, hy⟩ := h ⟨l, rfl⟩, rw [←hx, σ.inv_apply_self] at hy, exact absurd hy sum.inl_ne_inr}, { rintros ⟨a, ha⟩, exact ⟨r, rfl⟩, }, { rintros ⟨a, ha⟩, exact ⟨l, rfl⟩, }, { rintros ⟨a, rfl⟩, obtain ⟨y, hy⟩ := h ⟨r, rfl⟩, rw [←hx, σ.inv_apply_self] at hy, exact absurd hy sum.inr_ne_inl}, end lemma mem_sum_congr_hom_range_of_perm_maps_to_inl {m n : Type*} [fintype m] [fintype n] {σ : perm (m ⊕ n)} (h : set.maps_to σ (set.range sum.inl) (set.range sum.inl)) : σ ∈ (sum_congr_hom m n).range := begin classical, have h1 : ∀ (x : m ⊕ n), (∃ (a : m), sum.inl a = x) → (∃ (a : m), sum.inl a = σ x), { rintros x ⟨a, ha⟩, apply h, rw ← ha, exact ⟨a, rfl⟩ }, have h3 : ∀ (x : m ⊕ n), (∃ (b : n), sum.inr b = x) → (∃ (b : n), sum.inr b = σ x), { rintros x ⟨b, hb⟩, apply (perm_maps_to_inl_iff_maps_to_inr σ).mp h, rw ← hb, exact ⟨b, rfl⟩ }, let σ₁' := subtype_perm_of_fintype σ h1, let σ₂' := subtype_perm_of_fintype σ h3, let σ₁ := perm_congr (equiv.of_injective (@sum.inl m n) sum.inl_injective).symm σ₁', let σ₂ := perm_congr (equiv.of_injective (@sum.inr m n) sum.inr_injective).symm σ₂', rw [monoid_hom.mem_range, prod.exists], use [σ₁, σ₂], rw [perm.sum_congr_hom_apply], ext, cases x with a b, { rw [equiv.sum_congr_apply, sum.map_inl, perm_congr_apply, equiv.symm_symm, apply_of_injective_symm (@sum.inl m n)], erw subtype_perm_apply, rw [of_injective_apply, subtype.coe_mk, subtype.coe_mk] }, { rw [equiv.sum_congr_apply, sum.map_inr, perm_congr_apply, equiv.symm_symm, apply_of_injective_symm (@sum.inr m n)], erw subtype_perm_apply, rw [of_injective_apply, subtype.coe_mk, subtype.coe_mk] } end lemma disjoint.order_of {σ τ : perm α} (hστ : disjoint σ τ) : order_of (σ * τ) = nat.lcm (order_of σ) (order_of τ) := begin have h : ∀ n : ℕ, (σ * τ) ^ n = 1 ↔ σ ^ n = 1 ∧ τ ^ n = 1 := λ n, by rw [hστ.commute.mul_pow, disjoint.mul_eq_one_iff (hστ.pow_disjoint_pow n n)], exact nat.dvd_antisymm hστ.commute.order_of_mul_dvd_lcm (nat.lcm_dvd (order_of_dvd_of_pow_eq_one ((h (order_of (σ * τ))).mp (pow_order_of_eq_one (σ * τ))).1) (order_of_dvd_of_pow_eq_one ((h (order_of (σ * τ))).mp (pow_order_of_eq_one (σ * τ))).2)), end lemma disjoint.extend_domain {α : Type*} {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {σ τ : perm α} (h : disjoint σ τ) : disjoint (σ.extend_domain f) (τ.extend_domain f) := begin intro b, by_cases pb : p b, { refine (h (f.symm ⟨b, pb⟩)).imp _ _; { intro h, rw [extend_domain_apply_subtype _ _ pb, h, apply_symm_apply, subtype.coe_mk] } }, { left, rw [extend_domain_apply_not_subtype _ _ pb] } end variable [decidable_eq α] section fintype variable [fintype α] lemma support_pow_coprime {σ : perm α} {n : ℕ} (h : nat.coprime n (order_of σ)) : (σ ^ n).support = σ.support := begin obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h, exact le_antisymm (support_pow_le σ n) (le_trans (ge_of_eq (congr_arg support hm)) (support_pow_le (σ ^ n) m)), end end fintype /-- Given a list `l : list α` and a permutation `f : perm α` such that the nonfixed points of `f` are in `l`, recursively factors `f` as a product of transpositions. -/ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext $ λ x, by { rw [list.prod_nil], exact (not_not.1 (mt h (list.not_mem_nil _))).symm }, by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used. -/ def swap_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- This computably represents the fact that any permutation can be represented as the product of a list of transpositions. -/ def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) /-- An induction principle for permutations. If `P` holds for the identity permutation, and is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/ @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases (trunc_swap_factors f).out with l hl, induction l with g l ih generalizing f, { simp only [hl.left.symm, list.prod_nil, forall_true_iff] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma closure_is_swap [fintype α] : subgroup.closure {σ : perm α | is_swap σ} = ⊤ := begin refine eq_top_iff.mpr (λ x hx, _), obtain ⟨h1, h2⟩ := subtype.mem (trunc_swap_factors x).out, rw ← h1, exact subgroup.list_prod_mem _ (λ y hy, subgroup.subset_closure (h2 y hy)), end /-- Like `swap_induction_on`, but with the composition on the right of `f`. An induction principle for permutations. If `P` holds for the identity permutation, and is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/ @[elab_as_eliminator] lemma swap_induction_on' [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (f * swap x y)) → P f := λ h1 IH, inv_inv f ▸ swap_induction_on f⁻¹ h1 (λ f, IH f⁻¹) lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := is_conj_iff.2 (have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩) /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a).attach_fin (λ m hm, (mem_range.1 hm).trans a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp only [fin_pairs_lt, fin.lt_iff_coe_lt_coe, true_and, mem_attach_fin, mem_range, mem_univ, mem_sigma] /-- `sign_aux σ` is the sign of a permutation on `fin n`, defined as the parity of the number of pairs `(x₁, x₂)` such that `x₂ < x₁` but `σ x₁ ≤ σ x₂` -/ def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := ∏ x in fin_pairs_lt n, if a x.1 ≤ a x.2 then -1 else 1 @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one (units ℤ) _ (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (mem_fin_pairs_lt.1 ha).not_le) end /-- `sign_bij_aux f ⟨a, b⟩` returns the pair consisting of `f a` and `f b` in decreasing order. -/ def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := hb.le.not_lt, split_ifs at h; simp only [*, (equiv.injective f).eq_iff, eq_self_iff_true, and_self, heq_iff_eq] at *, end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by { dsimp [sign_bij_aux], rw [apply_inv_self, apply_inv_self, if_pos (mem_fin_pairs_lt.1 ha)] }⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ (le_of_not_gt hxa).lt_of_ne $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by { dsimp [sign_bij_aux], rw [apply_inv_self, apply_inv_self, if_neg (mem_fin_pairs_lt.1 ha).le.not_lt] }⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)} : ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 ((le_of_not_gt h).lt_of_ne (λ h, (mem_fin_pairs_lt.1 ha).ne (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg h.not_le, apply_inv_self, apply_inv_self, if_neg (mem_fin_pairs_lt.1 hab).not_le] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (mem_fin_pairs_lt.1 hab).le]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp only [not_le_of_gt hab, mul_one, perm.inv_apply_self, if_false] }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos hab.le], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, f.injective.eq_iff, g.injective.eq_iff], exact ne_of_lt hab }, rw [if_pos h₁, if_neg (h₁.lt_of_ne this).not_le], refl }, { rw [if_neg h₁, if_pos (lt_of_not_ge h₁).le], refl } } end private lemma sign_aux_swap_zero_one' (n : ℕ) : sign_aux (swap (0 : fin (n + 2)) 1) = -1 := show _ = ∏ x : Σ a : fin (n + 2), fin (n + 2) in {(⟨1, 0⟩ : Σ a : fin (n + 2), fin (n + 2))}, if (equiv.swap 0 1) x.1 ≤ swap 0 1 x.2 then (-1 : units ℤ) else 1, begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, fin.one_pos] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨a₁, a₂⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, dsimp only, rcases a₁.zero_le.eq_or_lt with rfl|H, { exact absurd a₂.zero_le ha₁.not_le }, rcases a₂.zero_le.eq_or_lt with rfl|H', { simp only [and_true, eq_self_iff_true, heq_iff_eq, mem_singleton] at ha₂, have : 1 < a₁ := lt_of_le_of_ne (nat.succ_le_of_lt ha₁) (ne.symm ha₂), have h01 : equiv.swap (0 : fin (n + 2)) 1 0 = 1, by simp, -- TODO : fix properly norm_num [swap_apply_of_ne_of_ne (ne_of_gt H) ha₂, this.not_le, h01] }, { have le : 1 ≤ a₂ := nat.succ_le_of_lt H', have lt : 1 < a₁ := le.trans_lt ha₁, have h01 : equiv.swap (0 : fin (n + 2)) 1 1 = 0, by simp, -- TODO rcases le.eq_or_lt with rfl|lt', { norm_num [swap_apply_of_ne_of_ne H.ne' lt.ne', H.not_le, h01] }, { norm_num [swap_apply_of_ne_of_ne (ne_of_gt H) (ne_of_gt lt), swap_apply_of_ne_of_ne (ne_of_gt H') (ne_of_gt lt'), ha₁.not_le] } } end private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := begin rcases n with _|_|n, { norm_num at hn }, { norm_num at hn }, { exact sign_aux_swap_zero_one' n } end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by { rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n], exact (monoid_hom.mk' sign_aux sign_aux_mul).map_is_conj (is_conj_swap hxy dec_trivial) } /-- When the list `l : list α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 l f` recursively calculates the sign of `f`. -/ def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, by ext; simp [← equiv.symm_trans_swap_trans, mul_def], have hefx : e x ≠ e (f x), from mt e.injective.eq_iff.1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp only [units.neg_neg, one_mul, units.neg_mul]} end /-- When the multiset `s : multiset α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 f _` recursively calculates the sign of `f`. -/ def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (fintype.trunc_equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp only [h.mem_iff]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let e := equiv_fin α in begin clear _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt e.injective.eq_iff.1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] : perm α →* units ℤ := monoid_hom.mk' (λ f, sign_aux3 f mem_univ) (λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1) section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := monoid_hom.map_mul sign f g @[simp] lemma sign_trans (f g : perm α) : sign (f.trans g) = sign g * sign f := by rw [←mul_def, sign_mul] @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := monoid_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := monoid_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [monoid_hom.map_inv sign f, int.units_inv_eq_self] @[simp] lemma sign_symm (e : perm α) : sign e.symm = sign e := sign_inv e lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma is_swap.sign_eq {f : perm α} (h : f.is_swap) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := equiv_fin β in by { rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)], exact congr_arg sign_aux (equiv.ext (λ x, by simp only [equiv.coe_trans, apply_eq_iff_eq, symm_trans_apply])) }) ht hs @[simp] lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ @[simp] lemma sign_trans_trans_symm [decidable_eq β] [fintype β] (f : perm β) (e : α ≃ β) : sign ((e.trans f).trans e.symm) = sign f := sign_symm_trans_trans f e.symm lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = (-1) ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ (hl _ hg.1).sign_eq⟩, by rw [← list.prod_repeat, ← h₁, list.prod_hom _ (@sign α _ _)] variable (α) lemma sign_surjective [nontrivial α] : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x, y, hxy⟩ := exists_pair_ne α in ⟨swap x y, by rw [sign_swap hxy, h]⟩ ) variable {α} lemma eq_sign_of_surjective_hom {s : perm α →* units ℤ} (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by { rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab'], exact s.map_is_conj (is_conj_swap hab hxy) }, let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := (trunc_swap_factors g).out in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [← l.prod_hom s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by { rw [hl.1, hg] at this, exact absurd this dec_trivial }), monoid_hom.ext $ λ f, let ⟨l, hl₁, hl₂⟩ := (trunc_swap_factors f).out in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, ← l.prod_hom s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := (trunc_swap_factors (subtype_perm f h₁)).out in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ (l.2.2 _ hg.1).of_subtype_is_swap, have hl'₂ : (l.1.map of_subtype).prod = f, by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂], by { conv { congr, rw ← l.2.1, skip, rw ← hl'₂ }, rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] } @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : (sign_subtype_perm _ _ (λ _, id)).symm ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by { rw [← h _ x.2 this], exact mt (hi _ _ this x.2) x.2 }⟩ : {y // g y ≠ y})) ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) /-- If we apply `prod_extend_right a (σ a)` for all `a : α` in turn, we get `prod_congr_right σ`. -/ lemma prod_prod_extend_right {α : Type*} [decidable_eq α] (σ : α → perm β) {l : list α} (hl : l.nodup) (mem_l : ∀ a, a ∈ l) : (l.map (λ a, prod_extend_right a (σ a))).prod = prod_congr_right σ := begin ext ⟨a, b⟩ : 1, -- We'll use induction on the list of elements, -- but we have to keep track of whether we already passed `a` in the list. suffices : (a ∈ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, σ a b)) ∨ (a ∉ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, b)), { obtain ⟨_, prod_eq⟩ := or.resolve_right this (not_and.mpr (λ h _, h (mem_l a))), rw [prod_eq, prod_congr_right_apply] }, clear mem_l, induction l with a' l ih, { refine or.inr ⟨list.not_mem_nil _, _⟩, rw [list.map_nil, list.prod_nil, one_apply] }, rw [list.map_cons, list.prod_cons, mul_apply], rcases ih (list.nodup_cons.mp hl).2 with ⟨mem_l, prod_eq⟩ | ⟨not_mem_l, prod_eq⟩; rw prod_eq, { refine or.inl ⟨list.mem_cons_of_mem _ mem_l, _⟩, rw prod_extend_right_apply_ne _ (λ (h : a = a'), (list.nodup_cons.mp hl).1 (h ▸ mem_l)) }, by_cases ha' : a = a', { rw ← ha' at *, refine or.inl ⟨l.mem_cons_self a, _⟩, rw prod_extend_right_apply_eq }, { refine or.inr ⟨λ h, not_or ha' not_mem_l ((list.mem_cons_iff _ _ _).mp h), _⟩, rw prod_extend_right_apply_ne _ ha' }, end section congr variables [decidable_eq β] [fintype β] @[simp] lemma sign_prod_extend_right (a : α) (σ : perm β) : (prod_extend_right a σ).sign = σ.sign := sign_bij (λ (ab : α × β) _, ab.snd) (λ ⟨a', b⟩ hab hab', by simp [eq_of_prod_extend_right_ne hab]) (λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ hab₁ hab₂ h, by simpa [eq_of_prod_extend_right_ne hab₁, eq_of_prod_extend_right_ne hab₂] using h) (λ y hy, ⟨(a, y), by simpa, by simp⟩) lemma sign_prod_congr_right (σ : α → perm β) : sign (prod_congr_right σ) = ∏ k, (σ k).sign := begin obtain ⟨l, hl, mem_l⟩ := fintype.exists_univ_list α, have l_to_finset : l.to_finset = finset.univ, { apply eq_top_iff.mpr, intros b _, exact list.mem_to_finset.mpr (mem_l b) }, rw [← prod_prod_extend_right σ hl mem_l, sign.map_list_prod, list.map_map, ← l_to_finset, list.prod_to_finset _ hl], simp_rw ← λ a, sign_prod_extend_right a (σ a) end lemma sign_prod_congr_left (σ : α → perm β) : sign (prod_congr_left σ) = ∏ k, (σ k).sign := begin refine (sign_eq_sign_of_equiv _ _ (prod_comm β α) _).trans (sign_prod_congr_right σ), rintro ⟨b, α⟩, refl end @[simp] lemma sign_perm_congr (e : α ≃ β) (p : perm α) : (e.perm_congr p).sign = p.sign := sign_eq_sign_of_equiv _ _ e.symm (by simp) @[simp] lemma sign_sum_congr (σa : perm α) (σb : perm β) : (sum_congr σa σb).sign = σa.sign * σb.sign := begin suffices : (sum_congr σa (1 : perm β)).sign = σa.sign ∧ (sum_congr (1 : perm α) σb).sign = σb.sign, { rw [←this.1, ←this.2, ←sign_mul, sum_congr_mul, one_mul, mul_one], }, split, { apply σa.swap_induction_on _ (λ σa' a₁ a₂ ha ih, _), { simp }, { rw [←one_mul (1 : perm β), ←sum_congr_mul, sign_mul, sign_mul, ih, sum_congr_swap_one, sign_swap ha, sign_swap (sum.inl_injective.ne_iff.mpr ha)], }, }, { apply σb.swap_induction_on _ (λ σb' b₁ b₂ hb ih, _), { simp }, { rw [←one_mul (1 : perm α), ←sum_congr_mul, sign_mul, sign_mul, ih, sum_congr_one_swap, sign_swap hb, sign_swap (sum.inr_injective.ne_iff.mpr hb)], }, } end @[simp] lemma sign_subtype_congr {p : α → Prop} [decidable_pred p] (ep : perm {a // p a}) (en : perm {a // ¬ p a}) : (ep.subtype_congr en).sign = ep.sign * en.sign := by simp [subtype_congr] @[simp] lemma sign_extend_domain (e : perm α) {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) : equiv.perm.sign (e.extend_domain f) = equiv.perm.sign e := by simp [equiv.perm.extend_domain] end congr end sign end equiv.perm
cea8ef4bd80783cbf7c97c2a8f725790be1a1f10
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/list/as_type.lean
9fc80f3b1bd9192d715578ed6f686cfdf8f9df5b
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
454
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.list.basic namespace list structure as_type {A : Type} (l : list A) : Type := (value : A) (is_member : value ∈ l) namespace as_type notation `⟪`:max l `⟫`:0 := as_type l definition lval {A : Type} (a : A) {l : list A} (m : a ∈ l) : ⟪l⟫ := mk a m end as_type end list
8a586c850d5ef6dbda3ca184b572f05e285227f5
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/field_power.lean
3ccad7f3cbef4ce45f4365e0103648fa8cd82cc7
[ "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
5,206
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Integer power operation on fields. -/ import algebra.group_power algebra.ordered_field algebra.group_with_zero_power import tactic.wlog tactic.linarith universe u @[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) (a : K) : ∀ (n : ℤ), f (a ^ n) = f a ^ n | (n : ℕ) := f.map_pow a n | -[1+n] := by simp only [fpow_neg_succ_of_nat, f.map_pow, f.map_inv, f.map_one] namespace is_ring_hom lemma map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K → L) [is_ring_hom f] (a : K) : ∀ (n : ℤ), f (a ^ n) = f a ^ n := (ring_hom.of f).map_fpow a end is_ring_hom section ordered_field_power open int variables {K : Type u} [discrete_linear_ordered_field K] lemma fpow_nonneg_of_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (of_nat n) := pow_nonneg ha _ | -[1+n] := inv_nonneg.2 $ pow_nonneg ha _ lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (of_nat n) := pow_pos ha _ | -[1+n] := inv_pos.2 $ pow_pos ha _ lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [fpow_of_nat, of_nat_eq_coe], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [fpow_neg_succ_of_nat, one_div_eq_inv], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [fpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply fpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp end ordered_field_power lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n | 1 h := by simp; assumption | (k+2) h := begin rw ←one_mul (1 : K), apply mul_lt_mul, { assumption }, { apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)}, { apply zero_lt_one }, { apply le_of_lt (lt_trans zero_lt_one hp) } end lemma one_lt_fpow {K} [discrete_linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (int.of_nat n) h := one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h)) section ordered variables {K : Type*} [discrete_linear_ordered_field K] lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply fpow_pos_of_pos, exact_mod_cast h } lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.fpow_pos_of_pos h n) lemma fpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := by linarith, have h₀ : x ≠ 0 := by linarith, have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have hxm₀ : x^m ≠ 0 := ne_of_gt hxm, suffices : 1 < x^(n-m), { replace := mul_lt_mul_of_pos_right this hxm, simp [sub_eq_add_neg] at this, simpa [*, fpow_add, mul_assoc, fpow_neg, inv_mul_cancel], }, apply one_lt_fpow hx, linarith, end @[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (fpow_strict_mono hx).lt_iff_lt @[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (fpow_strict_mono hx).le_iff_le lemma injective_fpow {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases lt_trichotomy x 1 with H|rfl|H, { apply (fpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← fpow_inv, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], }, { contradiction }, { exact (fpow_strict_mono H).injective h, }, end @[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (injective_fpow h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, move_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_fpow q n end
be0129ba6cb2bcaca252b6709def671c794df174
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/mvar_backtrack.lean
1aff48110eca987540c18fedd6a5b49b5d956666
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
366
lean
namespace foo open nat class lt (n : inout ℕ) (m : ℕ) instance succ_lt_succ_of_lt (n m) [lt n m] : lt (succ n) (succ m) := by constructor instance zero_lt_succ (m) : lt 0 (succ m) := by constructor class foo (n : inout ℕ) (m : ℕ) instance (n m) [lt n 10] [lt m n] : foo n m := by constructor def bar {n} (m) [foo n m] := n #eval bar 0 #eval bar 1 end foo
bed060add2f38ec665e5dbe7f6cdd302371d7a85
618003631150032a5676f229d13a079ac875ff77
/src/data/semiquot.lean
0b0ee53950914dd6a8b48dfcc00827aef3bd3302
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
7,658
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro A data type for semiquotients, which are classically equivalent to nonempty sets, but are useful for programming; the idea is that a semiquotient set `S` represents some (particular but unknown) element of `S`. This can be used to model nondeterministic functions, which return something in a range of values (represented by the predicate `S`) but are not completely determined. -/ import data.set.lattice /-- A member of `semiquot α` is classically a nonempty `set α`, and in the VM is represented by an element of `α`; the relation between these is that the VM element is required to be a member of the set `s`. The specific element of `s` that the VM computes is hidden by a quotient construction, allowing for the representation of nondeterministic functions. -/ structure {u} semiquot (α : Type*) := mk' :: (s : set α) (val : trunc ↥s) namespace semiquot variables {α : Type*} {β : Type*} instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩ /-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/ def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α := ⟨s, trunc.mk ⟨a, h⟩⟩ theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := ⟨congr_arg _, λ h, by cases q₁; cases q₂; congr; exact h⟩ theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ := ext_s.trans set.ext_iff theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q := let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩ theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h := ext_s.2 rfl theorem nonempty (q : semiquot α) : q.s.nonempty := q.exists_mem /-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/ protected def pure (a : α) : semiquot α := mk (set.mem_singleton a) @[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b := set.mem_singleton_iff /-- Replace `s` in a `semiquot` with a superset. -/ def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α := ⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩) (λ _ _, trunc.eq _ _) q.2⟩ /-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/ def blur (s : set α) (q : semiquot α) : semiquot α := blur' q (set.subset_union_right s q.s) theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) : blur s q = blur' q h := by unfold blur; congr; exact set.union_eq_self_of_subset_right h @[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl /-- Convert a `trunc α` to a `semiquot α`. -/ def of_trunc (q : trunc α) : semiquot α := ⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩ /-- Convert a `semiquot α` to a `trunc α`. -/ def to_trunc (q : semiquot α) : trunc α := q.2.map subtype.val /-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f` at any point of `q`. -/ def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β := trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2) theorem lift_on_of_mem (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : lift_on q f h = f a := by revert h; rw eq_mk_of_mem aq; intro; refl def map (f : α → β) (q : semiquot α) : semiquot β := ⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩ @[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _ def bind (q : semiquot α) (f : α → semiquot β) : semiquot β := ⟨⋃ a ∈ q.1, (f a).1, q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩ @[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) : b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_bUnion_iff instance : monad semiquot := { pure := @semiquot.pure, map := @semiquot.map, bind := @semiquot.bind } @[simp] lemma map_def {β} : ((<$>) : (α → β) → semiquot α → semiquot β) = map := rfl @[simp] lemma bind_def {β} : ((>>=) : semiquot α → (α → semiquot β) → semiquot β) = bind := rfl @[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b := set.mem_singleton_iff theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) := set.mem_singleton a @[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b := ext_s.trans set.singleton_eq_singleton_iff instance : is_lawful_monad semiquot := { pure_bind := λ α β x f, ext.2 $ by simp, bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩, λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩, id_map := λ α q, ext.2 $ by simp, bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] } instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩ instance : partial_order (semiquot α) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, le_refl := λ s, set.subset.refl _, le_trans := λ s t u, set.subset.trans, le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) } instance : semilattice_sup (semiquot α) := { sup := λ s, blur s.s, le_sup_left := λ s t, set.subset_union_left _ _, le_sup_right := λ s t, set.subset_union_right _ _, sup_le := λ s t u, set.union_subset, ..semiquot.partial_order } @[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s := set.singleton_subset_iff def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h theorem get_mem {q : semiquot α} (p) : get q p ∈ q := let ⟨a, h⟩ := exists_mem q in by unfold get; rw lift_on_of_mem q _ _ a h; exact h theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) := ext.2 $ λ a, by simp; exact ⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩ @[simp] theorem pure_is_pure (a : α) : is_pure (pure a) | b c ab ac := by { simp at ab ac, cc } theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a := ⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩ theorem is_pure.mono {s t : semiquot α} (st : s ≤ t) (h : is_pure t) : is_pure s | a b as bs := h _ _ (st as) (st bs) theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t := ⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp; exact h _ _ (get_mem _) (st $ get_mem _), le_of_eq⟩ theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q | a b aq bq := subsingleton.elim _ _ /-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/ def univ [inhabited α] : semiquot α := mk $ set.mem_univ (default _) instance [inhabited α] : inhabited (semiquot α) := ⟨univ⟩ @[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ := @set.mem_univ α @[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J := ext.2 $ by simp @[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α := ⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩ instance [inhabited α] : order_top (semiquot α) := { top := univ, le_top := λ s, set.subset_univ _, ..semiquot.partial_order } instance [inhabited α] : semilattice_sup_top (semiquot α) := { ..semiquot.order_top, ..semiquot.semilattice_sup } end semiquot
65358733e32c7e39095cdd5946c4beafebf7b9dd
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/parent_struct_inst.lean
94e9e4b080ea2663bcbe56b4d1986a2b0632d2be
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
165
lean
open nat class A := (n : ℕ) definition f [A] := A.n structure B extends A := (Hf : f = 0) example : B := ⟨⟨0⟩, rfl⟩ example : B := (| (| 0 |), rfl |)
19bd6a9687dc653d3fb9d774d7462f8c6a813233
4d3f29a7b2eff44af8fd0d3176232e039acb9ee3
/Mathlib/Mathlib.lean
ef742a4545ea1cebe3dda08ca3f89ddddb237b3d
[]
no_license
marijnheule/lamr
5fc5d69d326ff92e321242cfd7f72e78d7f99d7e
28cc4114c7361059bb54f407fa312bf38b48728b
refs/heads/main
1,689,338,013,620
1,630,359,632,000
1,630,359,632,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,239
lean
import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Defs import Mathlib.Algebra.GroupWithZero.Defs import Mathlib.Algebra.Ring.Basic import Mathlib.Data.Array.Basic import Mathlib.Data.ByteArray import Mathlib.Data.Char import Mathlib.Data.Equiv.Basic import Mathlib.Data.Equiv.Functor import Mathlib.Data.Int.Basic import Mathlib.Data.List.Basic import Mathlib.Data.List.Card import Mathlib.Data.Nat.Basic import Mathlib.Data.Nat.Gcd import Mathlib.Data.Prod import Mathlib.Data.Subtype import Mathlib.Data.UInt import Mathlib.Dvd import Mathlib.Function import Mathlib.Init.Algebra.Functions import Mathlib.Init.Algebra.Order import Mathlib.Init.Logic import Mathlib.Logic.Basic import Mathlib.Logic.Function.Basic import Mathlib.Set import Mathlib.SetNotation import Mathlib.Tactic.Basic import Mathlib.Tactic.Block import Mathlib.Tactic.Coe import Mathlib.Tactic.Core import Mathlib.Tactic.NoMatch import Mathlib.Tactic.NormNum import Mathlib.Tactic.OpenPrivate import Mathlib.Tactic.PrintPrefix import Mathlib.Tactic.Ring import Mathlib.Tactic.RunTac import Mathlib.Tactic.Split import Mathlib.Tactic.Spread import Mathlib.Tactic.SudoSetOption import Mathlib.Test.Split import Mathlib.Util.Export import Mathlib.Util.Time
b23183d632e67ab7a14a145d04e7e0303090c2e6
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/connected.lean
ef642ef23ac0bdf4c3549c14f2faeccf25d24dda
[ "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
63,172
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import data.int.succ_pred import data.nat.succ_pred import order.partial_sups import order.succ_pred.relation import topology.subset_properties /-! # Connected subsets of topological spaces In this file we define connected subsets of a topological spaces and various other properties and classes related to connectivity. ## Main definitions We define the following properties for sets in a topological space: * `is_connected`: a nonempty set that has no non-trivial open partition. See also the section below in the module doc. * `connected_component` is the connected component of an element in the space. * `is_totally_disconnected`: all of its connected components are singletons. * `is_totally_separated`: any two points can be separated by two disjoint opens that cover the set. For each of these definitions, we also have a class stating that the whole space satisfies that property: `connected_space`, `totally_disconnected_space`, `totally_separated_space`. ## On the definition of connected sets/spaces In informal mathematics, connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preconnected`. In other words, the only difference is whether the empty space counts as connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set function topological_space relation open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} {ι : Type*} {π : ι → Type*} [topological_space α] {s t u v : set α} section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected theorem is_preconnected_singleton {x} : is_preconnected ({x} : set α) := is_connected_singleton.is_preconnected theorem set.subsingleton.is_preconnected {s : set α} (hs : s.subsingleton) : is_preconnected s := hs.induction_on is_preconnected_empty (λ x, is_preconnected_singleton) /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩), exacts [is_preconnected_empty, is_preconnected_of_forall x $ λ y, H x hx y], end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected_Union {ι : Sort*} {s : ι → set α} (h₁ : (⋂ i, s i).nonempty) (h₂ : ∀ i, is_preconnected (s i)) : is_preconnected (⋃ i, s i) := exists.elim h₁ $ λ f hf, is_preconnected_sUnion f _ hf (forall_range_iff.2 h₂) theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_preconnected.union' {s t : set α} (H : (s ∩ t).nonempty) (hs : is_preconnected s) (ht : is_preconnected t) : is_preconnected (s ∪ t) := by { rcases H with ⟨x, hxs, hxt⟩, exact hs.union x hxs hxt ht } theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end /-- The directed sUnion of a set S of preconnected subsets is preconnected. -/ theorem is_preconnected.sUnion_directed {S : set (set α)} (K : directed_on (⊆) S) (H : ∀ s ∈ S, is_preconnected s) : is_preconnected (⋃₀ S) := begin rintros u v hu hv Huv ⟨a, ⟨s, hsS, has⟩, hau⟩ ⟨b, ⟨t, htS, hbt⟩, hbv⟩, obtain ⟨r, hrS, hsr, htr⟩ : ∃ r ∈ S, s ⊆ r ∧ t ⊆ r := K s hsS t htS, have Hnuv : (r ∩ (u ∩ v)).nonempty, from H _ hrS u v hu hv ((subset_sUnion_of_mem hrS).trans Huv) ⟨a, hsr has, hau⟩ ⟨b, htr hbt, hbv⟩, have Kruv : r ∩ (u ∩ v) ⊆ ⋃₀ S ∩ (u ∩ v), from inter_subset_inter_left _ (subset_sUnion_of_mem hrS), exact Hnuv.mono Kruv end /-- The bUnion of a family of preconnected sets is preconnected if the graph determined by whether two sets intersect is preconnected. -/ theorem is_preconnected.bUnion_of_refl_trans_gen {ι : Type*} {t : set ι} {s : ι → set α} (H : ∀ i ∈ t, is_preconnected (s i)) (K : ∀ i j ∈ t, refl_trans_gen (λ i j : ι, (s i ∩ s j).nonempty ∧ i ∈ t) i j) : is_preconnected (⋃ n ∈ t, s n) := begin let R := λ i j : ι, (s i ∩ s j).nonempty ∧ i ∈ t, have P : ∀ (i j ∈ t), refl_trans_gen R i j → ∃ (p ⊆ t), i ∈ p ∧ j ∈ p ∧ is_preconnected (⋃ j ∈ p, s j), { intros i hi j hj h, induction h, case refl { refine ⟨{i}, singleton_subset_iff.mpr hi, mem_singleton i, mem_singleton i, _⟩, rw [bUnion_singleton], exact H i hi }, case tail : j k hij hjk ih { obtain ⟨p, hpt, hip, hjp, hp⟩ := ih hjk.2, refine ⟨insert k p, insert_subset.mpr ⟨hj, hpt⟩, mem_insert_of_mem k hip, mem_insert k p, _⟩, rw [bUnion_insert], refine (H k hj).union' _ hp, refine hjk.1.mono _, rw [inter_comm], refine inter_subset_inter subset.rfl (subset_bUnion_of_mem hjp) } }, refine is_preconnected_of_forall_pair _, intros x hx y hy, obtain ⟨i: ι, hi : i ∈ t, hxi : x ∈ s i⟩ := mem_Union₂.1 hx, obtain ⟨j: ι, hj : j ∈ t, hyj : y ∈ s j⟩ := mem_Union₂.1 hy, obtain ⟨p, hpt, hip, hjp, hp⟩ := P i hi j hj (K i hi j hj), exact ⟨⋃ j ∈ p, s j, bUnion_subset_bUnion_left hpt, mem_bUnion hip hxi, mem_bUnion hjp hyj, hp⟩ end /-- The bUnion of a family of preconnected sets is preconnected if the graph determined by whether two sets intersect is preconnected. -/ theorem is_connected.bUnion_of_refl_trans_gen {ι : Type*} {t : set ι} {s : ι → set α} (ht : t.nonempty) (H : ∀ i ∈ t, is_connected (s i)) (K : ∀ i j ∈ t, refl_trans_gen (λ i j : ι, (s i ∩ s j).nonempty ∧ i ∈ t) i j) : is_connected (⋃ n ∈ t, s n) := ⟨nonempty_bUnion.2 $ ⟨ht.some, ht.some_mem, (H _ ht.some_mem).nonempty⟩, is_preconnected.bUnion_of_refl_trans_gen (λ i hi, (H i hi).is_preconnected) K⟩ /-- Preconnectedness of the Union of a family of preconnected sets indexed by the vertices of a preconnected graph, where two vertices are joined when the corresponding sets intersect. -/ theorem is_preconnected.Union_of_refl_trans_gen {ι : Type*} {s : ι → set α} (H : ∀ i, is_preconnected (s i)) (K : ∀ i j, refl_trans_gen (λ i j : ι, (s i ∩ s j).nonempty) i j) : is_preconnected (⋃ n, s n) := by { rw [← bUnion_univ], exact is_preconnected.bUnion_of_refl_trans_gen (λ i _, H i) (λ i _ j _, by simpa [mem_univ] using K i j) } theorem is_connected.Union_of_refl_trans_gen {ι : Type*} [nonempty ι] {s : ι → set α} (H : ∀ i, is_connected (s i)) (K : ∀ i j, refl_trans_gen (λ i j : ι, (s i ∩ s j).nonempty) i j) : is_connected (⋃ n, s n) := ⟨nonempty_Union.2 $ nonempty.elim ‹_› $ λ i : ι, ⟨i, (H _).nonempty⟩, is_preconnected.Union_of_refl_trans_gen (λ i, (H i).is_preconnected) K⟩ section succ_order open order variables [linear_order β] [succ_order β] [is_succ_archimedean β] /-- The Union of connected sets indexed by a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is preconnected. -/ theorem is_preconnected.Union_of_chain {s : β → set α} (H : ∀ n, is_preconnected (s n)) (K : ∀ n, (s n ∩ s (succ n)).nonempty) : is_preconnected (⋃ n, s n) := is_preconnected.Union_of_refl_trans_gen H $ λ i j, refl_trans_gen_of_succ _ (λ i _, K i) $ λ i _, by { rw inter_comm, exact K i } /-- The Union of connected sets indexed by a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is connected. -/ theorem is_connected.Union_of_chain [nonempty β] {s : β → set α} (H : ∀ n, is_connected (s n)) (K : ∀ n, (s n ∩ s (succ n)).nonempty) : is_connected (⋃ n, s n) := is_connected.Union_of_refl_trans_gen H $ λ i j, refl_trans_gen_of_succ _ (λ i _, K i) $ λ i _, by { rw inter_comm, exact K i } /-- The Union of preconnected sets indexed by a subset of a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is preconnected. -/ theorem is_preconnected.bUnion_of_chain {s : β → set α} {t : set β} (ht : ord_connected t) (H : ∀ n ∈ t, is_preconnected (s n)) (K : ∀ n : β, n ∈ t → succ n ∈ t → (s n ∩ s (succ n)).nonempty) : is_preconnected (⋃ n ∈ t, s n) := begin have h1 : ∀ {i j k : β}, i ∈ t → j ∈ t → k ∈ Ico i j → k ∈ t := λ i j k hi hj hk, ht.out hi hj (Ico_subset_Icc_self hk), have h2 : ∀ {i j k : β}, i ∈ t → j ∈ t → k ∈ Ico i j → succ k ∈ t := λ i j k hi hj hk, ht.out hi hj ⟨hk.1.trans $ le_succ k, succ_le_of_lt hk.2⟩, have h3 : ∀ {i j k : β}, i ∈ t → j ∈ t → k ∈ Ico i j → (s k ∩ s (succ k)).nonempty := λ i j k hi hj hk, K _ (h1 hi hj hk) (h2 hi hj hk), refine is_preconnected.bUnion_of_refl_trans_gen H (λ i hi j hj, _), exact refl_trans_gen_of_succ _ (λ k hk, ⟨h3 hi hj hk, h1 hi hj hk⟩) (λ k hk, ⟨by { rw [inter_comm], exact h3 hj hi hk }, h2 hj hi hk⟩), end /-- The Union of connected sets indexed by a subset of a type with an archimedean successor (like `ℕ` or `ℤ`) such that any two neighboring sets meet is preconnected. -/ theorem is_connected.bUnion_of_chain {s : β → set α} {t : set β} (hnt : t.nonempty) (ht : ord_connected t) (H : ∀ n ∈ t, is_connected (s n)) (K : ∀ n : β, n ∈ t → succ n ∈ t → (s n ∩ s (succ n)).nonempty) : is_connected (⋃ n ∈ t, s n) := ⟨nonempty_bUnion.2 $ ⟨hnt.some, hnt.some_mem, (H _ hnt.some_mem).nonempty⟩, is_preconnected.bUnion_of_chain ht (λ i hi, (H i hi).is_preconnected) K⟩ end succ_order /-- Theorem of bark and tree : if a set is within a (pre)connected set and its closure, then it is (pre)connected as well. -/ theorem is_preconnected.subset_closure {s : set α} {t : set α} (H : is_preconnected s) (Kst : s ⊆ t) (Ktcs : t ⊆ closure s) : is_preconnected t := λ u v hu hv htuv ⟨y, hyt, hyu⟩ ⟨z, hzt, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 (Ktcs hyt) u hu hyu, ⟨q, hqv, hqs⟩ := mem_closure_iff.1 (Ktcs hzt) v hv hzv, ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans Kst htuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, Kst hrs, hruv⟩ theorem is_connected.subset_closure {s : set α} {t : set α} (H : is_connected s) (Kst : s ⊆ t) (Ktcs : t ⊆ closure s): is_connected t := let hsne := H.left, ht := Kst, htne := nonempty.mono ht hsne in ⟨nonempty.mono Kst H.left, is_preconnected.subset_closure H.right Kst Ktcs ⟩ /-- The closure of a (pre)connected set is (pre)connected as well. -/ theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := is_preconnected.subset_closure H subset_closure $ subset.refl $ closure s theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := is_connected.subset_closure H subset_closure $ subset.refl $ closure s /-- The image of a (pre)connected set is (pre)connected as well. -/ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ lemma inducing.is_preconnected_image [topological_space β] {s : set α} {f : α → β} (hf : inducing f) : is_preconnected (f '' s) ↔ is_preconnected s := begin refine ⟨λ h, _, λ h, h.image _ hf.continuous.continuous_on⟩, rintro u v hu' hv' huv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩, rcases hf.is_open_iff.1 hu' with ⟨u, hu, rfl⟩, rcases hf.is_open_iff.1 hv' with ⟨v, hv, rfl⟩, replace huv : f '' s ⊆ u ∪ v, by rwa image_subset_iff, rcases h u v hu hv huv ⟨f x, mem_image_of_mem _ hxs, hxu⟩ ⟨f y, mem_image_of_mem _ hys, hyv⟩ with ⟨_, ⟨z, hzs, rfl⟩, hzuv⟩, exact ⟨z, hzs, hzuv⟩ end /- TODO: The following lemmas about connection of preimages hold more generally for strict maps (the quotient and subspace topologies of the image agree) whose fibers are preconnected. -/ lemma is_preconnected.preimage_of_open_map [topological_space β] {s : set β} (hs : is_preconnected s) {f : α → β} (hinj : function.injective f) (hf : is_open_map f) (hsf : s ⊆ range f) : is_preconnected (f ⁻¹' s) := λ u v hu hv hsuv hsu hsv, begin obtain ⟨b, hbs, hbu, hbv⟩ := hs (f '' u) (f '' v) (hf u hu) (hf v hv) _ _ _, obtain ⟨a, rfl⟩ := hsf hbs, rw hinj.mem_set_image at hbu hbv, exact ⟨a, hbs, hbu, hbv⟩, { have := image_subset f hsuv, rwa [set.image_preimage_eq_of_subset hsf, image_union] at this }, { obtain ⟨x, hx1, hx2⟩ := hsu, exact ⟨f x, hx1, x, hx2, rfl⟩ }, { obtain ⟨y, hy1, hy2⟩ := hsv, exact ⟨f y, hy1, y, hy2, rfl⟩ } end lemma is_preconnected.preimage_of_closed_map [topological_space β] {s : set β} (hs : is_preconnected s) {f : α → β} (hinj : function.injective f) (hf : is_closed_map f) (hsf : s ⊆ range f) : is_preconnected (f ⁻¹' s) := is_preconnected_closed_iff.2 $ λ u v hu hv hsuv hsu hsv, begin obtain ⟨b, hbs, hbu, hbv⟩ := is_preconnected_closed_iff.1 hs (f '' u) (f '' v) (hf u hu) (hf v hv) _ _ _, obtain ⟨a, rfl⟩ := hsf hbs, rw hinj.mem_set_image at hbu hbv, exact ⟨a, hbs, hbu, hbv⟩, { have := image_subset f hsuv, rwa [set.image_preimage_eq_of_subset hsf, image_union] at this }, { obtain ⟨x, hx1, hx2⟩ := hsu, exact ⟨f x, hx1, x, hx2, rfl⟩ }, { obtain ⟨y, hy1, hy2⟩ := hsv, exact ⟨f y, hy1, y, hy2, rfl⟩ } end lemma is_connected.preimage_of_open_map [topological_space β] {s : set β} (hs : is_connected s) {f : α → β} (hinj : function.injective f) (hf : is_open_map f) (hsf : s ⊆ range f) : is_connected (f ⁻¹' s) := ⟨hs.nonempty.preimage' hsf, hs.is_preconnected.preimage_of_open_map hinj hf hsf⟩ lemma is_connected.preimage_of_closed_map [topological_space β] {s : set β} (hs : is_connected s) {f : α → β} (hinj : function.injective f) (hf : is_closed_map f) (hsf : s ⊆ range f) : is_connected (f ⁻¹' s) := ⟨hs.nonempty.preimage' hsf, hs.is_preconnected.preimage_of_closed_map hinj hf hsf⟩ lemma is_preconnected.subset_or_subset (hu : is_open u) (hv : is_open v) (huv : disjoint u v) (hsuv : s ⊆ u ∪ v) (hs : is_preconnected s) : s ⊆ u ∨ s ⊆ v := begin specialize hs u v hu hv hsuv, obtain hsu | hsu := (s ∩ u).eq_empty_or_nonempty, { exact or.inr ((set.disjoint_iff_inter_eq_empty.2 hsu).subset_right_of_subset_union hsuv) }, { replace hs := mt (hs hsu), simp_rw [set.not_nonempty_iff_eq_empty, ←set.disjoint_iff_inter_eq_empty, disjoint_iff_inter_eq_empty.1 huv] at hs, exact or.inl ((hs s.disjoint_empty).subset_left_of_subset_union hsuv) } end lemma is_preconnected.subset_left_of_subset_union (hu : is_open u) (hv : is_open v) (huv : disjoint u v) (hsuv : s ⊆ u ∪ v) (hsu : (s ∩ u).nonempty) (hs : is_preconnected s) : s ⊆ u := disjoint.subset_left_of_subset_union hsuv begin by_contra hsv, rw not_disjoint_iff_nonempty_inter at hsv, obtain ⟨x, _, hx⟩ := hs u v hu hv hsuv hsu hsv, exact set.disjoint_iff.1 huv hx, end lemma is_preconnected.subset_right_of_subset_union (hu : is_open u) (hv : is_open v) (huv : disjoint u v) (hsuv : s ⊆ u ∪ v) (hsv : (s ∩ v).nonempty) (hs : is_preconnected s) : s ⊆ v := hs.subset_left_of_subset_union hv hu huv.symm (union_comm u v ▸ hsuv) hsv theorem is_preconnected.prod [topological_space β] {s : set α} {t : set β} (hs : is_preconnected s) (ht : is_preconnected t) : is_preconnected (s ×ˢ t) := begin apply is_preconnected_of_forall_pair, rintro ⟨a₁, b₁⟩ ⟨ha₁, hb₁⟩ ⟨a₂, b₂⟩ ⟨ha₂, hb₂⟩, refine ⟨prod.mk a₁ '' t ∪ flip prod.mk b₂ '' s, _, or.inl ⟨b₁, hb₁, rfl⟩, or.inr ⟨a₂, ha₂, rfl⟩, _⟩, { rintro _ (⟨y, hy, rfl⟩|⟨x, hx, rfl⟩), exacts [⟨ha₁, hy⟩, ⟨hx, hb₂⟩] }, { exact (ht.image _ (continuous.prod.mk _).continuous_on).union (a₁, b₂) ⟨b₂, hb₂, rfl⟩ ⟨a₁, ha₁, rfl⟩ (hs.image _ (continuous_id.prod_mk continuous_const).continuous_on) } end theorem is_connected.prod [topological_space β] {s : set α} {t : set β} (hs : is_connected s) (ht : is_connected t) : is_connected (s ×ˢ t) := ⟨hs.1.prod ht.1, hs.2.prod ht.2⟩ theorem is_preconnected_univ_pi [Π i, topological_space (π i)] {s : Π i, set (π i)} (hs : ∀ i, is_preconnected (s i)) : is_preconnected (pi univ s) := begin rintros u v uo vo hsuv ⟨f, hfs, hfu⟩ ⟨g, hgs, hgv⟩, rcases exists_finset_piecewise_mem_of_mem_nhds (uo.mem_nhds hfu) g with ⟨I, hI⟩, induction I using finset.induction_on with i I hi ihI, { refine ⟨g, hgs, ⟨_, hgv⟩⟩, simpa using hI }, { rw [finset.piecewise_insert] at hI, have := I.piecewise_mem_set_pi hfs hgs, refine (hsuv this).elim ihI (λ h, _), set S := update (I.piecewise f g) i '' (s i), have hsub : S ⊆ pi univ s, { refine image_subset_iff.2 (λ z hz, _), rwa update_preimage_univ_pi, exact λ j hj, this j trivial }, have hconn : is_preconnected S, from (hs i).image _ (continuous_const.update i continuous_id).continuous_on, have hSu : (S ∩ u).nonempty, from ⟨_, mem_image_of_mem _ (hfs _ trivial), hI⟩, have hSv : (S ∩ v).nonempty, from ⟨_, ⟨_, this _ trivial, update_eq_self _ _⟩, h⟩, refine (hconn u v uo vo (hsub.trans hsuv) hSu hSv).mono _, exact inter_subset_inter_left _ hsub } end @[simp] theorem is_connected_univ_pi [Π i, topological_space (π i)] {s : Π i, set (π i)} : is_connected (pi univ s) ↔ ∀ i, is_connected (s i) := begin simp only [is_connected, ← univ_pi_nonempty_iff, forall_and_distrib, and.congr_right_iff], refine λ hne, ⟨λ hc i, _, is_preconnected_univ_pi⟩, rw [← eval_image_univ_pi hne], exact hc.image _ (continuous_apply _).continuous_on end lemma sigma.is_connected_iff [Π i, topological_space (π i)] {s : set (Σ i, π i)} : is_connected s ↔ ∃ i t, is_connected t ∧ s = sigma.mk i '' t := begin refine ⟨λ hs, _, _⟩, { obtain ⟨⟨i, x⟩, hx⟩ := hs.nonempty, have : s ⊆ range (sigma.mk i), { have h : range (sigma.mk i) = sigma.fst ⁻¹' {i}, by { ext, simp }, rw h, exact is_preconnected.subset_left_of_subset_union (is_open_sigma_fst_preimage _) (is_open_sigma_fst_preimage {x | x ≠ i}) (set.disjoint_iff.2 $ λ x hx, hx.2 hx.1) (λ y hy, by simp [classical.em]) ⟨⟨i, x⟩, hx, rfl⟩ hs.2 }, exact ⟨i, sigma.mk i ⁻¹' s, hs.preimage_of_open_map sigma_mk_injective is_open_map_sigma_mk this, (set.image_preimage_eq_of_subset this).symm⟩ }, { rintro ⟨i, t, ht, rfl⟩, exact ht.image _ continuous_sigma_mk.continuous_on } end lemma sigma.is_preconnected_iff [hι : nonempty ι] [Π i, topological_space (π i)] {s : set (Σ i, π i)} : is_preconnected s ↔ ∃ i t, is_preconnected t ∧ s = sigma.mk i '' t := begin refine ⟨λ hs, _, _⟩, { obtain rfl | h := s.eq_empty_or_nonempty, { exact ⟨classical.choice hι, ∅, is_preconnected_empty, (set.image_empty _).symm⟩ }, { obtain ⟨a, t, ht, rfl⟩ := sigma.is_connected_iff.1 ⟨h, hs⟩, refine ⟨a, t, ht.is_preconnected, rfl⟩ } }, { rintro ⟨a, t, ht, rfl⟩, exact ht.image _ continuous_sigma_mk.continuous_on } end lemma sum.is_connected_iff [topological_space β] {s : set (α ⊕ β)} : is_connected s ↔ (∃ t, is_connected t ∧ s = sum.inl '' t) ∨ ∃ t, is_connected t ∧ s = sum.inr '' t := begin refine ⟨λ hs, _, _⟩, { let u : set (α ⊕ β):= range sum.inl, let v : set (α ⊕ β) := range sum.inr, have hu : is_open u, exact is_open_range_inl, obtain ⟨x | x, hx⟩ := hs.nonempty, { have h := is_preconnected.subset_left_of_subset_union is_open_range_inl is_open_range_inr is_compl_range_inl_range_inr.disjoint (show s ⊆ range sum.inl ∪ range sum.inr, by simp) ⟨sum.inl x, hx, x, rfl⟩ hs.2, refine or.inl ⟨sum.inl ⁻¹' s, _, _⟩, { exact hs.preimage_of_open_map sum.inl_injective open_embedding_inl.is_open_map h }, { exact (set.image_preimage_eq_of_subset h).symm } }, { have h := is_preconnected.subset_right_of_subset_union is_open_range_inl is_open_range_inr is_compl_range_inl_range_inr.disjoint (show s ⊆ range sum.inl ∪ range sum.inr, by simp) ⟨sum.inr x, hx, x, rfl⟩ hs.2, refine or.inr ⟨sum.inr ⁻¹' s, _, _⟩, { exact hs.preimage_of_open_map sum.inr_injective open_embedding_inr.is_open_map h }, { exact (set.image_preimage_eq_of_subset h).symm } } }, { rintro (⟨t, ht, rfl⟩ | ⟨t, ht, rfl⟩), { exact ht.image _ continuous_inl.continuous_on }, { exact ht.image _ continuous_inr.continuous_on } } end lemma sum.is_preconnected_iff [topological_space β] {s : set (α ⊕ β)} : is_preconnected s ↔ (∃ t, is_preconnected t ∧ s = sum.inl '' t) ∨ ∃ t, is_preconnected t ∧ s = sum.inr '' t := begin refine ⟨λ hs, _, _⟩, { obtain rfl | h := s.eq_empty_or_nonempty, { exact or.inl ⟨∅, is_preconnected_empty, (set.image_empty _).symm⟩ }, obtain ⟨t, ht, rfl⟩ | ⟨t, ht, rfl⟩ := sum.is_connected_iff.1 ⟨h, hs⟩, { exact or.inl ⟨t, ht.is_preconnected, rfl⟩ }, { exact or.inr ⟨t, ht.is_preconnected, rfl⟩ } }, { rintro (⟨t, ht, rfl⟩ | ⟨t, ht, rfl⟩), { exact ht.image _ continuous_inl.continuous_on }, { exact ht.image _ continuous_inr.continuous_on } } end /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } /-- The connected component of a point inside a set. -/ def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x) theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_preconnected_connected_component {x : α} : is_preconnected (connected_component x) := is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left) theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_connected_component⟩ theorem is_preconnected.subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_connected.subset_connected_component {x : α} {s : set α} (H1 : is_connected s) (H2 : x ∈ s) : s ⊆ connected_component x := H1.2.subset_connected_component H2 theorem connected_component_eq {x y : α} (h : y ∈ connected_component x) : connected_component x = connected_component y := eq_of_subset_of_subset (is_connected_connected_component.subset_connected_component h) (is_connected_connected_component.subset_connected_component (set.mem_of_mem_of_subset mem_connected_component (is_connected_connected_component.subset_connected_component h))) lemma connected_component_disjoint {x y : α} (h : connected_component x ≠ connected_component y) : disjoint (connected_component x) (connected_component y) := set.disjoint_left.2 (λ a h1 h2, h ((connected_component_eq h1).trans (connected_component_eq h2).symm)) theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (is_connected_connected_component.closure.subset_connected_component (subset_closure mem_connected_component)) subset_closure lemma continuous.image_connected_component_subset [topological_space β] {f : α → β} (h : continuous f) (a : α) : f '' connected_component a ⊆ connected_component (f a) := (is_connected_connected_component.image f h.continuous_on).subset_connected_component ((mem_image f (connected_component a) (f a)).2 ⟨a, mem_connected_component, rfl⟩) lemma continuous.maps_to_connected_component [topological_space β] {f : α → β} (h : continuous f) (a : α) : maps_to f (connected_component a) (connected_component (f a)) := maps_to'.2 $ h.image_connected_component_subset a theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := is_irreducible_irreducible_component.is_connected.subset_connected_component mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) export preconnected_space (is_preconnected_univ) /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] lemma is_connected_univ [connected_space α] : is_connected (univ : set α) := ⟨univ_nonempty, is_preconnected_univ⟩ lemma is_preconnected_range [topological_space β] [preconnected_space α] {f : α → β} (h : continuous f) : is_preconnected (range f) := @image_univ _ _ f ▸ is_preconnected_univ.image _ h.continuous_on lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) : is_connected (range f) := ⟨range_nonempty f, is_preconnected_range h⟩ lemma dense_range.preconnected_space [topological_space β] [preconnected_space α] {f : α → β} (hf : dense_range f) (hc : continuous f) : preconnected_space β := ⟨hf.closure_eq ▸ (is_preconnected_range hc).closure⟩ lemma connected_space_iff_connected_component : connected_space α ↔ ∃ x : α, connected_component x = univ := begin split, { rintros ⟨h, ⟨x⟩⟩, exactI ⟨x, eq_univ_of_univ_subset $ is_preconnected_univ.subset_connected_component (mem_univ x)⟩ }, { rintros ⟨x, h⟩, haveI : preconnected_space α := ⟨by { rw ← h, exact is_preconnected_connected_component }⟩, exact ⟨⟨x⟩⟩ } end lemma preconnected_space_iff_connected_component : preconnected_space α ↔ ∀ x : α, connected_component x = univ := begin split, { intros h x, exactI (eq_univ_of_univ_subset $ is_preconnected_univ.subset_connected_component (mem_univ x)) }, { intros h, casesI is_empty_or_nonempty α with hα hα, { exact ⟨by { rw (univ_eq_empty_iff.mpr hα), exact is_preconnected_empty }⟩ }, { exact ⟨by { rw ← h (classical.choice hα), exact is_preconnected_connected_component }⟩ } } end @[simp] lemma preconnected_space.connected_component_eq_univ {X : Type*} [topological_space X] [h : preconnected_space X] (x : X) : connected_component x = univ := preconnected_space_iff_connected_component.mp h x instance [topological_space β] [preconnected_space α] [preconnected_space β] : preconnected_space (α × β) := ⟨by { rw ← univ_prod_univ, exact is_preconnected_univ.prod is_preconnected_univ }⟩ instance [topological_space β] [connected_space α] [connected_space β] : connected_space (α × β) := ⟨prod.nonempty⟩ instance [Π i, topological_space (π i)] [∀ i, preconnected_space (π i)] : preconnected_space (Π i, π i) := ⟨by { rw ← pi_univ univ, exact is_preconnected_univ_pi (λ i, is_preconnected_univ) }⟩ instance [Π i, topological_space (π i)] [∀ i, connected_space (π i)] : connected_space (Π i, π i) := ⟨classical.nonempty_pi.2 $ λ i, by apply_instance⟩ @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2.is_open_compl (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α} (h : s.nonempty) (h' : is_clopen s) : s = univ := by { rw is_clopen_iff at h', exact h'.resolve_left h.ne_empty } lemma frontier_eq_empty_iff [preconnected_space α] {s : set α} : frontier s = ∅ ↔ s = ∅ ∨ s = univ := is_clopen_iff_frontier_eq_empty.symm.trans is_clopen_iff lemma nonempty_frontier_iff [preconnected_space α] {s : set α} : (frontier s).nonempty ↔ s.nonempty ∧ s ≠ univ := by simp only [← ne_empty_iff_nonempty, ne.def, frontier_eq_empty_iff, not_or_distrib] lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := by rwa [← embedding_subtype_coe.to_inducing.is_preconnected_image, image_univ, subtype.range_coe] } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { to_preconnected_space := subtype.preconnected_space h.is_preconnected, to_nonempty := h.nonempty.to_subtype } lemma is_preconnected_iff_preconnected_space {s : set α} : is_preconnected s ↔ preconnected_space s := ⟨subtype.preconnected_space, begin introI, simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on end⟩ lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s := ⟨subtype.connected_space, λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩ /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end /-- Preconnected sets are either contained in or disjoint to any given clopen set. -/ theorem is_preconnected.subset_clopen {s t : set α} (hs : is_preconnected s) (ht : is_clopen t) (hne : (s ∩ t).nonempty) : s ⊆ t := begin by_contra h, have : (s ∩ tᶜ).nonempty := inter_compl_nonempty_iff.2 h, obtain ⟨x, -, hx, hx'⟩ : (s ∩ (t ∩ tᶜ)).nonempty, from hs t tᶜ ht.is_open ht.compl.is_open (λ x hx, em _) hne this, exact hx' hx end /-- Preconnected sets are either contained in or disjoint to any given clopen set. -/ theorem disjoint_or_subset_of_clopen {s t : set α} (hs : is_preconnected s) (ht : is_clopen t) : disjoint s t ∨ s ⊆ t := (disjoint_or_nonempty_inter s t).imp_right $ hs.subset_clopen ht /-- A set `s` is preconnected if and only if for every cover by two closed sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_disjoint_closed : is_preconnected s ↔ ∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, rw is_preconnected_closed_iff at h, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { rw is_preconnected_closed_iff, intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A closed set `s` is preconnected if and only if for every cover by two closed sets that are disjoint, it is contained in one of the two covering sets. -/ theorem is_preconnected_iff_subset_of_fully_disjoint_closed {s : set α} (hs : is_closed s) : is_preconnected s ↔ ∀ (u v : set α) (hu : is_closed u) (hv : is_closed v) (hss : s ⊆ u ∪ v) (huv : u ∩ v = ∅), s ⊆ u ∨ s ⊆ v := begin split, { intros h u v hu hv hss huv, apply is_preconnected_iff_subset_of_disjoint_closed.1 h u v hu hv hss, rw huv, exact inter_empty s }, intro H, rw is_preconnected_iff_subset_of_disjoint_closed, intros u v hu hv hss huv, have H1 := H (u ∩ s) (v ∩ s), rw [subset_inter_iff, subset_inter_iff] at H1, simp only [subset.refl, and_true] at H1, apply H1 (is_closed.inter hu hs) (is_closed.inter hv hs), { rw ←inter_distrib_right, apply subset_inter_iff.2, exact ⟨hss, subset.refl s⟩ }, { rw [inter_comm v s, inter_assoc, ←inter_assoc s, inter_self s, inter_comm, inter_assoc, inter_comm v u, huv] } end lemma is_clopen.connected_component_subset {x} (hs : is_clopen s) (hx : x ∈ s) : connected_component x ⊆ s := is_preconnected_connected_component.subset_clopen hs ⟨x, mem_connected_component, hx⟩ /-- The connected component of a point is always a subset of the intersection of all its clopen neighbourhoods. -/ lemma connected_component_subset_Inter_clopen {x : α} : connected_component x ⊆ ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := subset_Inter $ λ Z, Z.2.1.connected_component_subset Z.2.2 /-- A clopen set is the union of its connected components. -/ lemma is_clopen.bUnion_connected_component_eq {Z : set α} (h : is_clopen Z) : (⋃ x ∈ Z, connected_component x) = Z := subset.antisymm (Union₂_subset $ λ x, h.connected_component_subset) $ λ x hx, mem_Union₂_of_mem hx mem_connected_component /-- The preimage of a connected component is preconnected if the function has connected fibers and a subset is closed iff the preimage is. -/ lemma preimage_connected_component_connected [topological_space β] {f : α → β} (connected_fibers : ∀ t : β, is_connected (f ⁻¹' {t})) (hcl : ∀ (T : set β), is_closed T ↔ is_closed (f ⁻¹' T)) (t : β) : is_connected (f ⁻¹' connected_component t) := begin -- The following proof is essentially https://stacks.math.columbia.edu/tag/0377 -- although the statement is slightly different have hf : surjective f := surjective.of_comp (λ t : β, (connected_fibers t).1), split, { cases hf t with s hs, use s, rw [mem_preimage, hs], exact mem_connected_component }, have hT : is_closed (f ⁻¹' connected_component t) := (hcl (connected_component t)).1 is_closed_connected_component, -- To show it's preconnected we decompose (f ⁻¹' connected_component t) as a subset of two -- closed disjoint sets in α. We want to show that it's a subset of either. rw is_preconnected_iff_subset_of_fully_disjoint_closed hT, intros u v hu hv huv uv_disj, -- To do this we decompose connected_component t into T₁ and T₂ -- we will show that connected_component t is a subset of either and hence -- (f ⁻¹' connected_component t) is a subset of u or v let T₁ := {t' ∈ connected_component t | f ⁻¹' {t'} ⊆ u}, let T₂ := {t' ∈ connected_component t | f ⁻¹' {t'} ⊆ v}, have fiber_decomp : ∀ t' ∈ connected_component t, f ⁻¹' {t'} ⊆ u ∨ f ⁻¹' {t'} ⊆ v, { intros t' ht', apply is_preconnected_iff_subset_of_disjoint_closed.1 (connected_fibers t').2 u v hu hv, { exact subset.trans (hf.preimage_subset_preimage_iff.2 (singleton_subset_iff.2 ht')) huv }, rw uv_disj, exact inter_empty _ }, have T₁_u : f ⁻¹' T₁ = (f ⁻¹' connected_component t) ∩ u, { apply eq_of_subset_of_subset, { rw ←bUnion_preimage_singleton, refine Union₂_subset (λ t' ht', subset_inter _ ht'.2), rw [hf.preimage_subset_preimage_iff, singleton_subset_iff], exact ht'.1 }, rintros a ⟨hat, hau⟩, constructor, { exact mem_preimage.1 hat }, dsimp only, cases fiber_decomp (f a) (mem_preimage.1 hat), { exact h }, { exfalso, rw ←not_nonempty_iff_eq_empty at uv_disj, exact uv_disj (nonempty_of_mem (mem_inter hau (h rfl))) } }, -- This proof is exactly the same as the above (modulo some symmetry) have T₂_v : f ⁻¹' T₂ = (f ⁻¹' connected_component t) ∩ v, { apply eq_of_subset_of_subset, { rw ←bUnion_preimage_singleton, refine Union₂_subset (λ t' ht', subset_inter _ ht'.2), rw [hf.preimage_subset_preimage_iff, singleton_subset_iff], exact ht'.1 }, rintros a ⟨hat, hav⟩, constructor, { exact mem_preimage.1 hat }, dsimp only, cases fiber_decomp (f a) (mem_preimage.1 hat), { exfalso, rw ←not_nonempty_iff_eq_empty at uv_disj, exact uv_disj (nonempty_of_mem (mem_inter (h rfl) hav)) }, { exact h } }, -- Now we show T₁, T₂ are closed, cover connected_component t and are disjoint. have hT₁ : is_closed T₁ := ((hcl T₁).2 (T₁_u.symm ▸ (is_closed.inter hT hu))), have hT₂ : is_closed T₂ := ((hcl T₂).2 (T₂_v.symm ▸ (is_closed.inter hT hv))), have T_decomp : connected_component t ⊆ T₁ ∪ T₂, { intros t' ht', rw mem_union t' T₁ T₂, cases fiber_decomp t' ht' with htu htv, { left, exact ⟨ht', htu⟩ }, right, exact ⟨ht', htv⟩ }, have T_disjoint : T₁ ∩ T₂ = ∅, { rw ←image_preimage_eq (T₁ ∩ T₂) hf, suffices : f ⁻¹' (T₁ ∩ T₂) = ∅, { rw this, exact image_empty _ }, rw [preimage_inter, T₁_u, T₂_v], rw inter_comm at uv_disj, conv { congr, rw [inter_assoc], congr, skip, rw [←inter_assoc, inter_comm, ←inter_assoc, uv_disj, empty_inter], }, exact inter_empty _ }, -- Now we do cases on whether (connected_component t) is a subset of T₁ or T₂ to show -- that the preimage is a subset of u or v. cases (is_preconnected_iff_subset_of_fully_disjoint_closed is_closed_connected_component).1 is_preconnected_connected_component T₁ T₂ hT₁ hT₂ T_decomp T_disjoint, { left, rw subset.antisymm_iff at T₁_u, suffices : f ⁻¹' connected_component t ⊆ f ⁻¹' T₁, { exact subset.trans (subset.trans this T₁_u.1) (inter_subset_right _ _) }, exact preimage_mono h }, right, rw subset.antisymm_iff at T₂_v, suffices : f ⁻¹' connected_component t ⊆ f ⁻¹' T₂, { exact subset.trans (subset.trans this T₂_v.1) (inter_subset_right _ _) }, exact preimage_mono h, end lemma quotient_map.preimage_connected_component [topological_space β] {f : α → β} (hf : quotient_map f) (h_fibers : ∀ y : β, is_connected (f ⁻¹' {y})) (a : α) : f ⁻¹' connected_component (f a) = connected_component a := ((preimage_connected_component_connected h_fibers (λ _, hf.is_closed_preimage.symm) _).subset_connected_component mem_connected_component).antisymm (hf.continuous.maps_to_connected_component a) lemma quotient_map.image_connected_component [topological_space β] {f : α → β} (hf : quotient_map f) (h_fibers : ∀ y : β, is_connected (f ⁻¹' {y})) (a : α) : f '' connected_component a = connected_component (f a) := by rw [← hf.preimage_connected_component h_fibers, image_preimage_eq _ hf.surjective] end preconnected section totally_disconnected /-- A set `s` is called totally disconnected if every subset `t ⊆ s` which is preconnected is a subsingleton, ie either empty or a singleton.-/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → t.subsingleton theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ _ ht _ _ x_in _ _, (ht x_in).elim theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ _ ht _, subsingleton.mono subsingleton_singleton ht /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) lemma is_preconnected.subsingleton [totally_disconnected_space α] {s : set α} (h : is_preconnected s) : s.subsingleton := totally_disconnected_space.is_totally_disconnected_univ s (subset_univ s) h instance pi.totally_disconnected_space {α : Type*} {β : α → Type*} [t₂ : Πa, topological_space (β a)] [∀a, totally_disconnected_space (β a)] : totally_disconnected_space (Π (a : α), β a) := ⟨λ t h1 h2, have this : ∀ a, is_preconnected ((λ x : Π a, β a, x a) '' t), from λ a, h2.image (λ x, x a) (continuous_apply a).continuous_on, λ x x_in y y_in, funext $ λ a, (this a).subsingleton ⟨x, x_in, rfl⟩ ⟨y, y_in, rfl⟩⟩ instance prod.totally_disconnected_space [topological_space β] [totally_disconnected_space α] [totally_disconnected_space β] : totally_disconnected_space (α × β) := ⟨λ t h1 h2, have H1 : is_preconnected (prod.fst '' t), from h2.image prod.fst continuous_fst.continuous_on, have H2 : is_preconnected (prod.snd '' t), from h2.image prod.snd continuous_snd.continuous_on, λ x hx y hy, prod.ext (H1.subsingleton ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩) (H2.subsingleton ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩)⟩ instance [topological_space β] [totally_disconnected_space α] [totally_disconnected_space β] : totally_disconnected_space (α ⊕ β) := begin refine ⟨λ s _ hs, _⟩, obtain (⟨t, ht, rfl⟩ | ⟨t, ht, rfl⟩) := sum.is_preconnected_iff.1 hs, { exact ht.subsingleton.image _ }, { exact ht.subsingleton.image _ } end instance [Π i, topological_space (π i)] [∀ i, totally_disconnected_space (π i)] : totally_disconnected_space (Σ i, π i) := begin refine ⟨λ s _ hs, _⟩, obtain rfl | h := s.eq_empty_or_nonempty, { exact subsingleton_empty }, { obtain ⟨a, t, ht, rfl⟩ := sigma.is_connected_iff.1 ⟨h, hs⟩, exact ht.is_preconnected.subsingleton.image _ } end /-- Let `X` be a topological space, and suppose that for all distinct `x,y ∈ X`, there is some clopen set `U` such that `x ∈ U` and `y ∉ U`. Then `X` is totally disconnected. -/ lemma is_totally_disconnected_of_clopen_set {X : Type*} [topological_space X] (hX : ∀ {x y : X} (h_diff : x ≠ y), ∃ (U : set X) (h_clopen : is_clopen U), x ∈ U ∧ y ∉ U) : is_totally_disconnected (set.univ : set X) := begin rintro S - hS, unfold set.subsingleton, by_contra' h_contra, rcases h_contra with ⟨x, hx, y, hy, hxy⟩, obtain ⟨U, h_clopen, hxU, hyU⟩ := hX hxy, specialize hS U Uᶜ h_clopen.1 h_clopen.compl.1 (λ a ha, em (a ∈ U)) ⟨x, hx, hxU⟩ ⟨y, hy, hyU⟩, rw [inter_compl_self, set.inter_empty] at hS, exact set.not_nonempty_empty hS, end /-- A space is totally disconnected iff its connected components are subsingletons. -/ lemma totally_disconnected_space_iff_connected_component_subsingleton : totally_disconnected_space α ↔ ∀ x : α, (connected_component x).subsingleton := begin split, { intros h x, apply h.1, { exact subset_univ _ }, exact is_preconnected_connected_component }, intro h, constructor, intros s s_sub hs, rcases eq_empty_or_nonempty s with rfl | ⟨x, x_in⟩, { exact subsingleton_empty }, { exact (h x).mono (hs.subset_connected_component x_in) } end /-- A space is totally disconnected iff its connected components are singletons. -/ lemma totally_disconnected_space_iff_connected_component_singleton : totally_disconnected_space α ↔ ∀ x : α, connected_component x = {x} := begin rw totally_disconnected_space_iff_connected_component_subsingleton, apply forall_congr (λ x, _), rw subsingleton_iff_singleton, exact mem_connected_component end /-- The image of a connected component in a totally disconnected space is a singleton. -/ @[simp] lemma continuous.image_connected_component_eq_singleton {β : Type*} [topological_space β] [totally_disconnected_space β] {f : α → β} (h : continuous f) (a : α) : f '' connected_component a = {f a} := (set.subsingleton_iff_singleton $ mem_image_of_mem f mem_connected_component).mp (is_preconnected_connected_component.image f h.continuous_on).subsingleton lemma is_totally_disconnected_of_totally_disconnected_space [totally_disconnected_space α] (s : set α) : is_totally_disconnected s := λ t hts ht, totally_disconnected_space.is_totally_disconnected_univ _ t.subset_univ ht lemma is_totally_disconnected_of_image [topological_space β] {f : α → β} (hf : continuous_on f s) (hf' : injective f) (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := λ t hts ht x x_in y y_in, hf' $ h _ (image_subset f hts) (ht.image f $ hf.mono hts) (mem_image_of_mem f x_in) (mem_image_of_mem f y_in) lemma embedding.is_totally_disconnected [topological_space β] {f : α → β} (hf : embedding f) {s : set α} (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := is_totally_disconnected_of_image hf.continuous.continuous_on hf.inj h instance subtype.totally_disconnected_space {α : Type*} {p : α → Prop} [topological_space α] [totally_disconnected_space α] : totally_disconnected_space (subtype p) := ⟨embedding_subtype_coe.is_totally_disconnected (is_totally_disconnected_of_totally_disconnected_space _)⟩ end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := begin intros t hts ht x x_in y y_in, by_contra h, obtain ⟨u : set α, v : set α, hu : is_open u, hv : is_open v, hxu : x ∈ u, hyv : y ∈ v, hs : s ⊆ u ∪ v, huv : u ∩ v = ∅⟩ := H x (hts x_in) y (hts y_in) h, have : (t ∩ u).nonempty → (t ∩ v).nonempty → (t ∩ (u ∩ v)).nonempty := ht _ _ hu hv (subset.trans hts hs), obtain ⟨z, hz : z ∈ t ∩ (u ∩ v)⟩ := this ⟨x, x_in, hxu⟩ ⟨y, y_in, hyv⟩, simpa [huv] using hz end alias is_totally_disconnected_of_is_totally_separated ← is_totally_separated.is_totally_disconnected /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.of_discrete (α : Type*) [topological_space α] [discrete_topology α] : totally_separated_space α := ⟨λ a _ b _ h, ⟨{b}ᶜ, {b}, is_open_discrete _, is_open_discrete _, by simpa⟩⟩ lemma exists_clopen_of_totally_separated {α : Type*} [topological_space α] [totally_separated_space α] {x y : α} (hxy : x ≠ y) : ∃ (U : set α) (hU : is_clopen U), x ∈ U ∧ y ∈ Uᶜ := begin obtain ⟨U, V, hU, hV, Ux, Vy, f, disj⟩ := totally_separated_space.is_totally_separated_univ α x (set.mem_univ x) y (set.mem_univ y) hxy, have clopen_U := is_clopen_inter_of_disjoint_cover_clopen (is_clopen_univ) f hU hV disj, rw univ_inter _ at clopen_U, rw [←set.subset_compl_iff_disjoint, subset_compl_comm] at disj, exact ⟨U, clopen_U, Ux, disj Vy⟩, end end totally_separated section connected_component_setoid /-- The setoid of connected components of a topological space -/ def connected_component_setoid (α : Type*) [topological_space α] : setoid α := ⟨λ x y, connected_component x = connected_component y, ⟨λ x, by trivial, λ x y h1, h1.symm, λ x y z h1 h2, h1.trans h2⟩⟩ /-- The quotient of a space by its connected components -/ def connected_components (α : Type u) [topological_space α] := quotient (connected_component_setoid α) instance : has_coe_t α (connected_components α) := ⟨quotient.mk'⟩ namespace connected_components @[simp] lemma coe_eq_coe {x y : α} : (x : connected_components α) = y ↔ connected_component x = connected_component y := quotient.eq' lemma coe_ne_coe {x y : α} : (x : connected_components α) ≠ y ↔ connected_component x ≠ connected_component y := not_congr coe_eq_coe lemma coe_eq_coe' {x y : α} : (x : connected_components α) = y ↔ x ∈ connected_component y := coe_eq_coe.trans ⟨λ h, h ▸ mem_connected_component, λ h, (connected_component_eq h).symm⟩ instance [inhabited α] : inhabited (connected_components α) := ⟨↑(default : α)⟩ instance : topological_space (connected_components α) := quotient.topological_space lemma surjective_coe : surjective (coe : α → connected_components α) := surjective_quot_mk _ lemma quotient_map_coe : quotient_map (coe : α → connected_components α) := quotient_map_quot_mk @[continuity] lemma continuous_coe : continuous (coe : α → connected_components α) := quotient_map_coe.continuous @[simp] lemma range_coe : range (coe : α → connected_components α)= univ := surjective_coe.range_eq end connected_components variables [topological_space β] [totally_disconnected_space β] {f : α → β} lemma continuous.image_eq_of_connected_component_eq (h : continuous f) (a b : α) (hab : connected_component a = connected_component b) : f a = f b := singleton_eq_singleton_iff.1 $ h.image_connected_component_eq_singleton a ▸ h.image_connected_component_eq_singleton b ▸ hab ▸ rfl /-- The lift to `connected_components α` of a continuous map from `α` to a totally disconnected space -/ def continuous.connected_components_lift (h : continuous f) : connected_components α → β := λ x, quotient.lift_on' x f h.image_eq_of_connected_component_eq @[continuity] lemma continuous.connected_components_lift_continuous (h : continuous f) : continuous h.connected_components_lift := continuous_quotient_lift_on' h.image_eq_of_connected_component_eq h @[simp] lemma continuous.connected_components_lift_apply_coe (h : continuous f) (x : α) : h.connected_components_lift x = f x := rfl @[simp] lemma continuous.connected_components_lift_comp_coe (h : continuous f) : h.connected_components_lift ∘ coe = f := rfl lemma connected_components_lift_unique' {β : Sort*} {g₁ g₂ : connected_components α → β} (hg : g₁ ∘ (coe : α → connected_components α) = g₂ ∘ coe) : g₁ = g₂ := connected_components.surjective_coe.injective_comp_right hg lemma continuous.connected_components_lift_unique (h : continuous f) (g : connected_components α → β) (hg : g ∘ coe = f) : g = h.connected_components_lift := connected_components_lift_unique' $ hg.trans h.connected_components_lift_comp_coe.symm /-- The preimage of a singleton in `connected_components` is the connected component of an element in the equivalence class. -/ lemma connected_components_preimage_singleton {x : α} : coe ⁻¹' ({x} : set (connected_components α)) = connected_component x := by { ext y, simp [connected_components.coe_eq_coe'] } /-- The preimage of the image of a set under the quotient map to `connected_components α` is the union of the connected components of the elements in it. -/ lemma connected_components_preimage_image (U : set α) : coe ⁻¹' (coe '' U : set (connected_components α)) = ⋃ x ∈ U, connected_component x := by simp only [connected_components_preimage_singleton, preimage_Union₂, image_eq_Union] instance connected_components.totally_disconnected_space : totally_disconnected_space (connected_components α) := begin rw totally_disconnected_space_iff_connected_component_singleton, refine connected_components.surjective_coe.forall.2 (λ x, _), rw [← connected_components.quotient_map_coe.image_connected_component, ← connected_components_preimage_singleton, image_preimage_eq _ connected_components.surjective_coe], refine connected_components.surjective_coe.forall.2 (λ y, _), rw connected_components_preimage_singleton, exact is_connected_connected_component end /-- Functoriality of `connected_components` -/ def continuous.connected_components_map {β : Type*} [topological_space β] {f : α → β} (h : continuous f) : connected_components α → connected_components β := continuous.connected_components_lift (continuous_quotient_mk.comp h) lemma continuous.connected_components_map_continuous {β : Type*} [topological_space β] {f : α → β} (h : continuous f) : continuous h.connected_components_map := continuous.connected_components_lift_continuous (continuous_quotient_mk.comp h) end connected_component_setoid
57621ea2622a20e79325b20fd51e89d246248ef2
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Parser/Do.lean
f0a2e630f031b8bffcda3939a62bc8608aa1ecc8
[ "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
8,786
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 ``Category.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 := leading_parser:minPrec leftArrow >> termParser def doSeqItem := leading_parser ppLine >> doElemParser >> optional "; " def doSeqIndent := leading_parser many1Indent doSeqItem def doSeqBracketed := leading_parser "{" >> withoutPosition (many1 doSeqItem) >> ppLine >> "}" def doSeq := withAntiquot (mkAntiquot "doSeq" `Lean.Parser.Term.doSeq (isPseudoKind := true)) <| doSeqBracketed <|> doSeqIndent def termBeforeDo := withForbidden "do" termParser attribute [runBuiltinParserAttributeHooks] doSeq termBeforeDo builtin_initialize register_parser_alias doSeq register_parser_alias termBeforeDo def notFollowedByRedefinedTermToken := -- Remark: we don't currently support `open` and `set_option` in `do`-blocks, but we include them in the following list to fix the ambiguity -- "open" command following `do`-block. If we don't add `do`, then users would have to indent `do` blocks or use `{ ... }`. notFollowedBy ("set_option" <|> "open" <|> "if" <|> "match" <|> "let" <|> "have" <|> "do" <|> "dbg_trace" <|> "assert!" <|> "for" <|> "unless" <|> "return" <|> symbol "try") "token at 'do' element" @[builtinDoElemParser] def doLet := leading_parser "let " >> optional "mut " >> letDecl @[builtinDoElemParser] def doLetElse := leading_parser "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doElemParser @[builtinDoElemParser] def doLetRec := leading_parser group ("let " >> nonReservedSymbol "rec ") >> letRecDecls def doIdDecl := leading_parser atomic (ident >> optType >> ppSpace >> leftArrow) >> doElemParser def doPatDecl := leading_parser atomic (termParser >> ppSpace >> leftArrow) >> doElemParser >> optional (checkColGt >> " | " >> doElemParser) @[builtinDoElemParser] def doLetArrow := leading_parser withPosition ("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 := leading_parser notFollowedByRedefinedTermToken >> (letIdDeclNoBinders <|> letPatDecl) @[builtinDoElemParser] def doReassignArrow := leading_parser notFollowedByRedefinedTermToken >> withPosition (doIdDecl <|> doPatDecl) @[builtinDoElemParser] def doHave := leading_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 "))) -- ensure `if $e then ...` still binds to `e:term` def doIfLetPure := leading_parser " := " >> termParser def doIfLetBind := leading_parser " ← " >> termParser def doIfLet := leading_parser (withAnonymousAntiquot := false) "let " >> termParser >> (doIfLetPure <|> doIfLetBind) def doIfProp := leading_parser (withAnonymousAntiquot := false) optIdent >> termParser def doIfCond := withAntiquot (mkAntiquot "doIfCond" `Lean.Parser.Term.doIfCond (anonymous := false) (isPseudoKind := true)) <| doIfLet <|> doIfProp @[builtinDoElemParser] def doIf := leading_parser withPositionAfterLinebreak $ "if " >> doIfCond >> " then " >> doSeq >> many (checkColGe "'else if' in 'do' must be indented" >> group (elseIf >> doIfCond >> " then " >> doSeq)) >> optional (checkColGe "'else' in 'do' must be indented" >> " else " >> doSeq) @[builtinDoElemParser] def doUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq def doForDecl := leading_parser optional (atomic (ident >> " : ")) >> termParser >> " in " >> withForbidden "do" termParser /-- `for x in e do s` iterates over `e` assuming `e`'s type has an instance of the `ForIn` typeclass. `break` and `continue` are supported inside `for` loops. `for x in e, x2 in e2, ... do s` iterates of the given collections in parallel, until at least one of them is exhausted. The types of `e2` etc. must implement the `ToStream` typeclass. -/ @[builtinDoElemParser] def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq def doMatchAlts := ppDedent <| matchAlts (rhsParser := doSeq) @[builtinDoElemParser] def doMatch := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> optional Term.motive >> sepBy1 matchDiscr ", " >> " with " >> doMatchAlts def doCatch := leading_parser atomic ("catch " >> binderIdent) >> optional (" : " >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq @[builtinDoElemParser] def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally /-- `break` exits the surrounding `for` loop. -/ @[builtinDoElemParser] def doBreak := leading_parser "break" /-- `continue` skips to the next iteration of the surrounding `for` loop. -/ @[builtinDoElemParser] def doContinue := leading_parser "continue" /-- `return e` inside of a `do` block makes the surrounding block evaluate to `pure e`, skipping any further statements. Note that uses of the `do` keyword in other syntax like in `for _ in _ do` do not constitute a surrounding block in this sense; in supported editors, the corresponding `do` keyword of the surrounding block is highlighted when hovering over `return`. `return` not followed by a term starting on the same line is equivalent to `return ()`. -/ @[builtinDoElemParser] def doReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) @[builtinDoElemParser] def doDbgTrace := leading_parser:leadPrec "dbg_trace " >> ((interpolatedStr termParser) <|> termParser) @[builtinDoElemParser] def doAssert := leading_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. The first `notFollowedBy` prevents this problem. Consider the `doElem` `x := (a, b⟩` it contains an error since we are using `⟩` instead of `)`. Thus, `doReassign` parser fails. However, `doExpr` would succeed consuming just `x`, and cryptic error message is generated after that. The second `notFollowedBy` prevents this problem. -/ @[builtinDoElemParser] def doExpr := leading_parser notFollowedByRedefinedTermToken >> termParser >> notFollowedBy (symbol ":=" <|> symbol "←" <|> symbol "<-") "unexpected token after 'expr' in 'do' block" @[builtinDoElemParser] def doNested := leading_parser "do " >> doSeq @[builtinTermParser] def «do» := leading_parser:argPrec ppAllowUngrouped >> "do " >> doSeq @[builtinTermParser] def doElem.quot : Parser := leading_parser "`(doElem|" >> incQuotDepth doElemParser >> ")" /- macros for using `unless`, `for`, `try`, `return` as terms. They expand into `do unless ...`, `do for ...`, `do try ...`, and `do return ...` -/ /-- `unless e do s` is a nicer way to write `if !e do s`. -/ @[builtinTermParser] def termUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq @[builtinTermParser] def termFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq @[builtinTermParser] def termTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally /-- `return` used outside of `do` blocks creates an implicit block around it and thus is equivalent to `pure e`, but helps with avoiding parentheses. -/ @[builtinTermParser] def termReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) end Term end Parser end Lean
b20aca75692a04e9fe5dcc643512c1ce1301e033
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/j3.lean
3cb5d9b7bda2dd0f7f13a9a608999745a57b708e
[ "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
1,415
lean
import macros import tactic using Nat definition dvd (a b : Nat) : Bool := ∃ c, a * c = b infix 50 | : dvd theorem dvd_elim {a b : Nat} (H : a | b) : ∃ c, a * c = b := H theorem dvd_intro {a b : Nat} (c : Nat) (H : a * c = b) : a | b := exists_intro c H set_opaque dvd true theorem dvd_trans {a b c} (H1 : a | b) (H2 : b | c) : a | c := obtain (w1 : Nat) (Hw1 : a * w1 = b), from dvd_elim H1, obtain (w2 : Nat) (Hw2 : b * w2 = c), from dvd_elim H2, dvd_intro (w1 * w2) (calc a * (w1 * w2) = a * w1 * w2 : symm (mul_assoc a w1 w2) ... = b * w2 : { Hw1 } ... = c : Hw2) definition prime p := p ≥ 2 ∧ forall m, m | p → m = 1 ∨ m = p theorem not_prime_eq (n : Nat) (H1 : n ≥ 2) (H2 : ¬ prime n) : ∃ m, m | n ∧ m ≠ 1 ∧ m ≠ n := have H3 : ¬ n ≥ 2 ∨ ¬ (∀ m : Nat, m | n → m = 1 ∨ m = n), from (not_and _ _ ◂ H2), have H4 : ¬ ¬ n ≥ 2, from ((symm (not_not_eq _)) ◂ H1), obtain (m : Nat) (H5 : ¬ (m | n → m = 1 ∨ m = n)), from (not_forall_elim (resolve1 H3 H4)), have H6 : m | n ∧ ¬ (m = 1 ∨ m = n), from ((not_implies _ _) ◂ H5), have H7 : ¬ (m = 1 ∨ m = n) ↔ (m ≠ 1 ∧ m ≠ n), from (not_or (m = 1) (m = n)), have H8 : m | n ∧ m ≠ 1 ∧ m ≠ n, from subst H6 H7, show ∃ m, m | n ∧ m ≠ 1 ∧ m ≠ n, from exists_intro m H8
512fc62ad566641d74acb08dd058ff33a36174ff
7cef822f3b952965621309e88eadf618da0c8ae9
/src/linear_algebra/finite_dimensional.lean
b09bb14a61432bc95eb148c8e982c2313d696de0
[ "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
17,130
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.noetherian linear_algebra.dimension import ring_theory.principal_ideal_domain /-! # Finite dimensional vector spaces Definition and basic properties of finite dimensional vector spaces, of their dimensions, and of linear maps on such spaces. ## Main definitions Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of finite-dimensionality of `V`: - it admits a finite basis. - it is finitely generated. - it is noetherian, i.e., every subspace is finitely generated. We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of proof, it is defined using the third point of view, i.e., as `is_noetherian`. However, we prove that all these points of view are equivalent, with the following lemmas (in the namespace `finite_dimensional`): - `exists_is_basis_finite` states that a finite-dimensional vector space has a finite basis - `of_finite_basis` states that the existence of a finite basis implies finite-dimensionality - `iff_fg` states that the space is finite-dimensional if and only if it is finitely generated Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `dim`, which returns a `cardinal`. When the space has infinite dimension, its `findim` is by convention set to `0`. Preservation of finite-dimensionality and formulas for the dimension are given for - submodules - quotients (for the dimension of a quotient, see `findim_quotient_add_findim`) - linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.findim_eq` - image under a linear map (the rank-nullity formula is in `findim_range_add_findim_ker`) Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`, and the equivalence between left-inverse and right-inverse in `mul_eq_one_comm` and `comp_eq_id_comm`. ## Implementation notes Most results are deduced from the corresponding results for the general dimension (as a cardinal), in `dimension.lean`. Not all results have been ported yet. One of the characterizations of finite-dimensionality is in terms of finite generation. This property is currently defined only for submodules, so we express it through the fact that the maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is not very convenient to use, although there are some helper functions. However, this becomes very convenient when speaking of submodules which are finite-dimensional, as this notion coincides with the fact that the submodule is finitely generated (as a submodule of the whole space). This equivalence is proved in `submodule.fg_iff_finite_dimensional`. -/ universes u v v' w open_locale classical open vector_space cardinal submodule module function variables {K : Type u} {V : Type v} [discrete_field K] [add_comm_group V] [vector_space K V] {V₂ : Type v'} [add_comm_group V₂] [vector_space K V₂] /-- `finite_dimensional` vector spaces are defined to be noetherian modules. Use `finite_dimensional.iff_fg` or `finite_dimensional.of_finite_basis` to prove finite dimension from a conventional definition. -/ @[reducible] def finite_dimensional (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] := is_noetherian K V namespace finite_dimensional open is_noetherian /-- A vector space is finite-dimensional if and only if its dimension (as a cardinal) is strictly less than the first infinite cardinal `omega`. -/ lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} := begin cases exists_is_basis K V with b hb, have := is_basis.mk_eq_dim hb, simp only [lift_id] at this, rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.val_range], split, { intro, resetI, convert finite_of_linear_independent hb.1, simp }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← hb.2], refl } end /-- The dimension of a finite-dimensional vector space, as a cardinal, is strictly less than the first infinite cardinal `omega`. -/ lemma dim_lt_omega (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] : ∀ [finite_dimensional K V], dim K V < omega.{v} := finite_dimensional_iff_dim_lt_omega.1 /-- In a finite dimensional space, there exists a finite basis. A basis is in general given as a function from an arbitrary type to the vector space. Here, we think of a basis as a set (instead of a function), and use as parametrizing type this set (and as a function the function `subtype.val`). -/ variables (K V) lemma exists_is_basis_finite [finite_dimensional K V] : ∃ s : set V, (is_basis K (subtype.val : s → V)) ∧ s.finite := begin cases exists_is_basis K V with s hs, exact ⟨s, hs, finite_of_linear_independent hs.1⟩ end variables {K V} /-- A vector space is finite-dimensional if and only if it is finitely generated. As the finitely-generated property is a property of submodules, we formulate this in terms of the maximal submodule, equal to the whole space as a set by definition.-/ lemma iff_fg : finite_dimensional K V ↔ (⊤ : submodule K V).fg := begin split, { introI h, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, exact ⟨s_finite.to_finset, by { convert s_basis.2, simp }⟩ }, { rintros ⟨s, hs⟩, rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs], exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) } end /-- If a vector space has a finite basis, then it is finite-dimensional. -/ lemma of_finite_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : finite_dimensional K V := iff_fg.2 $ ⟨finset.univ.image b, by {convert h.2, simp} ⟩ /-- A subspace of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V)) /-- A quotient of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) : finite_dimensional K (quotient S) := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_quotient_le _) (dim_lt_omega K V)) /-- The dimension of a finite-dimensional vector space as a natural number. Defined by convention to be `0` if the space is infinite-dimensional. -/ noncomputable def findim (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] : ℕ := if h : dim K V < omega.{v} then classical.some (lt_omega.1 h) else 0 /-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its `findim`. -/ lemma findim_eq_dim (K : Type u) (V : Type v) [discrete_field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : (findim K V : cardinal.{v}) = dim K V := begin have : findim K V = classical.some (lt_omega.1 (dim_lt_omega K V)) := dif_pos (dim_lt_omega K V), rw this, exact (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm end /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : dim K V = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective (h.injective zero_ne_one)] /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. -/ lemma findim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : findim K V = fintype.card ι := begin haveI : finite_dimensional K V := of_finite_basis h, have := dim_eq_card_basis h, rw ← findim_eq_dim at this, exact_mod_cast this end /-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its `findim`. -/ lemma findim_eq_card_basis' [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : is_basis K b) : (findim K V : cardinal.{w}) = cardinal.mk ι := begin rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI: fintype s := s_finite.fintype, have A : cardinal.mk s = fintype.card s := fintype_card _, have B : findim K V = fintype.card s := findim_eq_card_basis s_basis, have C : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk s) := mk_eq_mk_of_basis h s_basis, rw [A, ← B, lift_nat_cast] at C, have : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{w v} (findim K V), by { simp, exact C }, exact (lift_inj.mp this).symm end /-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the whole space. -/ lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V} (h : findim K S = findim K V) : S = ⊤ := begin cases exists_is_basis K S with bS hbS, have : linear_independent K (subtype.val : (subtype.val '' bS : set V) → V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) hbS.1 (by simp), cases exists_subset_is_basis this with b hb, letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1), letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this), letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1), have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1 (by rw [set.card_image_of_injective _ subtype.val_injective, ← findim_eq_card_basis hbS, ← findim_eq_card_basis hb.2, h]; apply_instance), erw [← hb.2.2, subtype.val_range, ← this, set.set_of_mem_eq, ← subtype_eq_val, span_image], have := hbS.2, erw [subtype.val_range, set.set_of_mem_eq] at this, rw [this, map_top (submodule.subtype S), range_subtype], end variable (K) /-- A field is one-dimensional as a vector space over itself. -/ @[simp] lemma findim_of_field : findim K K = 1 := begin have := dim_of_field K, rw [← findim_eq_dim] at this, exact_mod_cast this end /-- The vector space of functions on a fintype has finite dimension. -/ instance finite_dimensional_fintype_fun {ι : Type*} [fintype ι] : finite_dimensional K (ι → K) := by { rw [finite_dimensional_iff_dim_lt_omega, dim_fun'], exact nat_lt_omega _ } /-- The vector space of functions on a fintype ι has findim equal to the cardinality of ι. -/ @[simp] lemma findim_fintype_fun_eq_card {ι : Type v} [fintype ι] : findim K (ι → K) = fintype.card ι := begin have : vector_space.dim K (ι → K) = fintype.card ι := dim_fun', rwa [← findim_eq_dim, nat_cast_inj] at this, end /-- The vector space of functions on `fin n` has findim equal to `n`. -/ @[simp] lemma findim_fin_fun {n : ℕ} : findim K (fin n → K) = n := by simp /-- The submodule generated by a finite set is finite-dimensional. -/ theorem span_of_finite {A : set V} (hA : set.finite A) : finite_dimensional K (submodule.span K A) := is_noetherian_span_of_finite K hA end finite_dimensional namespace submodule open finite_dimensional /-- A submodule is finitely generated if and only if it is finite-dimensional -/ theorem fg_iff_finite_dimensional (s : submodule K V) : s.fg ↔ finite_dimensional K s := ⟨λh, is_noetherian_of_fg_of_noetherian s h, λh, by { rw ← map_subtype_top s, exact fg_map (iff_fg.1 h) }⟩ /-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding quotient add up to the dimension of the space. -/ theorem findim_quotient_add_findim [finite_dimensional K V] (s : submodule K V) : findim K s.quotient + findim K s = findim K V := begin have := dim_quotient_add_dim s, rw [← findim_eq_dim, ← findim_eq_dim, ← findim_eq_dim] at this, exact_mod_cast this end /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma findim_le [finite_dimensional K V] (s : submodule K V) : findim K s ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_left _ _ } /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma findim_quotient_le [finite_dimensional K V] (s : submodule K V) : findim K s.quotient ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_right _ _ } end submodule namespace linear_equiv open finite_dimensional /-- Finite dimensionality is preserved under linear equivalence. -/ protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : finite_dimensional K V₂ := is_noetherian_of_linear_equiv f /-- The dimension of a finite dimensional space is preserved under linear equivalence. -/ theorem findim_eq (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : findim K V = findim K V₂ := begin haveI : finite_dimensional K V₂ := f.finite_dimensional, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI : fintype s := s_finite.fintype, have A : findim K V = fintype.card s := findim_eq_card_basis s_basis, have : is_basis K (λx:s, f (subtype.val x)) := f.is_basis s_basis, have B : findim K V₂ = fintype.card s := findim_eq_card_basis this, rw [A, B] end end linear_equiv namespace linear_map open finite_dimensional /-- On a finite-dimensional space, an injective linear map is surjective. -/ lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_injective _ hinj, rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_findim_eq h.symm) end /-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/ lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} : injective f ↔ surjective f := ⟨surjective_of_injective, λ hsurj, let ⟨g, hg⟩ := exists_right_inverse_linear_map_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from λ x, show (linear_map.comp f g) x = (@linear_map.id K V _ _ _ : V → V) x, by rw hg, injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse (surjective_of_injective (injective_of_has_left_inverse ⟨_, this⟩)) this⟩⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] /-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they are also inverse to each other on the other side. -/ lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) : g * f = 1 := have ginj : injective g, from injective_of_has_left_inverse ⟨f, λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl⟩, let ⟨i, hi⟩ := exists_right_inverse_linear_map_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id := mul_eq_one_comm /-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/ lemma finite_dimensional_of_surjective [h : finite_dimensional K V] (f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ := is_noetherian_of_surjective V f hf /-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) : finite_dimensional K f.range := f.quot_ker_equiv_range.finite_dimensional /-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to the dimension of the source space. -/ theorem findim_range_add_findim_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) : findim K f.range + findim K f.ker = findim K V := by { rw [← f.quot_ker_equiv_range.findim_eq], exact submodule.findim_quotient_add_findim _ } end linear_map
608c60cde18229988984c7108cf299e176ecfeca
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/adjunction/limits.lean
1b009900b89d81ebeab2b49b3dff89e79f2770af
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
8,656
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.creates open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality _ G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality _ F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality _ F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (cocones.functoriality K F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. See https://stacks.math.columbia.edu/tag/0038. -/ def left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, @equiv.unique _ _ (is_colimit.iso_unique_cocone_morphism.hom hc _) (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _)) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := left_adjoint_preserves_colimits E.adjunction -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := has_colimit.mk { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves (colimit.is_colimit K) } lemma has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality _ F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality _ G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality _ G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (cones.functoriality K G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. See https://stacks.math.columbia.edu/tag/0038. -/ def right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, @equiv.unique _ _ (is_limit.iso_unique_cone_morphism.hom hc _) (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := right_adjoint_preserves_limits E.inv.adjunction @[priority 100] -- see Note [lower instance priority] instance is_equivalence_reflects_limits (E : D ⥤ C) [is_equivalence E] : reflects_limits E := { reflects_limits_of_shape := λ J 𝒥, by exactI { reflects_limit := λ K, { reflects := λ c t, begin have l: is_limit (E.inv.map_cone (E.map_cone c)) := preserves_limit.preserves t, convert is_limit.map_cone_equiv E.fun_inv_id l, { rw functor.comp_id }, { cases c, cases c_π, congr; rw functor.comp_id } end } } } @[priority 100] -- see Note [lower instance priority] instance is_equivalence_creates_limits (H : D ⥤ C) [is_equivalence H] : creates_limits H := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ F, { lifts := λ c t, { lifted_cone := H.map_cone_inv c, valid_lift := H.map_cone_map_cone_inv c } } } } -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := has_limit.mk { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves (limit.is_limit K) } lemma has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxiliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by { erw [← adj.hom_equiv_naturality_left, t.naturality], dsimp, simp } } /-- auxiliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxiliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxiliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
772eb074469c2ad174ed312e262b8e3862ff733d
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/star/pi.lean
e86ed581ead5576aa65c11349389defacf441631
[ "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,646
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.star.basic import algebra.ring.pi import algebra.module.pi /-! # `star` on pi types We put a `has_star` structure on pi types that operates elementwise, such that it describes the complex conjugation of vectors. -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances namespace pi instance [Π i, has_star (f i)] : has_star (Π i, f i) := { star := λ x i, star (x i) } @[simp] lemma star_apply [Π i, has_star (f i)] (x : Π i, f i) (i : I) : star x i = star (x i) := rfl lemma star_def [Π i, has_star (f i)] (x : Π i, f i) : star x = λ i, star (x i) := rfl instance [Π i, has_involutive_star (f i)] : has_involutive_star (Π i, f i) := { star_involutive := λ _, funext $ λ _, star_star _ } instance [Π i, semigroup (f i)] [Π i, star_semigroup (f i)] : star_semigroup (Π i, f i) := { star_mul := λ _ _, funext $ λ _, star_mul _ _ } instance [Π i, add_monoid (f i)] [Π i, star_add_monoid (f i)] : star_add_monoid (Π i, f i) := { star_add := λ _ _, funext $ λ _, star_add _ _ } instance [Π i, non_unital_semiring (f i)] [Π i, star_ring (f i)] : star_ring (Π i, f i) := { ..pi.star_add_monoid, ..(pi.star_semigroup : star_semigroup (Π i, f i)) } instance {R : Type w} [Π i, has_scalar R (f i)] [has_star R] [Π i, has_star (f i)] [Π i, star_module R (f i)] : star_module R (Π i, f i) := { star_smul := λ r x, funext $ λ i, star_smul r (x i) } end pi
a336844ab532f868e1dfdc3ae26142913e90aea1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/fundamental_groupoid/simply_connected.lean
e04bbe10c63b603d3516e6fe59d0a0216f09ea86
[ "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,797
lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import algebraic_topology.fundamental_groupoid.induced_maps import topology.homotopy.contractible import category_theory.punit import algebraic_topology.fundamental_groupoid.punit /-! # Simply connected spaces This file defines simply connected spaces. A topological space is simply connected if its fundamental groupoid is equivalent to `unit`. ## Main theorems - `simply_connected_iff_unique_homotopic` - A space is simply connected if and only if it is nonempty and there is a unique path up to homotopy between any two points - `simply_connected_space.of_contractible` - A contractible space is simply connected -/ noncomputable theory open category_theory open continuous_map open_locale continuous_map /-- A simply connected space is one whose fundamental groupoid is equivalent to `discrete unit` -/ class simply_connected_space (X : Type*) [topological_space X] : Prop := (equiv_unit [] : nonempty (fundamental_groupoid X ≌ discrete unit)) lemma simply_connected_def (X : Type*) [topological_space X] : simply_connected_space X ↔ nonempty (fundamental_groupoid X ≌ discrete unit) := ⟨λ h, @simply_connected_space.equiv_unit X _ h, λ h, ⟨h⟩⟩ lemma simply_connected_iff_unique_homotopic (X : Type*) [topological_space X] : simply_connected_space X ↔ (nonempty X) ∧ ∀ (x y : X), nonempty (unique (path.homotopic.quotient x y)) := by { rw [simply_connected_def, equiv_punit_iff_unique], refl, } namespace simply_connected_space variables {X : Type*} [topological_space X] [simply_connected_space X] instance (x y : X) : subsingleton (path.homotopic.quotient x y) := @unique.subsingleton _ (nonempty.some (by { rw simply_connected_iff_unique_homotopic at *, tauto })) local attribute [instance] path.homotopic.setoid @[priority 100] instance : path_connected_space X := let unique_homotopic := (simply_connected_iff_unique_homotopic X).mp infer_instance in { nonempty := unique_homotopic.1, joined := λ x y, ⟨(unique_homotopic.2 x y).some.default.out⟩, } /-- In a simply connected space, any two paths are homotopic -/ lemma paths_homotopic {x y : X} (p₁ p₂ : path x y) : path.homotopic p₁ p₂ := by simpa using @subsingleton.elim (path.homotopic.quotient x y) _ ⟦p₁⟧ ⟦p₂⟧ @[priority 100] instance of_contractible (Y : Type*) [topological_space Y] [contractible_space Y] : simply_connected_space Y := { equiv_unit := let H : Top.of Y ≃ₕ Top.of unit := (contractible_space.hequiv_unit Y).some in ⟨(fundamental_groupoid_functor.equiv_of_homotopy_equiv H).trans fundamental_groupoid.punit_equiv_discrete_punit⟩, } end simply_connected_space local attribute [instance] path.homotopic.setoid /-- A space is simply connected iff it is path connected, and there is at most one path up to homotopy between any two points. -/ lemma simply_connected_iff_paths_homotopic {Y : Type*} [topological_space Y] : simply_connected_space Y ↔ (path_connected_space Y) ∧ (∀ x y : Y, subsingleton (path.homotopic.quotient x y)) := ⟨by { introI, split; apply_instance, }, λ h, begin casesI h, rw simply_connected_iff_unique_homotopic, exact ⟨infer_instance, λ x y, ⟨unique_of_subsingleton ⟦path_connected_space.some_path x y⟧⟩⟩, end⟩ /-- Another version of `simply_connected_iff_paths_homotopic` -/ lemma simply_connected_iff_paths_homotopic' {Y : Type*} [topological_space Y] : simply_connected_space Y ↔ (path_connected_space Y) ∧ (∀ {x y : Y} (p₁ p₂ : path x y), path.homotopic p₁ p₂) := begin convert simply_connected_iff_paths_homotopic, simp [path.homotopic.quotient, setoid.eq_top_iff], refl, end
9064c3fb97968c157a02c29e63daaa9e129355ca
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/elab_meta1.lean
74eab02d9712b9be0cdf176ffa4a2b2e54c162f0
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
230
lean
meta definition f : nat → nat | n := if n / 2 = 0 then n + 1 else f (n / 2) + 1 meta definition g : nat × nat → nat | (0, b) := b | (a+1, b+1) := g (a/2 - 1, a + b) | (a+1, 0) := 2*a vm_eval f 200 vm_eval g (10, 20)
f6af8eb878c21738fda601b0698b1cfb4a2257ec
510e96af568b060ed5858226ad954c258549f143
/algebra/lattice/filter.lean
ccae2306fda6f6703191c392fbdf3ea8d03b4081
[]
no_license
Shamrock-Frost/library_dev
cb6d1739237d81e17720118f72ba0a6db8a5906b
0245c71e4931d3aceeacf0aea776454f6ee03c9c
refs/heads/master
1,609,481,034,595
1,500,165,215,000
1,500,165,347,000
97,350,162
0
0
null
1,500,164,969,000
1,500,164,969,000
null
UTF-8
Lean
false
false
66,108
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of filters on sets. -/ import .complete_lattice ...data.set .zorn open lattice set universes u v w x section applicative variables {f : Type u → Type v} [applicative f] {α β : Type u} lemma pure_seq_eq_map : ∀ {α β : Type u} (g : α → β) (x : f α), pure g <*> x = g <$> x := @applicative.pure_seq_eq_map f _ end applicative section monad variables {α β γ : Type u} {m : Type u → Type v} [monad m] theorem map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = (x >>= λa, f <$> g a) := by simp [monad.bind_assoc, (∘), (monad.bind_pure_comp_eq_map _ _ _).symm] theorem seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : (f <$> x) >>= g = (x >>= g ∘ f) := show bind (f <$> x) g = bind x (g ∘ f), by rw [←monad.bind_pure_comp_eq_map, monad.bind_assoc]; simp [monad.pure_bind] theorem seq_eq_bind_map {x : m α} {f : m (α → β)} : f <*> x = (f >>= (<$> x)) := (monad.bind_map_eq_seq m f x)^.symm theorem bind_assoc : ∀ {α β γ : Type u} (x : m α) (f : α → m β) (g : β → m γ), x >>= f >>= g = x >>= λ x, f x >>= g := @monad.bind_assoc m _ end monad section prod variables {α : Type u} {β : Type v} @[simp] -- copied from parser lemma prod.mk.eta : ∀{p : α × β}, (p.1, p.2) = p | (a, b) := rfl def prod.swap : (α×β) → (β×α) := λp, (p.2, p.1) @[simp] lemma prod.swap_swap : ∀x:α×β, prod.swap (prod.swap x) = x | ⟨a, b⟩ := rfl @[simp] lemma prod.fst_swap {p : α×β} : (prod.swap p).1 = p.2 := rfl @[simp] lemma prod.snd_swap {p : α×β} : (prod.swap p).2 = p.1 := rfl @[simp] lemma prod.swap_prod_mk {a : α} {b : β} : prod.swap (a, b) = (b, a) := rfl @[simp] lemma prod.swap_swap_eq : prod.swap ∘ prod.swap = @id (α × β) := funext $ prod.swap_swap end prod namespace lattice variables {α : Type u} {ι : Sort v} [complete_lattice α] lemma Inf_eq_finite_sets {s : set α} : Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) := le_antisymm (le_infi $ assume t, le_infi $ assume ⟨_, h⟩, Inf_le_Inf h) (le_Inf $ assume b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp) lemma Sup_le_iff {s : set α} {a : α} : Sup s ≤ a ↔ (∀x∈s, x ≤ a) := ⟨assume h x hx, le_trans (le_Sup hx) h, Sup_le⟩ end lattice instance : monad set := { monad . pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, map := λ(α β : Type u), set.image, pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp; exact ⟨assume ⟨b, ag, a, as, bf⟩, ⟨a, as, b, bf, ag⟩, assume ⟨a, as, b, bf, ag⟩, ⟨b, ag, a, as, bf⟩⟩, id_map := assume α, functor.id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm] } namespace set section variables {α β : Type u} @[simp] theorem bind_def (s : set α) (f : α → set β) : s >>= f = ⋃i∈s, f i := rfl theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := ⟨exists_mem_of_ne_empty, assume ⟨x, (hx : x ∈ s)⟩ h, by rw [h] at hx; assumption⟩ lemma fmap_eq_image {f : α → β} {s : set α} : f <$> s = f '' s := rfl lemma mem_seq_iff {f : set (α → β)} {s : set α} {b : β} : b ∈ (f <*> s) ↔ (∃(f' : α → β), ∃a ∈ s, f' ∈ f ∧ b = f' a) := begin simp [seq_eq_bind_map], apply exists_congr, intro f', exact ⟨assume ⟨hf', a, ha, h_eq⟩, ⟨a, h_eq^.symm, ha, hf'⟩, assume ⟨a, h_eq, ha, hf'⟩, ⟨hf', a, ha, h_eq^.symm⟩⟩ end end variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma mem_prod_eq {s : set α} {t : set β} {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl lemma prod_vimage_eq {s : set α} {t : set β} {f : γ → α} {g : δ → β} : set.prod (vimage f s) (vimage g t) = vimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl lemma prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ lemma prod_inter_prod {s₁ s₂ : set α} {t₁ t₂ : set β} : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) lemma monotone_prod [weak_order α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) := assume a b h, prod_mono (hf h) (hg h) lemma image_swap_prod {s : set α} {t : set β} : image (λp:β×α, (p.2, p.1)) (set.prod t s) = set.prod s t := set.ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod]; exact ⟨ assume ⟨b', a', h_a, h_b, h⟩, by rw [h_a, h_b] at h; assumption, assume ⟨ha, hb⟩, ⟨b, a, rfl, rfl, ⟨ha, hb⟩⟩⟩ lemma prod_image_image_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {s₁ : set α₁} {s₂ : set α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : set.prod (image m₁ s₁) (image m₂ s₂) = image (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (set.prod s₁ s₂) := set.ext $ assume ⟨b₁, b₂⟩, ⟨assume ⟨⟨a₁, ha₁, (eq₁ : m₁ a₁ = b₁)⟩, ⟨a₂, ha₂, (eq₂ : m₂ a₂ = b₂)⟩⟩, mem_image (show (a₁, a₂) ∈ set.prod s₁ s₂, from ⟨ha₁, ha₂⟩) (by simp [eq₁, eq₂]), assume ⟨⟨a₁, a₂⟩, ⟨ha₁, ha₂⟩, eq⟩, eq ▸ ⟨mem_image_of_mem m₁ ha₁, mem_image_of_mem m₂ ha₂⟩⟩ @[simp] lemma prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := set.ext $ assume ⟨a', b'⟩, by simp [set.prod] lemma prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := begin rw [ne_empty_iff_exists_mem, ne_empty_iff_exists_mem, ne_empty_iff_exists_mem, prod.exists], exact ⟨assume ⟨a, b, ha, hb⟩, ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, assume ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨a, b, ha, hb⟩⟩ end @[simp] lemma prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl lemma monotone_inter [weak_order β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) := assume a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h h₂⟩ @[simp] lemma vimage_set_of_eq {p : α → Prop} {f : β → α} : vimage f {a | p a} = {a | p (f a)} := rfl @[simp] lemma set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl lemma mem_image_iff_of_inverse (f : α → β) (g : β → α) {b : β} {s : set α} (h₁ : ∀a, g (f a) = a ) (h₂ : ∀b, f (g b) = b ) : b ∈ f '' s ↔ g b ∈ s := ⟨assume ⟨a, ha, fa_eq⟩, fa_eq ▸ (h₁ a)^.symm ▸ ha, assume h, ⟨g b, h, h₂ b⟩⟩ lemma image_eq_vimage_of_inverse (f : α → β) (g : β → α) (h₁ : ∀a, g (f a) = a ) (h₂ : ∀b, f (g b) = b ) : image f = vimage g := funext $ assume s, set.ext $ assume b, mem_image_iff_of_inverse f g h₁ h₂ lemma image_swap_eq_vimage_swap : image (@prod.swap α β) = vimage prod.swap := image_eq_vimage_of_inverse (@prod.swap α β) (@prod.swap β α) begin simp; intros; trivial end begin simp; intros; trivial end lemma monotone_set_of [weak_order α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h lemma diff_right_antimono {s t u : set α} (h : t ⊆ u) : s - u ⊆ s - t := assume x ⟨hs, hnx⟩, ⟨hs, assume hx, hnx $ h hx⟩ end set section variables {α : Type u} {ι : Sort v} lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {ι₂ : Sort x} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h lemma diff_neq_empty {s t : set α} : s - t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ suppose x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, bot_unique $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] lemma diff_empty {s : set α} : s - ∅ = s := set.ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ end @[simp] -- should be handled by implies_true_iff lemma implies_implies_true_iff {α : Sort u} {β : Sort v} : (α → β → true) ↔ true := ⟨assume _, trivial, assume _ _ _ , trivial⟩ @[simp] lemma not_not_mem_iff {α : Type u} {a : α} {s : set α} : ¬ (a ∉ s) ↔ a ∈ s := classical.not_not_iff _ @[simp] lemma singleton_neq_emptyset {α : Type u} {a : α} : {a} ≠ (∅ : set α) := assume h, have a ∉ ({a} : set α), by simp [h], this $ mem_singleton a lemma eq_of_sup_eq_inf_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (calc b ≤ (c ⊓ a) ⊔ b : le_sup_right ... = (c ⊔ b) ⊓ (a ⊔ b) : sup_inf_right ... = c ⊔ (c ⊓ a) : by rw [←h₁, sup_inf_left, ←h₂]; simp [sup_comm] ... = c : sup_inf_self) (calc c ≤ (b ⊓ a) ⊔ c : le_sup_right ... = (b ⊔ c) ⊓ (a ⊔ c) : sup_inf_right ... = b ⊔ (b ⊓ a) : by rw [h₁, sup_inf_left, h₂]; simp [sup_comm] ... = b : sup_inf_self) lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨suppose a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], suppose a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by rw [inf_comm]; exact inf_le_inf (le_refl _) this ... = ⊥ : h₂⟩ lemma compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := set.ext $ assume x, ⟨assume ⟨y, (hy : p y), (h_eq : -y = x)⟩, show p (- x), by rw [←h_eq, lattice.neg_neg]; assumption, assume h : p (-x), ⟨_, h, lattice.neg_neg⟩⟩ lemma neg_subset_neg_iff_subset {α : Type u} {x y : set α} : - y ⊆ - x ↔ x ⊆ y := @neg_le_neg_iff_le (set α) _ _ _ lemma sUnion_eq_Union {α : Type u} {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := set.ext $ by simp lemma not_or_iff_implies {a b : Prop} : (¬ a ∨ b) ↔ (a → b) := ⟨assume h ha, h.neg_resolve_left ha, classical.not_or_of_implies⟩ section order variables {α : Type u} (r : α → α → Prop) local infix `≼` : 50 := r def directed {ι : Sort v} (f : ι → α) := ∀x, ∀y, ∃z, f z ≼ f x ∧ f z ≼ f y def directed_on (s : set α) := ∀x ∈ s, ∀y ∈ s, ∃z ∈ s, z ≼ x ∧ z ≼ y lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊇) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp [directed_on]; exact assume a₁ ⟨b₁, fb₁⟩ a₂ ⟨b₂, fb₂⟩, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, xa₁, xa₂, z, xf⟩ def upwards (s : set α) := ∀{x y}, x ∈ s → x ≼ y → y ∈ s end order lemma directed_of_chain {α : Type u} {β : Type v} [weak_order β] {f : α → β} {c : set α} (h : @zorn.chain α (λa b, f b ≤ f a) c) : directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (suppose a = b, begin simp [this]; exact ⟨⟨b, hb⟩, le_refl _⟩ end) (suppose a ≠ b, have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this, or.elim this (suppose f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩) (suppose f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩)) structure filter (α : Type u) := (sets : set (set α)) (inhabited : ∃x, x ∈ sets) (upwards_sets : upwards (⊆) sets) (directed_sets : directed_on (⊆) sets) namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} lemma filter_eq : ∀{f g : filter α}, f^.sets = g^.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma univ_mem_sets' {f : filter α} {s : set α} (h : ∀ a, a ∈ s): s ∈ f^.sets := let ⟨x, x_in_s⟩ := f^.inhabited in f^.upwards_sets x_in_s (assume x _, h x) lemma univ_mem_sets {f : filter α} : univ ∈ f^.sets := univ_mem_sets' mem_univ lemma inter_mem_sets {f : filter α} {x y : set α} (hx : x ∈ f^.sets) (hy : y ∈ f^.sets) : x ∩ y ∈ f^.sets := let ⟨z, ⟨z_in_s, z_le_x, z_le_y⟩⟩ := f^.directed_sets _ hx _ hy in f^.upwards_sets z_in_s (subset_inter z_le_x z_le_y) lemma Inter_mem_sets {f : filter α} {s : β → set α} {is : set β} (hf : finite is) (hs : ∀i∈is, s i ∈ f^.sets) : (⋂i∈is, s i) ∈ f^.sets := begin /- equation compiler complains that this is requires well-founded recursion -/ induction hf with i is _ hf hi, { simp [univ_mem_sets] }, begin simp, apply inter_mem_sets, apply hs i, simp, exact (hi $ assume a ha, hs _ $ by simp [ha]) end end lemma exists_sets_subset_iff {f : filter α} {x : set α} : (∃y∈f^.sets, y ⊆ x) ↔ x ∈ f^.sets := ⟨assume ⟨y, hy, yx⟩, f^.upwards_sets hy yx, assume hx, ⟨x, hx, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f^.sets) := assume s t hst h, f^.upwards_sets h hst def principal (s : set α) : filter α := { filter . sets := {t | s ⊆ t}, inhabited := ⟨s, subset.refl _⟩, upwards_sets := assume x y hx hy, subset.trans hx hy, directed_sets := assume x hx y hy, ⟨s, subset.refl _, hx, hy⟩ } def join (f : filter (filter α)) : filter α := { filter . sets := {s | {t | s ∈ filter.sets t} ∈ f^.sets}, inhabited := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩, upwards_sets := assume x y hx xy, f^.upwards_sets hx $ assume a h, a^.upwards_sets h xy, directed_sets := assume x hx y hy, ⟨x ∩ y, f^.upwards_sets (inter_mem_sets hx hy) $ assume z ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂, inter_subset_left _ _, inter_subset_right _ _⟩ } def map (m : α → β) (f : filter α) : filter β := { filter . sets := vimage (vimage m) f^.sets, inhabited := ⟨univ, univ_mem_sets⟩, upwards_sets := assume s t hs st, f^.upwards_sets hs (assume x h, st h), directed_sets := assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, inter_subset_left _ _, inter_subset_right _ _⟩ } def vmap (m : α → β) (f : filter β) : filter α := { filter . sets := { s | ∃t∈f.sets, vimage m t ⊆ s }, inhabited := ⟨univ, univ, univ_mem_sets, by simp⟩, upwards_sets := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, directed_sets := assume a ⟨a', ha₁, ha₂⟩ b ⟨b', hb₁, hb₂⟩, ⟨vimage m (a' ∩ b'), ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, subset.refl _⟩, subset.trans (vimage_mono $ inter_subset_left _ _) ha₂, subset.trans (vimage_mono $ inter_subset_right _ _) hb₂⟩ } protected def sup (f g : filter α) : filter α := { filter . sets := f^.sets ∩ g^.sets, inhabited := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩, upwards_sets := assume x y hx xy, and.imp (assume h, f^.upwards_sets h xy) (assume h, g^.upwards_sets h xy) hx, directed_sets := assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y, ⟨inter_mem_sets hx₁ hy₁, inter_mem_sets hx₂ hy₂⟩, inter_subset_left _ _, inter_subset_right _ _⟩ } protected def inf (f g : filter α) := { filter . sets := {s | ∃ a ∈ f^.sets, ∃ b ∈ g^.sets, a ∩ b ⊆ s }, inhabited := ⟨univ, univ, univ_mem_sets, univ, univ_mem_sets, subset_univ _⟩, upwards_sets := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, directed_sets := assume x ⟨a₁, ha₁, b₁, hb₁, h₁⟩ y ⟨a₂, ha₂, b₂, hb₂, h₂⟩, ⟨x ∩ y, ⟨_, inter_mem_sets ha₁ ha₂, _, inter_mem_sets hb₁ hb₂, calc (a₁ ⊓ a₂) ⊓ (b₁ ⊓ b₂) = (a₁ ⊓ b₁) ⊓ (a₂ ⊓ b₂) : by ac_refl ... ≤ x ∩ y : inf_le_inf h₁ h₂ ⟩, inter_subset_left _ _, inter_subset_right _ _⟩ } def cofinite : filter α := { filter . sets := {s | finite (- s)}, inhabited := ⟨univ, by simp⟩, upwards_sets := assume s t, assume hs : finite (-s), assume st: s ⊆ t, finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, directed_sets := assume s, assume hs : finite (-s), assume t, assume ht : finite (-t), ⟨s ∩ t, by simp [compl_inter, finite_union, ht, hs], inter_subset_left _ _, inter_subset_right _ _⟩ } instance weak_order_filter : weak_order (filter α) := { weak_order . le := λf g, g^.sets ⊆ f^.sets, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } instance : has_Sup (filter α) := ⟨join ∘ principal⟩ instance inhabited' : _root_.inhabited (filter α) := ⟨principal ∅⟩ protected lemma le_Sup {s : set (filter α)} {f : filter α} : f ∈ s → f ≤ Sup s := assume f_in_s t' h, h f_in_s protected lemma Sup_le {s : set (filter α)} {f : filter α} : (∀g∈s, g ≤ f) → Sup s ≤ f := assume h a ha g hg, h g hg ha @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ (join f)^.sets = ({t | s ∈ filter.sets t} ∈ f^.sets) := rfl @[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t)^.sets = (t ⊆ s) := rfl @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f^.sets := show (∀{t}, s ⊆ t → t ∈ f^.sets) ↔ s ∈ f^.sets, from ⟨assume h, h (subset.refl s), assume hs t ht, f^.upwards_sets hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp lemma monotone_principal : monotone (principal : set α → filter α) := by simp [monotone, principal_mono]; exact assume a b h, h @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp [eq_iff_le_and_le]; refl instance complete_lattice_filter : complete_lattice (filter α) := { filter.weak_order_filter with sup := filter.sup, le_sup_left := assume a b, inter_subset_left _ _, le_sup_right := assume a b, inter_subset_right _ _, sup_le := assume a b c h₁ h₂, subset_inter h₁ h₂, inf := filter.inf, le_inf := assume f g h fg fh s ⟨a, ha, b, hb, h⟩, f^.upwards_sets (inter_mem_sets (fg ha) (fh hb)) h, inf_le_left := assume f g s h, ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩, inf_le_right := assume f g s h, ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩, top := principal univ, le_top := assume a, show a ≤ principal univ, by simp [univ_mem_sets], bot := principal ∅, bot_le := assume a, show a^.sets ⊆ {x | ∅ ⊆ x}, by simp; apply subset_univ, Sup := Sup, le_Sup := assume s f, filter.le_Sup, Sup_le := assume s f, filter.Sup_le, Inf := λs, Sup {x | ∀y∈s, x ≤ y}, le_Inf := assume s a h, filter.le_Sup h, Inf_le := assume s a ha, filter.Sup_le $ assume b h, h _ ha } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff_subset_vimage^.symm @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl instance monad_filter : monad filter := { monad . bind := λ(α β : Type u) f m, join (map m f), pure := λ(α : Type u) x, principal {x}, map := λ(α β : Type u), filter.map, id_map := assume α f, filter_eq $ rfl, pure_bind := assume α β a f, by simp [Sup_image], bind_assoc := assume α β γ f m₁ m₂, filter_eq $ rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp [join, map, vimage, principal] } @[simp] theorem pure_def (x : α) : pure x = principal {x} := rfl @[simp] theorem bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = join (map m f) := rfl instance : alternative filter := { filter.monad_filter with failure := λα, ⊥, orelse := λα x y, x ⊔ y } def at_top [weak_order α] : filter α := ⨅ a, principal {b | a ≤ b} def at_bot [weak_order α] : filter α := ⨅ a, principal {b | b ≤ a} /- lattice equations -/ lemma mem_inf_sets_of_left {f g : filter α} {s : set α} : s ∈ f.sets → s ∈ (f ⊓ g)^.sets := have f ⊓ g ≤ f, from inf_le_left, assume hs, this hs lemma mem_inf_sets_of_right {f g : filter α} {s : set α} : s ∈ g.sets → s ∈ (f ⊓ g)^.sets := have f ⊓ g ≤ g, from inf_le_right, assume hs, this hs @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α)^.sets := assume x, false.elim lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f^.sets ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, f.upwards_sets h (empty_subset s), suppose f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f^.sets) : ∃x, x ∈ s := have ∅ ∉ f^.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), exists_mem_of_ne_empty this lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ f.upwards_sets univ_mem_sets $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} : (∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ := by simp [(@empty_in_sets_eq_bot α f).symm]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets := have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in have s₁ ⊆ s, from assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩, f.upwards_sets hs₁ this @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ (f ⊔ g)^.sets = (s ∈ f^.sets ∧ s ∈ g^.sets) := by refl @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ (f ⊓ g)^.sets = (∃t₁∈f^.sets, ∃t₂∈g^.sets, t₁ ∩ t₂ ⊆ s) := by refl lemma infi_sets_eq {f : ι → filter α} (h : directed (≤) f) (ne : nonempty ι) : (infi f)^.sets = (⋃ i, (f i)^.sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i)^.sets), inhabited := ⟨univ, begin simp, exact ⟨i, univ_mem_sets⟩ end⟩, directed_sets := directed_on_Union (show directed (≤) f, from h) (assume i, (f i)^.directed_sets), upwards_sets := by simp [upwards]; exact assume x y ⟨j, xf⟩ xy, ⟨j, (f j)^.upwards_sets xf xy⟩ } in subset.antisymm (show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i)^.sets) i) (Union_subset $ assume i, infi_le f i) lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) : (⨅ i∈s, f i)^.sets = (⋃ i ∈ s, (f i)^.sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i)^.sets = (⨅ t : {t // t ∈ s}, (f t^.val))^.sets : by simp [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t^.val)^.sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t)^.sets) : by simp [supr_subtype]; refl lemma Inf_sets_eq_finite {s : set (filter α)} : (complete_lattice.Inf s)^.sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t)^.sets) := calc (Inf s)^.sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t)^.sets : by rw [lattice.Inf_eq_finite_sets] ... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t)^.sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩, Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩) ⟨∅, by simp⟩ lemma supr_sets_eq {f : ι → filter α} : (supr f)^.sets = (⋂i, (f i)^.sets) := set.ext $ assume s, show s ∈ (join (principal {a : filter α | ∃i : ι, a = f i}))^.sets ↔ s ∈ (⋂i, (f i)^.sets), begin rw [mem_join_sets], simp, exact ⟨assume h i, h (f i) ⟨_, rfl⟩, assume h x ⟨i, eq⟩, eq^.symm ▸ h i⟩ end @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] instance : bounded_distrib_lattice (filter α) := { filter.complete_lattice_filter with le_sup_inf := assume x y z s h, begin cases h with h₁ h₂, revert h₂, simp, exact assume ⟨t₁, ht₁, t₂, ht₂, hs⟩, ⟨s ∪ t₁, x^.upwards_sets h₁ $ subset_union_left _ _, y^.upwards_sets ht₁ $ subset_union_right _ _, s ∪ t₂, x^.upwards_sets h₁ $ subset_union_left _ _, z^.upwards_sets ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hs)⟩ end } private theorem infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) : (⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) := begin induction h with a s hn hs hi, { simp, exact infi_const ⊥ }, { rw [infi_insert], simp [hi, infi_or, sup_inf_left] } end /- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/ lemma binfi_sup_eq { f : filter α } {s : set (filter α)} : (⨅ g∈s, f ⊔ g) = f ⊔ complete_lattice.Inf s := le_antisymm begin intros t h, cases h with h₁ h₂, rw [Inf_sets_eq_finite] at h₂, simp at h₂, cases h₂ with s' hs', cases hs' with hs' hs'', cases hs'' with hs's ht', have ht : t ∈ (⨅ a ∈ s', f ⊔ a)^.sets, { rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' }, clear h₁ ht', revert ht t, change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a), apply infi_le_infi2 _, exact assume i, ⟨i, infi_le_infi2 $ assume h, ⟨hs's h, le_refl _⟩⟩ end (le_infi $ assume g, le_infi $ assume h, sup_le_sup (le_refl f) $ Inf_le h) lemma infi_sup_eq { f : filter α } {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp ... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq ... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, subset.refl _⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp [union_subset_iff] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _)^.symm lemma principal_univ : principal (univ : set α) = ⊤ := rfl lemma principal_empty : principal (∅ : set α) = ⊥ := rfl @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], assume h, by simp [*, principal_empty]⟩ @[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets := by simp; exact id /- map equations -/ @[simp] lemma mem_map {f : filter α} {s : set β} {m : α → β} : (s ∈ (map m f)^.sets) = ({x | m x ∈ s} ∈ f^.sets) := rfl lemma image_mem_map {f : filter α} {m : α → β} {s : set α} (hs : s ∈ f.sets): m '' s ∈ (map m f).sets := f.upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩ @[simp] lemma map_id {f : filter α} : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose {γ : Type w} {f : α → β} {g : β → γ} : filter.map g ∘ filter.map f = filter.map (g ∘ f) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_sup {f g : filter α} {m : α → β} : map m (f ⊔ g) = map m f ⊔ map m g := filter_eq $ set.ext $ assume x, by simp @[simp] lemma supr_map {ι : Sort w} {f : ι → filter α} {m : α → β} : (⨆x, map m (f x)) = map m (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, map] @[simp] lemma map_bot {m : α → β} : map m ⊥ = ⊥ := filter_eq $ set.ext $ assume x, by simp @[simp] lemma map_eq_bot_iff {f : filter α} {m : α → β} : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp [*]⟩ lemma map_mono {f g : filter α} {m : α → β} (h : f ≤ g) : map m f ≤ map m g := le_of_sup_eq $ calc map m f ⊔ map m g = map m (f ⊔ g) : map_sup ... = map m g : congr_arg (map m) $ sup_of_le_right h lemma monotone_map {m : α → β} : monotone (map m : filter α → filter β) := assume a b h, map_mono h -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≤) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : vimage m s ∈ (infi f).sets), have ∃i, vimage m s ∈ (f i).sets, by simp [infi_sets_eq hf hι] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp; assumption, by simp at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {s : set ι} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) : map m (⨅i∈s, f i) = (⨅i∈s, map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i∈s, f i) = map m (⨅i:{i // i ∈ s}, f i.val) : by simp [infi_subtype] ... = (⨅i:{i // i ∈ s}, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i∈s, map m (f i)) : by simp [infi_subtype] /- bind equations -/ lemma mem_bind_sets {β : Type u} {s : set β} {f : filter α} {m : α → filter β} : s ∈ (f >>= m)^.sets ↔ (∃t ∈ f^.sets, ∀x ∈ t, s ∈ (m x)^.sets) := calc s ∈ (f >>= m)^.sets ↔ {a | s ∈ (m a)^.sets} ∈ f^.sets : by simp ... ↔ (∃t ∈ f^.sets, t ⊆ {a | s ∈ (m a)^.sets}) : exists_sets_subset_iff^.symm ... ↔ (∃t ∈ f^.sets, ∀x ∈ t, s ∈ (m x)^.sets) : iff.refl _ lemma bind_mono {β : Type u} {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f^.sets) : f >>= g ≤ f >>= h := assume x h₂, f^.upwards_sets (inter_mem_sets h₁ h₂) $ assume s ⟨gh', h'⟩, gh' h' lemma bind_sup {β : Type u} {f g : filter α} {h : α → filter β} : (f ⊔ g) >>= h = (f >>= h) ⊔ (g >>= h) := by simp lemma bind_mono2 {β : Type u} {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : f >>= h ≤ g >>= h := assume s h', h₁ h' lemma principal_bind {β : Type u} {s : set α} {f : α → filter β} : (principal s >>= f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp [Sup_image] lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ := le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ assume f, map_mono hg) @[simp] lemma fmap_principal {β : Type u} {s : set α} {f : α → β} : f <$> principal s = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff_subset_vimage^.symm lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α)^.sets ↔ a ∈ s := show s ∈ (principal {a})^.sets ↔ a ∈ s, by simp lemma infi_neq_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≤) f) (hb : ∀i, f i ≠ ⊥): (infi f) ≠ ⊥ := let ⟨x⟩ := hn in assume h, have he: ∅ ∈ (infi f)^.sets, from h.symm ▸ mem_bot_sets, classical.by_cases (suppose nonempty ι, have ∃i, ∅ ∈ (f i).sets, by rw [infi_sets_eq hd this] at he; simp at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i)^.upwards_sets hi $ empty_subset _) (suppose ¬ nonempty ι, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ this ⟨i⟩) end, this $ mem_univ x) lemma infi_neq_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≤) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _, infi_neq_bot_of_directed hn hd⟩ @[simp] lemma return_neq_bot {α : Type u} {a : α} : return a ≠ (⊥ : filter α) := by simp [return] section vmap variables {f f₁ f₂ : filter β} {m : α → β} lemma mem_vmap_of_mem {s : set β} (h : s ∈ f.sets) : vimage m s ∈ (vmap m f).sets := ⟨s, h, subset.refl _⟩ lemma vmap_mono (h : f₁ ≤ f₂) : vmap m f₁ ≤ vmap m f₂ := assume s ⟨t, ht, h_sub⟩, ⟨t, h ht, h_sub⟩ lemma monotone_vmap : monotone (vmap m : filter β → filter α) := assume a b h, vmap_mono h @[simp] lemma vmap_principal {t : set β} : vmap m (principal t) = principal (vimage m t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : vimage m u ⊆ s)⟩, subset.trans (vimage_mono hu) b, suppose vimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma vimage_mem_vmap {f : filter β} {m : α → β} {s : set β} (hs : s ∈ f.sets): vimage m s ∈ (vmap m f).sets := ⟨s, hs, subset.refl _⟩ lemma le_map_vmap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) : f ≤ map m (vmap m f) := assume s ⟨t, ht, (sub : ∀x, m x ∈ t → m x ∈ s)⟩, f.upwards_sets ht $ assume x, let ⟨y, (hy : m y = x)⟩ := hm x in hy ▸ sub y lemma vmap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : vmap m (map m f) = f := have ∀s, vimage m (image m s) = s, from assume s, vimage_image_eq h, le_antisymm (assume s hs, ⟨ image m s, f.upwards_sets hs $ by simp [this, subset.refl], by simp [this, subset.refl]⟩) (assume s ⟨t, (h₁ : vimage m t ∈ f.sets), (h₂ : vimage m t ⊆ s)⟩, f.upwards_sets h₁ h₂) lemma vmap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈f.sets, ∃a, m a ∈ t) : vmap m f ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ vimage m t)⟩ := hm t ht in neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s lemma vmap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : vmap m f ≠ ⊥ := vmap_neq_bot $ assume t ht, let ⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht, ⟨a, (ha : m a = b)⟩ := hm b in ⟨a, ha.symm ▸ hx⟩ lemma map_vmap_le {f : filter β} {m : α → β} : map m (vmap m f) ≤ f := assume s hs, ⟨s, hs, subset.refl _⟩ lemma le_vmap_map {f : filter α} {m : α → β} : f ≤ vmap m (map m f) := assume s ⟨t, ht, h_eq⟩, f.upwards_sets ht h_eq lemma vmap_vmap_comp {f : filter α} {m : γ → β} {n : β → α} : vmap m (vmap n f) = vmap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : vimage (n ∘ m) b ⊆ c)⟩, ⟨vimage n b, vimage_mem_vmap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : vimage n a ⊆ b)⟩, (h₂ : vimage m b ⊆ c)⟩, ⟨a, ha, show vimage m (vimage n a) ⊆ c, from subset.trans (vimage_mono h₁) h₂⟩) lemma le_vmap_iff_map_le {f : filter α} {g : filter β} {m : α → β} : f ≤ vmap m g ↔ map m f ≤ g := ⟨assume h, le_trans (map_mono h) map_vmap_le, assume h, le_trans le_vmap_map (vmap_mono h)⟩ end vmap section lift protected def lift (f : filter α) (g : set α → filter β) := (⨅s ∈ f^.sets, g s) section variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} lemma lift_sets_eq (hg : monotone g) : (f^.lift g)^.sets = (⋃t∈f^.sets, (g t)^.sets) := infi_sets_eq' (assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩) ⟨univ, univ_mem_sets⟩ lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f^.sets) (hs : s ∈ (g t)^.sets) : s ∈ (f^.lift g)^.sets := le_principal_iff.mp $ show f^.lift g ≤ principal s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma mem_lift_iff (hg : monotone g) {s : set β} : s ∈ (f^.lift g)^.sets ↔ (∃t∈f^.sets, s ∈ (g t)^.sets) := by rw [lift_sets_eq hg]; simp lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁^.lift g₁ ≤ f₂^.lift g₂ := infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s∈f^.sets, g₁ s ≤ g₂ s) : f^.lift g₁ ≤ f^.lift g₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f^.lift g) = f^.lift (map m ∘ g) := have monotone (map m ∘ g), from monotone_comp hg monotone_map, filter_eq $ set.ext $ by simp [mem_lift_iff, hg, @mem_lift_iff _ _ f _ this] lemma vmap_lift_eq {m : γ → β} (hg : monotone g) : vmap m (f^.lift g) = f^.lift (vmap m ∘ g) := have monotone (vmap m ∘ g), from monotone_comp hg monotone_vmap, filter_eq $ set.ext $ begin simp [vmap, mem_lift_iff, hg, @mem_lift_iff _ _ f _ this], simp [vmap, function.comp], exact assume s, ⟨assume ⟨t₁, hs, t₂, ht, ht₁⟩, ⟨t₂, ht, t₁, hs, ht₁⟩, assume ⟨t₂, ht, t₁, hs, ht₁⟩, ⟨t₁, hs, t₂, ht, ht₁⟩⟩ end lemma vmap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (vmap m f)^.lift g = f^.lift (g ∘ vimage m) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, infi_le_of_le (vimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩) (le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : vimage m s' ⊆ s)⟩, infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub) lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f)^.lift g = f^.lift (g ∘ image m) := le_antisymm (infi_le_infi2 $ assume s, ⟨image m s, infi_le_infi2 $ assume hs, ⟨ f^.upwards_sets hs $ assume a h, mem_image_of_mem _ h, le_refl _⟩⟩) (infi_le_infi2 $ assume t, ⟨vimage m t, infi_le_infi2 $ assume ht, ⟨ht, hg $ assume x, assume h : x ∈ m '' vimage m t, let ⟨y, hy, h_eq⟩ := h in show x ∈ t, from h_eq ▸ hy⟩⟩) lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f^.lift (λs, g^.lift (h s)) = g^.lift (λt, f^.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f^.lift g)^.lift h = f^.lift (λs, (g s)^.lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_iff hg)^.mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_iff hg)^.mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f^.lift (λs, f^.lift (g s)) ≤ f^.lift (λs, g s s) := le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)): f^.lift (λs, f^.lift (g s)) = f^.lift (λs, g s s) := le_antisymm lift_lift_same_le_lift (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le (s ∩ t) $ infi_le_of_le (inter_mem_sets hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _)) lemma lift_principal {s : set α} (hg : monotone g) : (principal s)^.lift g = g s := le_antisymm (infi_le_of_le s $ infi_le _ $ subset.refl _) (le_infi $ assume t, le_infi $ assume hi, hg hi) lemma monotone_lift [weak_order γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c)^.lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_neq_bot_iff (hm : monotone g) : (f^.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) := classical.by_cases (assume hn : nonempty β, calc f^.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f^.sets}, g s.val) ≠ ⊥ : by simp [filter.lift, infi_subtype] ... ↔ (∀s:{ s // s ∈ f^.sets}, g s.val ≠ ⊥) : infi_neq_bot_iff_of_directed hn (assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩, hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩) ... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩) (assume hn : ¬ nonempty β, have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn, have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn, calc (f.lift g ≠ ⊥) ↔ false : by simp [h₁] ... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩ ... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂]) end section protected def lift' (f : filter α) (h : set α → set β) := f^.lift (principal ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} lemma mem_lift' {t : set α} (ht : t ∈ f^.sets) : h t ∈ (f^.lift' h)^.sets := le_principal_iff.mp $ show f^.lift' h ≤ principal (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_refl _ lemma mem_lift'_iff (hh : monotone h) {s : set β} : s ∈ (f^.lift' h)^.sets ↔ (∃t∈f^.sets, h t ⊆ s) := have monotone (principal ∘ h), from assume a b h, principal_mono.mpr $ hh h, by simp [filter.lift', @mem_lift_iff α β f _ this] lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁^.lift' h₁ ≤ f₂^.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f^.sets, h₁ s ⊆ h₂ s) : f^.lift' h₁ ≤ f^.lift' h₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f^.sets, h₁ s = h₂ s) : f^.lift' h₁ = f^.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f^.lift' h) = f^.lift' (image m ∘ h) := calc map m (f^.lift' h) = f^.lift (map m ∘ principal ∘ h) : map_lift_eq $ monotone_comp hh monotone_principal ... = f^.lift' (image m ∘ h) : by simp [function.comp, filter.lift'] lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f)^.lift' g = f^.lift' (g ∘ image m) := map_lift_eq2 $ monotone_comp hg monotone_principal lemma vmap_lift'_eq {m : γ → β} (hh : monotone h) : vmap m (f^.lift' h) = f^.lift' (vimage m ∘ h) := calc vmap m (f^.lift' h) = f^.lift (vmap m ∘ principal ∘ h) : vmap_lift_eq $ monotone_comp hh monotone_principal ... = f^.lift' (vimage m ∘ h) : by simp [function.comp, filter.lift'] lemma vmap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (vmap m f)^.lift' g = f^.lift' (g ∘ vimage m) := vmap_lift_eq2 $ monotone_comp hg monotone_principal lemma lift'_principal {s : set α} (hh : monotone h) : (principal s)^.lift' h = principal (h s) := lift_principal $ monotone_comp hh monotone_principal lemma principal_le_lift' {t : set β} (hh : ∀s∈f^.sets, t ⊆ h s) : principal t ≤ f^.lift' h := le_infi $ assume s, le_infi $ assume hs, principal_mono^.mpr (hh s hs) lemma monotone_lift' [weak_order γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c)^.lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f^.lift' g)^.lift h = f^.lift (λs, h (g s)) := calc (f^.lift' g)^.lift h = f^.lift (λs, (principal (g s))^.lift h) : lift_assoc (monotone_comp hg monotone_principal) ... = f^.lift (λs, h (g s)) : by simp [lift_principal, hh] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f^.lift' g)^.lift' h = f^.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_comp hh monotone_principal) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f^.lift g)^.lift' h = f^.lift (λs, (g s)^.lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f^.lift (λs, f^.lift' (g s)) ≤ f^.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)): f^.lift (λs, f^.lift' (g s)) = f^.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal) (assume t, monotone_comp (hg₂ t) monotone_principal) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f^.lift' h ⊓ principal s = f^.lift' (λt, h t ∩ s) := le_antisymm (le_infi $ assume t, le_infi $ assume ht, calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s : inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _) ... = _ : by simp) (le_inf (le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _) (infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; exact inter_subset_left _ _)) lemma lift'_neq_bot_iff (hh : monotone h) : (f^.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) := calc (f^.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) : lift_neq_bot_iff (monotone_comp hh monotone_principal) ... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp [principal_eq_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := le_antisymm (assume s hs, mem_lift' hs) (le_infi $ assume s, le_infi $ assume hs, by simp [hs]) lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} (h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, by simp [h_le]; exact h_le s hs end end lift lemma vmap_eq_lift' {f : filter β} {m : α → β} : vmap m f = f.lift' (vimage m) := filter_eq $ set.ext $ by simp [mem_lift'_iff, monotone_vimage, vmap] /- product filter -/ /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x <- seq, y <- top, return (x, y)} hence: s ∈ F <-> ∃n, [n..∞] × univ ⊆ s G := do {y <- top, x <- seq, return (x, y)} hence: s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ section prod protected def prod (f : filter α) (g : filter β) : filter (α × β) := f^.lift $ λs, g^.lift' $ λt, set.prod s t lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f^.sets) (ht : t ∈ g^.sets) : set.prod s t ∈ (filter.prod f g)^.sets := le_principal_iff^.mp $ show filter.prod f g ≤ principal (set.prod s t), from infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ ht lemma prod_same_eq {f : filter α} : filter.prod f f = f^.lift' (λt, set.prod t t) := lift_lift'_same_eq_lift' (assume s, set.monotone_prod monotone_const monotone_id) (assume t, set.monotone_prod monotone_id monotone_const) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ (filter.prod f g)^.sets ↔ (∃t₁∈f^.sets, ∃t₂∈g^.sets, set.prod t₁ t₂ ⊆ s) := begin delta filter.prod, rw [mem_lift_iff], apply exists_congr, intro t₁, apply exists_congr, intro ht₁, rw [mem_lift'_iff], exact set.monotone_prod monotone_const monotone_id, exact (monotone_lift' monotone_const $ monotone_lam $ assume b, set.monotone_prod monotone_id monotone_const) end lemma mem_prod_same_iff {s : set (α×α)} {f : filter α} : s ∈ (filter.prod f f)^.sets ↔ (∃t∈f^.sets, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_iff]; exact set.monotone_prod monotone_id monotone_id lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ := lift_mono hf $ assume s, lift'_mono hg $ le_refl _ lemma prod_comm {f : filter α} {g : filter β} : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) := eq.symm $ calc map (λp:β×α, (p.2, p.1)) (filter.prod g f) = (g^.lift $ λt, map (λp:β×α, (p.2, p.1)) (f^.lift' $ λs, set.prod t s)) : map_lift_eq $ assume a b h, lift'_mono (le_refl f) (assume t, set.prod_mono h (subset.refl t)) ... = (g^.lift $ λt, f^.lift' $ λs, image (λp:β×α, (p.2, p.1)) (set.prod t s)) : congr_arg (filter.lift g) $ funext $ assume s, map_lift'_eq $ assume a b h, set.prod_mono (subset.refl s) h ... = (g^.lift $ λt, f^.lift' $ λs, set.prod s t) : by simp [set.image_swap_prod] ... = filter.prod f g : lift_comm lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) := begin delta filter.prod, rw [lift_assoc], apply congr_arg, apply funext, intro x, rw [lift_comm], apply congr_arg, apply funext, intro y, rw [lift'_lift_assoc], exact hg₂, exact hg₁ end lemma prod_lift'_lift' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) := begin delta filter.prod, rw [lift_lift'_assoc], apply congr_arg, apply funext, intro x, rw [lift'_lift'_assoc], exact hg₂, exact set.monotone_prod monotone_const monotone_id, exact hg₁, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, set.monotone_prod monotone_id monotone_const) end lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := begin simp [filter.prod], rw [map_lift_eq], tactic.swap, exact (monotone_lift' monotone_const $ monotone_lam $ assume t, set.monotone_prod monotone_id monotone_const), rw [map_lift_eq2], tactic.swap, exact (monotone_lift' monotone_const $ monotone_lam $ assume t, set.monotone_prod monotone_id monotone_const), apply congr_arg, apply funext, intro t, dsimp [(∘)], rw [map_lift'_eq], tactic.swap, exact set.monotone_prod monotone_const monotone_id, rw [map_lift'_eq2], tactic.swap, exact set.monotone_prod monotone_const monotone_id, apply congr_arg, apply funext, intro t, exact set.prod_image_image_eq end lemma prod_vmap_vmap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : filter.prod (vmap m₁ f₁) (vmap m₂ f₂) = vmap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := have ∀s t, set.prod (vimage m₁ s) (vimage m₂ t) = vimage (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (set.prod s t), from assume s t, rfl, begin rw [vmap_eq_lift', vmap_eq_lift', prod_lift'_lift'], simp [this, filter.prod], rw [vmap_lift_eq], tactic.swap, exact (monotone_lift' monotone_const $ monotone_lam $ assume t, set.monotone_prod monotone_id monotone_const), apply congr_arg, apply funext, intro t', dsimp [function.comp], rw [vmap_lift'_eq], exact set.monotone_prod monotone_const monotone_id, exact monotone_vimage, exact monotone_vimage end lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, begin revert s hs t ht, simp, exact assume s ⟨s₁, hs₁, s₂, hs₂, hs⟩ t ⟨t₁, ht₁, t₂, ht₂, ht⟩, ⟨set.prod s₁ t₁, prod_mem_prod hs₁ ht₁, set.prod s₂ t₂, prod_mem_prod hs₂ ht₂, by rw [set.prod_inter_prod]; exact set.prod_mono hs ht⟩ end) (le_inf (prod_mono inf_le_left inf_le_left) (prod_mono inf_le_right inf_le_right)) lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) : begin delta filter.prod, rw [lift_neq_bot_iff], exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const) end ... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) : begin apply forall_congr, intro s, apply forall_congr, intro hs, rw [lift'_neq_bot_iff], apply forall_congr, intro t, apply forall_congr, intro ht, rw [set.prod_neq_empty_iff], exact set.monotone_prod monotone_const monotone_id end ... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) : ⟨assume h, ⟨assume s hs, (h s hs univ univ_mem_sets).left, assume t ht, (h univ univ_mem_sets t ht).right⟩, assume ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩ ... ↔ _ : by simp [forall_sets_neq_empty_iff_neq_bot] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := begin delta filter.prod, rw [lift_principal, lift'_principal], exact set.monotone_prod monotone_const monotone_id, exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const) end end prod lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets := show (⨅i, f i) ≤ f i, from infi_le _ _ @[simp] lemma mem_top_sets_iff {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ := ⟨assume h, top_unique $ h, assume h, h.symm ▸ univ_mem_sets⟩ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin have hs' : s ∈ (complete_lattice.Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs, rw [Inf_sets_eq_finite] at hs', simp at hs', cases hs' with is hs, cases hs with fin_is hs, cases hs with hs his, induction fin_is generalizing s, case finite.empty hs' s hs' hs { simp at hs, subst hs, assumption }, case finite.insert fi is fi_ne_is fin_is ih fi_sub s hs' hs { simp at hs, cases hs with s₁ hs, cases hs with hs₁ hs, cases hs with s₂ hs, cases hs with hs hs₂, have hi : ∃i, fi = f i := fi_sub (mem_insert _ _), cases hi with i hi, exact have hs₁ : s₁ ∈ (f i).sets, from hi ▸ hs₁, have hs₂ : p s₂, from have his : is ⊆ {x | ∃i, x = f i}, from assume i hi, fi_sub $ mem_insert_of_mem _ hi, have infi f ≤ Inf is, from Inf_le_Inf his, ih his (this hs₂) hs₂, show p s, from upw hs $ ins hs₁ hs₂ } end lemma lift_infi {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f)^.lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, have g_mono : monotone g, from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h, have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t, from assume t ht, infi_sets_induct ht (let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets) (assume i s₁ s₂ hs₁ hs₂, @hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂) (assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁), by rw [lift_sets_eq g_mono]; simp; exact assume ⟨t, hs, ht⟩, this t ht hs) lemma lift_infi' {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hf : directed (≤) f) (hg : monotone g) : (infi f)^.lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, begin rw [lift_sets_eq hg], simp [infi_sets_eq hf hι], exact assume ⟨t, hs, i, ht⟩, mem_infi_sets i $ mem_lift ht hs end) lemma lift'_infi {f : ι → filter α} {g : set α → set β} (hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f)^.lift' g = (⨅i, (f i).lift' g) := lift_infi hι $ by simp; apply assume s t, hg lemma map_eq_vmap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = vmap n f := le_antisymm (assume b ⟨a, ha, (h : vimage n a ⊆ b)⟩, f.upwards_sets ha $ calc a = vimage (n ∘ m) a : by simp [h₂, vimage_id] ... ⊆ vimage m b : vimage_mono h) (assume b (hb : vimage m b ∈ f.sets), ⟨vimage m b, hb, show vimage (m ∘ n) b ⊆ b, by simp [h₁]; apply subset.refl⟩) lemma map_swap_vmap_swap_eq {f : filter (α × β)} : prod.swap <$> f = vmap prod.swap f := map_eq_vmap_of_inverse prod.swap_swap_eq prod.swap_swap_eq /- towards -/ def towards (f : α → β) (l₁ : filter α) (l₂ : filter β) := filter.map f l₁ ≤ l₂ /- ultrafilter -/ section ultrafilter open classical zorn local attribute [instance] prop_decidable variables {f g : filter α} def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_pure {a : α} : ultrafilter (pure a) := ⟨return_neq_bot, assume g hg ha, have {a} ∈ g.sets, by simp at ha; assumption, show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $ begin simp [classical.not_forall_iff_exists_not, classical.not_implies_iff_and_not], exact assume ⟨s, hna, hs⟩, have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs, have ∅ ∈ g.sets, from g.upwards_sets this $ assume x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end, have g = ⊥, from empty_in_sets_eq_bot.mp this, hg this end⟩ lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_neq_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) : s ∈ f.sets ∨ - s ∈ f.sets := or_of_not_implies $ suppose - s ∉ f.sets, have f ≤ principal s, from le_of_ultrafilter hf $ assume h, this $ mem_sets_of_neq_bot $ by simp [*], by simp at this; assumption lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : ultrafilter f) (h : s ∪ t ∈ f.sets) : s ∈ f.sets ∨ t ∈ f.sets := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (suppose -s ∈ f.sets, f.upwards_sets (inter_mem_sets this h) $ assume x ⟨hnx, hx⟩, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets := begin induction hs, case finite.empty { simp [empty_in_sets_eq_bot, hf.left] }, case finite.insert t s' ht' hs' ih { simp, exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (suppose t ∈ f.sets, ⟨t, this, or.inl rfl⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, ht, or.inr hts'⟩) } end lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets := have his : finite (image s is), from finite_image his, have h : (⋃₀ image s is) ∈ f.sets, from by simp [sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) : ultrafilter f := ⟨hf, assume g hg g_le s hs, (h s).elim id $ suppose - s ∈ f.sets, have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this), by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) := ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $ assume s, show vimage m s ∈ f.sets ∨ - vimage m s ∈ f.sets, from mem_or_compl_mem_of_ultrafilter h (vimage m s) noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else epsilon (λu, u ≤ f ∧ ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) := begin have h' := epsilon_spec (exists_ultrafilter h), simp [ultrafilter_of, dif_neg, h], simp at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le end ultrafilter end filter
bccc884bc4db10b2c09646a112f21d7177c30db7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/calculus/inverse.lean
0d145396471edab45005490a410249a9d6c841d6
[ "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
37,367
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth, Sébastien Gouëzel -/ import analysis.calculus.cont_diff import tactic.ring_exp import analysis.normed_space.banach import topology.local_homeomorph /-! # Inverse function theorem In this file we prove the inverse function theorem. It says that if a map `f : E → F` has an invertible strict derivative `f'` at `a`, then it is locally invertible, and the inverse function has derivative `f' ⁻¹`. We define `has_strict_deriv_at.to_local_homeomorph` that repacks a function `f` with a `hf : has_strict_fderiv_at f f' a`, `f' : E ≃L[𝕜] F`, into a `local_homeomorph`. The `to_fun` of this `local_homeomorph` is `defeq` to `f`, so one can apply theorems about `local_homeomorph` to `hf.to_local_homeomorph f`, and get statements about `f`. Then we define `has_strict_fderiv_at.local_inverse` to be the `inv_fun` of this `local_homeomorph`, and prove two versions of the inverse function theorem: * `has_strict_fderiv_at.to_local_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense (`hf`), then `hf.local_inverse f f' a` has derivative `f'.symm` at `f a` in the strict sense; * `has_strict_fderiv_at.to_local_left_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense and `g` is locally left inverse to `f` near `a`, then `g` has derivative `f'.symm` at `f a` in the strict sense. In the one-dimensional case we reformulate these theorems in terms of `has_strict_deriv_at` and `f'⁻¹`. We also reformulate the theorems in terms of `cont_diff`, to give that `C^k` (respectively, smooth) inputs give `C^k` (smooth) inverses. These versions require that continuous differentiability implies strict differentiability; this is false over a general field, true over `ℝ` or `ℂ` and implemented here assuming `is_R_or_C 𝕂`. Some related theorems, providing the derivative and higher regularity assuming that we already know the inverse function, are formulated in `fderiv.lean`, `deriv.lean`, and `cont_diff.lean`. ## Notations In the section about `approximates_linear_on` we introduce some `local notation` to make formulas shorter: * by `N` we denote `∥f'⁻¹∥`; * by `g` we denote the auxiliary contracting map `x ↦ x + f'.symm (y - f x)` used to prove that `{x | f x = y}` is nonempty. ## Tags derivative, strictly differentiable, continuously differentiable, smooth, inverse function -/ open function set filter metric open_locale topological_space classical nnreal noncomputable theory variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_add_comm_group G'] [normed_space 𝕜 G'] variables {ε : ℝ} open asymptotics filter metric set open continuous_linear_map (id) /-! ### Non-linear maps close to affine maps In this section we study a map `f` such that `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` on an open set `s`, where `f' : E →L[𝕜] F` is a continuous linear map and `c` is suitably small. Maps of this type behave like `f a + f' (x - a)` near each `a ∈ s`. When `f'` is onto, we show that `f` is locally onto. When `f'` is a continuous linear equiv, we show that `f` is a homeomorphism between `s` and `f '' s`. More precisely, we define `approximates_linear_on.to_local_homeomorph` to be a `local_homeomorph` with `to_fun = f`, `source = s`, and `target = f '' s`. Maps of this type naturally appear in the proof of the inverse function theorem (see next section), and `approximates_linear_on.to_local_homeomorph` will imply that the locally inverse function exists. We define this auxiliary notion to split the proof of the inverse function theorem into small lemmas. This approach makes it possible - to prove a lower estimate on the size of the domain of the inverse function; - to reuse parts of the proofs in the case if a function is not strictly differentiable. E.g., for a function `f : E × F → G` with estimates on `f x y₁ - f x y₂` but not on `f x₁ y - f x₂ y`. -/ /-- We say that `f` approximates a continuous linear map `f'` on `s` with constant `c`, if `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` whenever `x, y ∈ s`. This predicate is defined to facilitate the splitting of the inverse function theorem into small lemmas. Some of these lemmas can be useful, e.g., to prove that the inverse function is defined on a specific set. -/ def approximates_linear_on (f : E → F) (f' : E →L[𝕜] F) (s : set E) (c : ℝ≥0) : Prop := ∀ (x ∈ s) (y ∈ s), ∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥ @[simp] lemma approximates_linear_on_empty (f : E → F) (f' : E →L[𝕜] F) (c : ℝ≥0) : approximates_linear_on f f' ∅ c := by simp [approximates_linear_on] namespace approximates_linear_on variables [cs : complete_space E] {f : E → F} /-! First we prove some properties of a function that `approximates_linear_on` a (not necessarily invertible) continuous linear map. -/ section variables {f' : E →L[𝕜] F} {s t : set E} {c c' : ℝ≥0} theorem mono_num (hc : c ≤ c') (hf : approximates_linear_on f f' s c) : approximates_linear_on f f' s c' := λ x hx y hy, le_trans (hf x hx y hy) (mul_le_mul_of_nonneg_right hc $ norm_nonneg _) theorem mono_set (hst : s ⊆ t) (hf : approximates_linear_on f f' t c) : approximates_linear_on f f' s c := λ x hx y hy, hf x (hst hx) y (hst hy) lemma approximates_linear_on_iff_lipschitz_on_with {f : E → F} {f' : E →L[𝕜] F} {s : set E} {c : ℝ≥0} : approximates_linear_on f f' s c ↔ lipschitz_on_with c (f - f') s := begin have : ∀ x y, f x - f y - f' (x - y) = (f - f') x - (f - f') y, { assume x y, simp only [map_sub, pi.sub_apply], abel }, simp only [this, lipschitz_on_with_iff_norm_sub_le, approximates_linear_on], end alias approximates_linear_on_iff_lipschitz_on_with ↔ lipschitz_on_with _root_.lipschitz_on_with.approximates_linear_on lemma lipschitz_sub (hf : approximates_linear_on f f' s c) : lipschitz_with c (λ x : s, f x - f' x) := begin refine lipschitz_with.of_dist_le_mul (λ x y, _), rw [dist_eq_norm, subtype.dist_eq, dist_eq_norm], convert hf x x.2 y y.2 using 2, rw [f'.map_sub], abel end protected lemma lipschitz (hf : approximates_linear_on f f' s c) : lipschitz_with (∥f'∥₊ + c) (s.restrict f) := by simpa only [restrict_apply, add_sub_cancel'_right] using (f'.lipschitz.restrict s).add hf.lipschitz_sub protected lemma continuous (hf : approximates_linear_on f f' s c) : continuous (s.restrict f) := hf.lipschitz.continuous protected lemma continuous_on (hf : approximates_linear_on f f' s c) : continuous_on f s := continuous_on_iff_continuous_restrict.2 hf.continuous end section locally_onto /-! We prove that a function which is linearly approximated by a continuous linear map with a nonlinear right inverse is locally onto. This will apply to the case where the approximating map is a linear equivalence, for the local inverse theorem, but also whenever the approximating map is onto, by Banach's open mapping theorem. -/ include cs variables {s : set E} {c : ℝ≥0} {f' : E →L[𝕜] F} /-- If a function is linearly approximated by a continuous linear map with a (possibly nonlinear) right inverse, then it is locally onto: a ball of an explicit radius is included in the image of the map. -/ theorem surj_on_closed_ball_of_nonlinear_right_inverse (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {ε : ℝ} {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : surj_on f (closed_ball b ε) (closed_ball (f b) (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε)) := begin assume y hy, cases le_or_lt (f'symm.nnnorm : ℝ) ⁻¹ c with hc hc, { refine ⟨b, by simp [ε0], _⟩, have : dist y (f b) ≤ 0 := (mem_closed_ball.1 hy).trans (mul_nonpos_of_nonpos_of_nonneg (by linarith) ε0), simp only [dist_le_zero] at this, rw this }, have If' : (0 : ℝ) < f'symm.nnnorm, by { rw [← inv_pos], exact (nnreal.coe_nonneg _).trans_lt hc }, have Icf' : (c : ℝ) * f'symm.nnnorm < 1, by rwa [inv_eq_one_div, lt_div_iff If'] at hc, have Jf' : (f'symm.nnnorm : ℝ) ≠ 0 := ne_of_gt If', have Jcf' : (1 : ℝ) - c * f'symm.nnnorm ≠ 0, by { apply ne_of_gt, linarith }, /- We have to show that `y` can be written as `f x` for some `x ∈ closed_ball b ε`. The idea of the proof is to apply the Banach contraction principle to the map `g : x ↦ x + f'symm (y - f x)`, as a fixed point of this map satisfies `f x = y`. When `f'symm` is a genuine linear inverse, `g` is a contracting map. In our case, since `f'symm` is nonlinear, this map is not contracting (it is not even continuous), but still the proof of the contraction theorem holds: `uₙ = gⁿ b` is a Cauchy sequence, converging exponentially fast to the desired point `x`. Instead of appealing to general results, we check this by hand. The main point is that `f (u n)` becomes exponentially close to `y`, and therefore `dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive bound on `dist (u n) b`, from which one checks that `u n` stays in the ball on which one has a control. Therefore, the bound can be checked at the next step, and so on inductively. -/ set g := λ x, x + f'symm (y - f x) with hg, set u := λ (n : ℕ), g ^[n] b with hu, have usucc : ∀ n, u (n + 1) = g (u n), by simp [hu, ← iterate_succ_apply' g _ b], -- First bound: if `f z` is close to `y`, then `g z` is close to `z` (i.e., almost a fixed point). have A : ∀ z, dist (g z) z ≤ f'symm.nnnorm * dist (f z) y, { assume z, rw [dist_eq_norm, hg, add_sub_cancel', dist_eq_norm'], exact f'symm.bound _ }, -- Second bound: if `z` and `g z` are in the set with good control, then `f (g z)` becomes closer -- to `y` than `f z` was (this uses the linear approximation property, and is the reason for the -- choice of the formula for `g`). have B : ∀ z ∈ closed_ball b ε, g z ∈ closed_ball b ε → dist (f (g z)) y ≤ c * f'symm.nnnorm * dist (f z) y, { assume z hz hgz, set v := f'symm (y - f z) with hv, calc dist (f (g z)) y = ∥f (z + v) - y∥ : by rw [dist_eq_norm] ... = ∥f (z + v) - f z - f' v + f' v - (y - f z)∥ : by { congr' 1, abel } ... = ∥f (z + v) - f z - f' ((z + v) - z)∥ : by simp only [continuous_linear_map.nonlinear_right_inverse.right_inv, add_sub_cancel', sub_add_cancel] ... ≤ c * ∥(z + v) - z∥ : hf _ (hε hgz) _ (hε hz) ... ≤ c * (f'symm.nnnorm * dist (f z) y) : begin apply mul_le_mul_of_nonneg_left _ (nnreal.coe_nonneg c), simpa [hv, dist_eq_norm'] using f'symm.bound (y - f z), end ... = c * f'symm.nnnorm * dist (f z) y : by ring }, -- Third bound: a complicated bound on `dist w b` (that will show up in the induction) is enough -- to check that `w` is in the ball on which one has controls. Will be used to check that `u n` -- belongs to this ball for all `n`. have C : ∀ (n : ℕ) (w : E), dist w b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y → w ∈ closed_ball b ε, { assume n w hw, apply hw.trans, rw [div_mul_eq_mul_div, div_le_iff], swap, { linarith }, calc (f'symm.nnnorm : ℝ) * (1 - (c * f'symm.nnnorm) ^ n) * dist (f b) y = f'symm.nnnorm * dist (f b) y * (1 - (c * f'symm.nnnorm) ^ n) : by ring ... ≤ f'symm.nnnorm * dist (f b) y * 1 : begin apply mul_le_mul_of_nonneg_left _ (mul_nonneg (nnreal.coe_nonneg _) dist_nonneg), rw [sub_le_self_iff], exact pow_nonneg (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) _, end ... ≤ f'symm.nnnorm * (((f'symm.nnnorm : ℝ)⁻¹ - c) * ε) : by { rw [mul_one], exact mul_le_mul_of_nonneg_left (mem_closed_ball'.1 hy) (nnreal.coe_nonneg _) } ... = ε * (1 - c * f'symm.nnnorm) : by { field_simp, ring } }, /- Main inductive control: `f (u n)` becomes exponentially close to `y`, and therefore `dist (u (n+1)) (u n)` becomes exponentally small, making it possible to get an inductive bound on `dist (u n) b`, from which one checks that `u n` remains in the ball on which we have estimates. -/ have D : ∀ (n : ℕ), dist (f (u n)) y ≤ (c * f'symm.nnnorm)^n * dist (f b) y ∧ dist (u n) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y, { assume n, induction n with n IH, { simp [hu, le_refl] }, rw usucc, have Ign : dist (g (u n)) b ≤ f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y := calc dist (g (u n)) b ≤ dist (g (u n)) (u n) + dist (u n) b : dist_triangle _ _ _ ... ≤ f'symm.nnnorm * dist (f (u n)) y + dist (u n) b : add_le_add (A _) le_rfl ... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) + f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n) / (1 - c * f'symm.nnnorm) * dist (f b) y : add_le_add (mul_le_mul_of_nonneg_left IH.1 (nnreal.coe_nonneg _)) IH.2 ... = f'symm.nnnorm * (1 - (c * f'symm.nnnorm)^n.succ) / (1 - c * f'symm.nnnorm) * dist (f b) y : by { field_simp [Jcf'], ring_exp }, refine ⟨_, Ign⟩, calc dist (f (g (u n))) y ≤ c * f'symm.nnnorm * dist (f (u n)) y : B _ (C n _ IH.2) (C n.succ _ Ign) ... ≤ (c * f'symm.nnnorm) * ((c * f'symm.nnnorm)^n * dist (f b) y) : mul_le_mul_of_nonneg_left IH.1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) ... = (c * f'symm.nnnorm) ^ n.succ * dist (f b) y : by ring_exp }, -- Deduce from the inductive bound that `uₙ` is a Cauchy sequence, therefore converging. have : cauchy_seq u, { have : ∀ (n : ℕ), dist (u n) (u (n+1)) ≤ f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n, { assume n, calc dist (u n) (u (n+1)) = dist (g (u n)) (u n) : by rw [usucc, dist_comm] ... ≤ f'symm.nnnorm * dist (f (u n)) y : A _ ... ≤ f'symm.nnnorm * ((c * f'symm.nnnorm)^n * dist (f b) y) : mul_le_mul_of_nonneg_left (D n).1 (nnreal.coe_nonneg _) ... = f'symm.nnnorm * dist (f b) y * (c * f'symm.nnnorm)^n : by ring }, exact cauchy_seq_of_le_geometric _ _ Icf' this }, obtain ⟨x, hx⟩ : ∃ x, tendsto u at_top (𝓝 x) := cauchy_seq_tendsto_of_complete this, -- As all the `uₙ` belong to the ball `closed_ball b ε`, so does their limit `x`. have xmem : x ∈ closed_ball b ε := is_closed_ball.mem_of_tendsto hx (eventually_of_forall (λ n, C n _ (D n).2)), refine ⟨x, xmem, _⟩, -- It remains to check that `f x = y`. This follows from continuity of `f` on `closed_ball b ε` -- and from the fact that `f uₙ` is converging to `y` by construction. have hx' : tendsto u at_top (𝓝[closed_ball b ε] x), { simp only [nhds_within, tendsto_inf, hx, true_and, ge_iff_le, tendsto_principal], exact eventually_of_forall (λ n, C n _ (D n).2) }, have T1 : tendsto (λ n, f (u n)) at_top (𝓝 (f x)) := (hf.continuous_on.mono hε x xmem).tendsto.comp hx', have T2 : tendsto (λ n, f (u n)) at_top (𝓝 y), { rw tendsto_iff_dist_tendsto_zero, refine squeeze_zero (λ n, dist_nonneg) (λ n, (D n).1) _, simpa using (tendsto_pow_at_top_nhds_0_of_lt_1 (mul_nonneg (nnreal.coe_nonneg _) (nnreal.coe_nonneg _)) Icf').mul tendsto_const_nhds }, exact tendsto_nhds_unique T1 T2, end lemma open_image (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) (hs : is_open s) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : is_open (f '' s) := begin cases hc with hE hc, { resetI, apply is_open_discrete }, simp only [is_open_iff_mem_nhds, nhds_basis_closed_ball.mem_iff, ball_image_iff] at hs ⊢, intros x hx, rcases hs x hx with ⟨ε, ε0, hε⟩, refine ⟨(f'symm.nnnorm⁻¹ - c) * ε, mul_pos (sub_pos.2 hc) ε0, _⟩, exact (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'symm (le_of_lt ε0) hε).mono hε (subset.refl _) end lemma image_mem_nhds (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : f '' s ∈ 𝓝 (f x) := begin obtain ⟨t, hts, ht, xt⟩ : ∃ t ⊆ s, is_open t ∧ x ∈ t := _root_.mem_nhds_iff.1 hs, have := is_open.mem_nhds ((hf.mono_set hts).open_image f'symm ht hc) (mem_image_of_mem _ xt), exact mem_of_superset this (image_subset _ hts), end lemma map_nhds_eq (hf : approximates_linear_on f f' s c) (f'symm : f'.nonlinear_right_inverse) {x : E} (hs : s ∈ 𝓝 x) (hc : subsingleton F ∨ c < f'symm.nnnorm⁻¹) : map f (𝓝 x) = 𝓝 (f x) := begin refine le_antisymm ((hf.continuous_on x (mem_of_mem_nhds hs)).continuous_at hs) (le_map (λ t ht, _)), have : f '' (s ∩ t) ∈ 𝓝 (f x) := (hf.mono_set (inter_subset_left s t)).image_mem_nhds f'symm (inter_mem hs ht) hc, exact mem_of_superset this (image_subset _ (inter_subset_right _ _)), end end locally_onto /-! From now on we assume that `f` approximates an invertible continuous linear map `f : E ≃L[𝕜] F`. We also assume that either `E = {0}`, or `c < ∥f'⁻¹∥⁻¹`. We use `N` as an abbreviation for `∥f'⁻¹∥`. -/ variables {f' : E ≃L[𝕜] F} {s : set E} {c : ℝ≥0} local notation `N` := ∥(f'.symm : F →L[𝕜] E)∥₊ protected lemma antilipschitz (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : antilipschitz_with (N⁻¹ - c)⁻¹ (s.restrict f) := begin cases hc with hE hc, { haveI : subsingleton s := ⟨λ x y, subtype.eq $ @subsingleton.elim _ hE _ _⟩, exact antilipschitz_with.of_subsingleton }, convert (f'.antilipschitz.restrict s).add_lipschitz_with hf.lipschitz_sub hc, simp [restrict] end protected lemma injective (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : injective (s.restrict f) := (hf.antilipschitz hc).injective protected lemma inj_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : inj_on f s := inj_on_iff_injective.2 $ hf.injective hc protected lemma surjective [complete_space E] (hf : approximates_linear_on f (f' : E →L[𝕜] F) univ c) (hc : subsingleton E ∨ c < N⁻¹) : surjective f := begin cases hc with hE hc, { haveI : subsingleton F := (equiv.subsingleton_congr f'.to_linear_equiv.to_equiv).1 hE, exact surjective_to_subsingleton _ }, { apply forall_of_forall_mem_closed_ball (λ (y : F), ∃ a, f a = y) (f 0) _, have hc' : (0 : ℝ) < N⁻¹ - c, by { rw sub_pos, exact hc }, let p : ℝ → Prop := λ R, closed_ball (f 0) R ⊆ set.range f, have hp : ∀ᶠ (r:ℝ) in at_top, p ((N⁻¹ - c) * r), { have hr : ∀ᶠ (r:ℝ) in at_top, 0 ≤ r := eventually_ge_at_top 0, refine hr.mono (λ r hr, subset.trans _ (image_subset_range f (closed_ball 0 r))), refine hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse hr _, exact subset_univ _ }, refine ((tendsto_id.const_mul_at_top hc').frequently hp.frequently).mono _, exact λ R h y hy, h hy }, end /-- A map approximating a linear equivalence on a set defines a local equivalence on this set. Should not be used outside of this file, because it is superseded by `to_local_homeomorph` below. This is a first step towards the inverse function. -/ def to_local_equiv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : local_equiv E F := (hf.inj_on hc).to_local_equiv _ _ /-- The inverse function is continuous on `f '' s`. Use properties of `local_homeomorph` instead. -/ lemma inverse_continuous_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : continuous_on (hf.to_local_equiv hc).symm (f '' s) := begin apply continuous_on_iff_continuous_restrict.2, refine ((hf.antilipschitz hc).to_right_inv_on' _ (hf.to_local_equiv hc).right_inv').continuous, exact (λ x hx, (hf.to_local_equiv hc).map_target hx) end /-- The inverse function is approximated linearly on `f '' s` by `f'.symm`. -/ lemma to_inv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : approximates_linear_on (hf.to_local_equiv hc).symm (f'.symm : F →L[𝕜] E) (f '' s) (N * (N⁻¹ - c)⁻¹ * c) := begin assume x hx y hy, set A := hf.to_local_equiv hc with hA, have Af : ∀ z, A z = f z := λ z, rfl, rcases (mem_image _ _ _).1 hx with ⟨x', x's, rfl⟩, rcases (mem_image _ _ _).1 hy with ⟨y', y's, rfl⟩, rw [← Af x', ← Af y', A.left_inv x's, A.left_inv y's], calc ∥x' - y' - (f'.symm) (A x' - A y')∥ ≤ N * ∥f' (x' - y' - (f'.symm) (A x' - A y'))∥ : (f' : E →L[𝕜] F).bound_of_antilipschitz f'.antilipschitz _ ... = N * ∥A y' - A x' - f' (y' - x')∥ : begin congr' 2, simp only [continuous_linear_equiv.apply_symm_apply, continuous_linear_equiv.map_sub], abel, end ... ≤ N * (c * ∥y' - x'∥) : mul_le_mul_of_nonneg_left (hf _ y's _ x's) (nnreal.coe_nonneg _) ... ≤ N * (c * (((N⁻¹ - c)⁻¹ : ℝ≥0) * ∥A y' - A x'∥)) : begin apply_rules [mul_le_mul_of_nonneg_left, nnreal.coe_nonneg], rw [← dist_eq_norm, ← dist_eq_norm], exact (hf.antilipschitz hc).le_mul_dist ⟨y', y's⟩ ⟨x', x's⟩, end ... = (N * (N⁻¹ - c)⁻¹ * c : ℝ≥0) * ∥A x' - A y'∥ : by { simp only [norm_sub_rev, nonneg.coe_mul], ring } end include cs section variables (f s) /-- Given a function `f` that approximates a linear equivalence on an open set `s`, returns a local homeomorph with `to_fun = f` and `source = s`. -/ def to_local_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : local_homeomorph E F := { to_local_equiv := hf.to_local_equiv hc, open_source := hs, open_target := hf.open_image f'.to_nonlinear_right_inverse hs (by rwa f'.to_linear_equiv.to_equiv.subsingleton_congr at hc), continuous_to_fun := hf.continuous_on, continuous_inv_fun := hf.inverse_continuous_on hc } /-- A function `f` that approximates a linear equivalence on the whole space is a homeomorphism. -/ def to_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) univ c) (hc : subsingleton E ∨ c < N⁻¹) : E ≃ₜ F := begin refine (hf.to_local_homeomorph _ _ hc is_open_univ).to_homeomorph_of_source_eq_univ_target_eq_univ rfl _, change f '' univ = univ, rw [image_univ, range_iff_surjective], exact hf.surjective hc, end omit cs /-- In a real vector space, a function `f` that approximates a linear equivalence on a subset `s` can be extended to a homeomorphism of the whole space. -/ lemma exists_homeomorph_extension {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] [finite_dimensional ℝ F] {s : set E} {f : E → F} {f' : E ≃L[ℝ] F} {c : ℝ≥0} (hf : approximates_linear_on f (f' : E →L[ℝ] F) s c) (hc : subsingleton E ∨ lipschitz_extension_constant F * c < (∥(f'.symm : F →L[ℝ] E)∥₊)⁻¹) : ∃ g : E ≃ₜ F, eq_on f g s := begin -- the difference `f - f'` is Lipschitz on `s`. It can be extended to a Lipschitz function `u` -- on the whole space, with a slightly worse Lipschitz constant. Then `f' + u` will be the -- desired homeomorphism. obtain ⟨u, hu, uf⟩ : ∃ (u : E → F), lipschitz_with (lipschitz_extension_constant F * c) u ∧ eq_on (f - f') u s := hf.lipschitz_on_with.extend_finite_dimension, let g : E → F := λ x, f' x + u x, have fg : eq_on f g s := λ x hx, by simp_rw [g, ← uf hx, pi.sub_apply, add_sub_cancel'_right], have hg : approximates_linear_on g (f' : E →L[ℝ] F) univ (lipschitz_extension_constant F * c), { apply lipschitz_on_with.approximates_linear_on, rw lipschitz_on_univ, convert hu, ext x, simp only [add_sub_cancel', continuous_linear_equiv.coe_coe, pi.sub_apply] }, haveI : finite_dimensional ℝ E := f'.symm.to_linear_equiv.finite_dimensional, exact ⟨hg.to_homeomorph g hc, fg⟩, end end @[simp] lemma to_local_homeomorph_coe (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs : E → F) = f := rfl @[simp] lemma to_local_homeomorph_source (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).source = s := rfl @[simp] lemma to_local_homeomorph_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).target = f '' s := rfl lemma closed_ball_subset_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : closed_ball (f b) ((N⁻¹ - c) * ε) ⊆ (hf.to_local_homeomorph f s hc hs).target := (hf.surj_on_closed_ball_of_nonlinear_right_inverse f'.to_nonlinear_right_inverse ε0 hε).mono hε (subset.refl _) end approximates_linear_on /-! ### Inverse function theorem Now we prove the inverse function theorem. Let `f : E → F` be a map defined on a complete vector space `E`. Assume that `f` has an invertible derivative `f' : E ≃L[𝕜] F` at `a : E` in the strict sense. Then `f` approximates `f'` in the sense of `approximates_linear_on` on an open neighborhood of `a`, and we can apply `approximates_linear_on.to_local_homeomorph` to construct the inverse function. -/ namespace has_strict_fderiv_at /-- If `f` has derivative `f'` at `a` in the strict sense and `c > 0`, then `f` approximates `f'` with constant `c` on some neighborhood of `a`. -/ lemma approximates_deriv_on_nhds {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f f' a) {c : ℝ≥0} (hc : subsingleton E ∨ 0 < c) : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := begin cases hc with hE hc, { refine ⟨univ, is_open.mem_nhds is_open_univ trivial, λ x hx y hy, _⟩, simp [@subsingleton.elim E hE x y] }, have := hf.def hc, rw [nhds_prod_eq, filter.eventually, mem_prod_same_iff] at this, rcases this with ⟨s, has, hs⟩, exact ⟨s, has, λ x hx y hy, hs (mk_mem_prod hx hy)⟩ end lemma map_nhds_eq_of_surj [complete_space E] [complete_space F] {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) (h : f'.range = ⊤) : map f (𝓝 a) = 𝓝 (f a) := begin let f'symm := f'.nonlinear_right_inverse_of_surjective h, set c : ℝ≥0 := f'symm.nnnorm⁻¹ / 2 with hc, have f'symm_pos : 0 < f'symm.nnnorm := f'.nonlinear_right_inverse_of_surjective_nnnorm_pos h, have cpos : 0 < c, by simp [hc, nnreal.half_pos, nnreal.inv_pos, f'symm_pos], obtain ⟨s, s_nhds, hs⟩ : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := hf.approximates_deriv_on_nhds (or.inr cpos), apply hs.map_nhds_eq f'symm s_nhds (or.inr (nnreal.half_lt_self _)), simp [ne_of_gt f'symm_pos], end variables [cs : complete_space E] {f : E → F} {f' : E ≃L[𝕜] F} {a : E} lemma approximates_deriv_on_open_nhds (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∃ (s : set E) (hs : a ∈ s ∧ is_open s), approximates_linear_on f (f' : E →L[𝕜] F) s (∥(f'.symm : F →L[𝕜] E)∥₊⁻¹ / 2) := begin refine ((nhds_basis_opens a).exists_iff _).1 _, exact (λ s t, approximates_linear_on.mono_set), exact (hf.approximates_deriv_on_nhds $ f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_pos $ nnreal.inv_pos.2 $ hf') end include cs variable (f) /-- Given a function with an invertible strict derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. This is a part of the inverse function theorem. The other part `has_strict_fderiv_at.to_local_inverse` states that the inverse function of this `local_homeomorph` has derivative `f'.symm`. -/ def to_local_homeomorph (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : local_homeomorph E F := approximates_linear_on.to_local_homeomorph f (classical.some hf.approximates_deriv_on_open_nhds) (classical.some_spec hf.approximates_deriv_on_open_nhds).snd (f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_lt_self $ ne_of_gt $ nnreal.inv_pos.2 $ hf') (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.2 variable {f} @[simp] lemma to_local_homeomorph_coe (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : (hf.to_local_homeomorph f : E → F) = f := rfl lemma mem_to_local_homeomorph_source (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : a ∈ (hf.to_local_homeomorph f).source := (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.1 lemma image_mem_to_local_homeomorph_target (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : f a ∈ (hf.to_local_homeomorph f).target := (hf.to_local_homeomorph f).map_source hf.mem_to_local_homeomorph_source lemma map_nhds_eq_of_equiv (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : map f (𝓝 a) = 𝓝 (f a) := (hf.to_local_homeomorph f).map_nhds_eq hf.mem_to_local_homeomorph_source variables (f f' a) /-- Given a function `f` with an invertible derivative, returns a function that is locally inverse to `f`. -/ def local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : F → E := (hf.to_local_homeomorph f).symm variables {f f' a} lemma local_inverse_def (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f _ _ = (hf.to_local_homeomorph f).symm := rfl lemma eventually_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ x in 𝓝 a, hf.local_inverse f f' a (f x) = x := (hf.to_local_homeomorph f).eventually_left_inverse hf.mem_to_local_homeomorph_source @[simp] lemma local_inverse_apply_image (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f f' a (f a) = a := hf.eventually_left_inverse.self_of_nhds lemma eventually_right_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ y in 𝓝 (f a), f (hf.local_inverse f f' a y) = y := (hf.to_local_homeomorph f).eventually_right_inverse' hf.mem_to_local_homeomorph_source lemma local_inverse_continuous_at (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : continuous_at (hf.local_inverse f f' a) (f a) := (hf.to_local_homeomorph f).continuous_at_symm hf.image_mem_to_local_homeomorph_target lemma local_inverse_tendsto (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : tendsto (hf.local_inverse f f' a) (𝓝 $ f a) (𝓝 a) := (hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source lemma local_inverse_unique (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : ∀ᶠ y in 𝓝 (f a), g y = local_inverse f f' a hf y := eventually_eq_of_left_inv_of_right_inv hg hf.eventually_right_inverse $ (hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source /-- If `f` has an invertible derivative `f'` at `a` in the sense of strict differentiability `(hf)`, then the inverse function `hf.local_inverse f` has derivative `f'.symm` at `f a`. -/ theorem to_local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : has_strict_fderiv_at (hf.local_inverse f f' a) (f'.symm : F →L[𝕜] E) (f a) := (hf.to_local_homeomorph f).has_strict_fderiv_at_symm hf.image_mem_to_local_homeomorph_target $ by simpa [← local_inverse_def] using hf /-- If `f : E → F` has an invertible derivative `f'` at `a` in the sense of strict differentiability and `g (f x) = x` in a neighborhood of `a`, then `g` has derivative `f'.symm` at `f a`. For a version assuming `f (g y) = y` and continuity of `g` at `f a` but not `[complete_space E]` see `of_local_left_inverse`. -/ theorem to_local_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) (f a) := hf.to_local_inverse.congr_of_eventually_eq $ (hf.local_inverse_unique hg).mono $ λ _, eq.symm end has_strict_fderiv_at /-- If a function has an invertible strict derivative at all points, then it is an open map. -/ lemma open_map_of_strict_fderiv_equiv [complete_space E] {f : E → F} {f' : E → E ≃L[𝕜] F} (hf : ∀ x, has_strict_fderiv_at f (f' x : E →L[𝕜] F) x) : is_open_map f := is_open_map_iff_nhds_le.2 $ λ x, (hf x).map_nhds_eq_of_equiv.ge /-! ### Inverse function theorem, 1D case In this case we prove a version of the inverse function theorem for maps `f : 𝕜 → 𝕜`. We use `continuous_linear_equiv.units_equiv_aut` to translate `has_strict_deriv_at f f' a` and `f' ≠ 0` into `has_strict_fderiv_at f (_ : 𝕜 ≃L[𝕜] 𝕜) a`. -/ namespace has_strict_deriv_at variables [cs : complete_space 𝕜] {f : 𝕜 → 𝕜} {f' a : 𝕜} (hf : has_strict_deriv_at f f' a) (hf' : f' ≠ 0) include cs variables (f f' a) /-- A function that is inverse to `f` near `a`. -/ @[reducible] def local_inverse : 𝕜 → 𝕜 := (hf.has_strict_fderiv_at_equiv hf').local_inverse _ _ _ variables {f f' a} lemma map_nhds_eq : map f (𝓝 a) = 𝓝 (f a) := (hf.has_strict_fderiv_at_equiv hf').map_nhds_eq_of_equiv theorem to_local_inverse : has_strict_deriv_at (hf.local_inverse f f' a hf') f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_inverse theorem to_local_left_inverse {g : 𝕜 → 𝕜} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_deriv_at g f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_left_inverse hg end has_strict_deriv_at /-- If a function has a non-zero strict derivative at all points, then it is an open map. -/ lemma open_map_of_strict_deriv [complete_space 𝕜] {f f' : 𝕜 → 𝕜} (hf : ∀ x, has_strict_deriv_at f (f' x) x) (h0 : ∀ x, f' x ≠ 0) : is_open_map f := is_open_map_iff_nhds_le.2 $ λ x, ((hf x).map_nhds_eq (h0 x)).ge /-! ### Inverse function theorem, smooth case -/ namespace cont_diff_at variables {𝕂 : Type*} [is_R_or_C 𝕂] variables {E' : Type*} [normed_add_comm_group E'] [normed_space 𝕂 E'] variables {F' : Type*} [normed_add_comm_group F'] [normed_space 𝕂 F'] variables [complete_space E'] (f : E' → F') {f' : E' ≃L[𝕂] F'} {a : E'} /-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. -/ def to_local_homeomorph {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : local_homeomorph E' F' := (hf.has_strict_fderiv_at' hf' hn).to_local_homeomorph f variable {f} @[simp] lemma to_local_homeomorph_coe {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : (hf.to_local_homeomorph f hf' hn : E' → F') = f := rfl lemma mem_to_local_homeomorph_source {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : a ∈ (hf.to_local_homeomorph f hf' hn).source := (hf.has_strict_fderiv_at' hf' hn).mem_to_local_homeomorph_source lemma image_mem_to_local_homeomorph_target {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : f a ∈ (hf.to_local_homeomorph f hf' hn).target := (hf.has_strict_fderiv_at' hf' hn).image_mem_to_local_homeomorph_target /-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, returns a function that is locally inverse to `f`. -/ def local_inverse {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : F' → E' := (hf.has_strict_fderiv_at' hf' hn).local_inverse f f' a lemma local_inverse_apply_image {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : hf.local_inverse hf' hn (f a) = a := (hf.has_strict_fderiv_at' hf' hn).local_inverse_apply_image /-- Given a `cont_diff` function over `𝕂` (which is `ℝ` or `ℂ`) with an invertible derivative at `a`, the inverse function (produced by `cont_diff.to_local_homeomorph`) is also `cont_diff`. -/ lemma to_local_inverse {n : ℕ∞} (hf : cont_diff_at 𝕂 n f a) (hf' : has_fderiv_at f (f' : E' →L[𝕂] F') a) (hn : 1 ≤ n) : cont_diff_at 𝕂 n (hf.local_inverse hf' hn) (f a) := begin have := hf.local_inverse_apply_image hf' hn, apply (hf.to_local_homeomorph f hf' hn).cont_diff_at_symm (image_mem_to_local_homeomorph_target hf hf' hn), { convert hf' }, { convert hf } end end cont_diff_at
06a0f1a3b08918c0db1cd43b39509bd30f30c996
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/types/fiber.hlean
37f89ecbad3dd79d3f24a1a42ed9fe5a33c1ec6b
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
10,767
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mike Shulman Ported from Coq HoTT Theorems about fibers -/ import .sigma .eq .pi cubical.squareover .pointed .eq open equiv sigma sigma.ops eq pi pointed structure fiber {A B : Type} (f : A → B) (b : B) := (point : A) (point_eq : f point = b) namespace fiber variables {A B : Type} {f : A → B} {b : B} protected definition sigma_char [constructor] (f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) := begin fapply equiv.MK, {intro x, exact ⟨point x, point_eq x⟩}, {intro x, exact (fiber.mk x.1 x.2)}, {intro x, cases x, apply idp }, {intro x, cases x, apply idp }, end definition fiber_eq_equiv [constructor] (x y : fiber f b) : (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) := begin apply equiv.trans, apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char, apply equiv.trans, apply sigma_eq_equiv, apply sigma_equiv_sigma_right, intro p, apply eq_pathover_equiv_Fl, end definition fiber_eq {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : x = y := to_inv !fiber_eq_equiv ⟨p, q⟩ definition fiber_pathover {X : Type} {A B : X → Type} {x₁ x₂ : X} {p : x₁ = x₂} {f : Πx, A x → B x} {b : Πx, B x} {v₁ : fiber (f x₁) (b x₁)} {v₂ : fiber (f x₂) (b x₂)} (q : point v₁ =[p] point v₂) (r : squareover B hrfl (pathover_idp_of_eq (point_eq v₁)) (pathover_idp_of_eq (point_eq v₂)) (apo f q) (apd b p)) : v₁ =[p] v₂ := begin apply pathover_of_fn_pathover_fn (λa, !fiber.sigma_char), esimp, fapply sigma_pathover: esimp, { exact q}, { induction v₁ with a₁ p₁, induction v₂ with a₂ p₂, esimp at *, induction q, esimp at *, apply pathover_idp_of_eq, apply eq_of_vdeg_square, apply square_of_squareover_ids r} end open is_trunc definition fiber_pr1 (B : A → Type) (a : A) : fiber (pr1 : (Σa, B a) → A) a ≃ B a := calc fiber pr1 a ≃ Σu, u.1 = a : fiber.sigma_char ... ≃ Σa' (b : B a'), a' = a : sigma_assoc_equiv ... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', !comm_equiv_nondep) ... ≃ Σu, B u.1 : sigma_assoc_equiv ... ≃ B a : !sigma_equiv_of_is_contr_left definition sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A := calc (Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, !fiber.sigma_char) ... ≃ Σa b, f a = b : sigma_comm_equiv ... ≃ A : sigma_equiv_of_is_contr_right definition is_pointed_fiber [instance] [constructor] (f : A → B) (a : A) : pointed (fiber f (f a)) := pointed.mk (fiber.mk a idp) definition pointed_fiber [constructor] (f : A → B) (a : A) : Type* := pointed.Mk (fiber.mk a (idpath (f a))) definition is_trunc_fun [reducible] (n : ℕ₋₂) (f : A → B) := Π(b : B), is_trunc n (fiber f b) definition is_contr_fun [reducible] (f : A → B) := is_trunc_fun -2 f -- pre and post composition with equivalences open function variable (f) protected definition equiv_postcompose [constructor] {B' : Type} (g : B ≃ B') --[H : is_equiv g] (b : B) : fiber (g ∘ f) (g b) ≃ fiber f b := calc fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma_right, intro a, apply equiv.symm, apply eq_equiv_fn_eq end ... ≃ fiber f b : fiber.sigma_char protected definition equiv_precompose [constructor] {A' : Type} (g : A' ≃ A) --[H : is_equiv g] (b : B) : fiber (f ∘ g) b ≃ fiber f b := calc fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma g, intro a', apply erfl end ... ≃ fiber f b : fiber.sigma_char end fiber open unit is_trunc pointed namespace fiber definition fiber_star_equiv [constructor] (A : Type) : fiber (λx : A, star) star ≃ A := begin fapply equiv.MK, { intro f, cases f with a H, exact a }, { intro a, apply fiber.mk a, reflexivity }, { intro a, reflexivity }, { intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H, rewrite [is_set.elim H (refl star)] } end definition fiber_const_equiv [constructor] (A : Type) (a₀ : A) (a : A) : fiber (λz : unit, a₀) a ≃ a₀ = a := calc fiber (λz : unit, a₀) a ≃ Σz : unit, a₀ = a : fiber.sigma_char ... ≃ a₀ = a : sigma_unit_left -- the pointed fiber of a pointed map, which is the fiber over the basepoint open pointed definition pfiber [constructor] {X Y : Type*} (f : X →* Y) : Type* := pointed.MK (fiber f pt) (fiber.mk pt !respect_pt) definition ppoint [constructor] {X Y : Type*} (f : X →* Y) : pfiber f →* X := pmap.mk point idp definition pfiber.sigma_char [constructor] {A B : Type*} (f : A →* B) : pfiber f ≃* pointed.MK (Σa, f a = pt) ⟨pt, respect_pt f⟩ := pequiv_of_equiv (fiber.sigma_char f pt) idp definition ppoint_sigma_char [constructor] {A B : Type*} (f : A →* B) : ppoint f ~* pmap.mk pr1 idp ∘* pfiber.sigma_char f := !phomotopy.refl definition pfiber_loop_space {A B : Type*} (f : A →* B) : pfiber (Ω→ f) ≃* Ω (pfiber f) := pequiv_of_equiv (calc pfiber (Ω→ f) ≃ Σ(p : Point A = Point A), ap1 f p = rfl : (fiber.sigma_char (ap1 f) (Point (Ω B))) ... ≃ Σ(p : Point A = Point A), (respect_pt f) = ap f p ⬝ (respect_pt f) : (sigma_equiv_sigma_right (λp, calc (ap1 f p = rfl) ≃ !respect_pt⁻¹ ⬝ (ap f p ⬝ !respect_pt) = rfl : equiv_eq_closed_left _ (con.assoc _ _ _) ... ≃ ap f p ⬝ (respect_pt f) = (respect_pt f) : eq_equiv_inv_con_eq_idp ... ≃ (respect_pt f) = ap f p ⬝ (respect_pt f) : eq_equiv_eq_symm)) ... ≃ fiber.mk (Point A) (respect_pt f) = fiber.mk pt (respect_pt f) : fiber_eq_equiv ... ≃ Ω (pfiber f) : erfl) (begin cases f with f p, cases A with A a, cases B with B b, esimp at p, esimp at f, induction p, reflexivity end) definition pfiber_equiv_of_phomotopy {A B : Type*} {f g : A →* B} (h : f ~* g) : pfiber f ≃* pfiber g := begin fapply pequiv_of_equiv, { refine (fiber.sigma_char f pt ⬝e _ ⬝e (fiber.sigma_char g pt)⁻¹ᵉ), apply sigma_equiv_sigma_right, intros a, apply equiv_eq_closed_left, apply (to_homotopy h) }, { refine (fiber_eq rfl _), change (h pt)⁻¹ ⬝ respect_pt f = idp ⬝ respect_pt g, rewrite idp_con, apply inv_con_eq_of_eq_con, symmetry, exact (to_homotopy_pt h) } end definition transport_fiber_equiv [constructor] {A B : Type} (f : A → B) {b1 b2 : B} (p : b1 = b2) : fiber f b1 ≃ fiber f b2 := calc fiber f b1 ≃ Σa, f a = b1 : fiber.sigma_char ... ≃ Σa, f a = b2 : sigma_equiv_sigma_right (λa, equiv_eq_closed_right (f a) p) ... ≃ fiber f b2 : fiber.sigma_char definition pequiv_postcompose {A B B' : Type*} (f : A →* B) (g : B ≃* B') : pfiber (g ∘* f) ≃* pfiber f := begin fapply pequiv_of_equiv, esimp, refine transport_fiber_equiv (g ∘* f) (respect_pt g)⁻¹ ⬝e fiber.equiv_postcompose f g (Point B), esimp, apply (ap (fiber.mk (Point A))), refine !con.assoc ⬝ _, apply inv_con_eq_of_eq_con, rewrite [con.assoc, con.right_inv, con_idp, -ap_compose'], apply ap_con_eq_con end definition pequiv_precompose {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : pfiber (f ∘* g) ≃* pfiber f := begin fapply pequiv_of_equiv, esimp, refine fiber.equiv_precompose f g (Point B), esimp, apply (eq_of_fn_eq_fn (fiber.sigma_char _ _)), fapply sigma_eq: esimp, { apply respect_pt g }, { apply eq_pathover_Fl' } end definition pfiber_equiv_of_square {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k ∘* f ~* g ∘* h) : pfiber f ≃* pfiber g := calc pfiber f ≃* pfiber (k ∘* f) : pequiv_postcompose ... ≃* pfiber (g ∘* h) : pfiber_equiv_of_phomotopy s ... ≃* pfiber g : pequiv_precompose end fiber open function is_equiv namespace fiber /- Theorem 4.7.6 -/ variables {A : Type} {P Q : A → Type} variable (f : Πa, P a → Q a) definition fiber_total_equiv [constructor] {a : A} (q : Q a) : fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q := calc fiber (total f) ⟨a , q⟩ ≃ Σ(w : Σx, P x), ⟨w.1 , f w.1 w.2 ⟩ = ⟨a , q⟩ : fiber.sigma_char ... ≃ Σ(x : A), Σ(p : P x), ⟨x , f x p⟩ = ⟨a , q⟩ : sigma_assoc_equiv ... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q : begin apply sigma_equiv_sigma_right, intro x, apply sigma_equiv_sigma_right, intro p, apply sigma_eq_equiv end ... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q : begin apply sigma_equiv_sigma_right, intro x, apply sigma_comm_equiv end ... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q : sigma_assoc_equiv ... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q : sigma_equiv_of_is_contr_left ... ≃ Σ(p : P a), f a p =[idpath a] q : equiv_of_eq idp ... ≃ Σ(p : P a), f a p = q : begin apply sigma_equiv_sigma_right, intro p, apply pathover_idp end ... ≃ fiber (f a) q : fiber.sigma_char end fiber
f191ee11088607aa14414dd498c6d14f4c85f183
d642a6b1261b2cbe691e53561ac777b924751b63
/src/topology/algebra/uniform_group.lean
e38b175b567921a37788be753425ee8186db965d
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
19,797
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Uniform structure on topological groups: * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ import topology.uniform_space.uniform_embedding topology.uniform_space.complete_separated import topology.algebra.group noncomputable theory open_locale classical uniformity section uniform_add_group open filter set variables {α : Type*} {β : Type*} /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub' : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub α lemma uniform_continuous_sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := uniform_continuous_sub'.comp (hf.prod_mk hg) lemma uniform_continuous_neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_sub uniform_continuous_const hf, by simp * at * lemma uniform_continuous_neg' : uniform_continuous (λx:α, - x) := uniform_continuous_neg uniform_continuous_id lemma uniform_continuous_add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from uniform_continuous_sub hf $ uniform_continuous_neg hg, by simp * at * lemma uniform_continuous_add' : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_add uniform_continuous_fst uniform_continuous_snd @[priority 10] instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add'.continuous, continuous_neg := uniform_continuous_neg'.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨uniform_continuous.prod_mk (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_fst) (uniform_continuous_fst.comp uniform_continuous_snd)) (uniform_continuous_sub (uniform_continuous_snd.comp uniform_continuous_fst) (uniform_continuous_snd.comp uniform_continuous_snd)) ⟩ lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α := le_antisymm (uniform_continuous_add uniform_continuous_id uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_add uniform_continuous_id uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := { comap_uniformity := begin rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end, inj := assume x y, eq_of_add_eq_add_right } section variables (α) lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (nhds (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap_comp], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_sub' hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_sets_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_add' hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_eq_empty] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (nhds 0) (nhds 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [is_add_group_hom.map_sub f] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp h tendsto_comap end lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (nhds 0) (nhds (f 0)), by rwa [is_add_group_hom.map_zero f] at this, h.tendsto 0 end uniform_add_group section topological_add_comm_group universes u v w x open filter variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (nhds 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (nhds 0)) (nhds (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp (tendsto_neg tendsto_id) tendsto_comap end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 - p.1) (nhds (0 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa using V_sum _ _ Hz1 Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 - p.1) (nhds (0 : G)), rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation a, mem_comap_sets, mem_comap_sets], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : 𝓤 G = comap (λp:G×G, p.2 - p.1) (nhds (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((nhds 0).prod (nhds 0))) (nhds (0 - 0)) := (tendsto_sub tendsto_fst tendsto_snd).comp tendsto_comap, begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘)] end end lemma to_uniform_space_eq {α : Type*} [u : uniform_space α] [add_comm_group α] [uniform_add_group α]: topological_add_group.to_uniform_space α = u := begin ext : 1, show @uniformity α (topological_add_group.to_uniform_space α) = 𝓤 α, rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α] end end topological_add_comm_group namespace add_comm_group section Z_bilin variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [add_comm_group α] [add_comm_group β] [add_comm_group γ] /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ class is_Z_bilin (f : α × β → γ) : Prop := (add_left : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b)) (add_right : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b')) variables (f : α × β → γ) [is_Z_bilin f] instance is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_hom.map_add g] instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) := ⟨λ a a' b, is_Z_bilin.add_right f b a a', λ a b b', is_Z_bilin.add_left f b b' a⟩ lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 := begin intro b, apply add_self_iff_eq_zero.1, rw ←is_Z_bilin.add_left f, simp end lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) lemma is_Z_bilin.zero : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) := begin intros a b, apply eq_of_sub_eq_zero, rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f] end lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) := assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) := begin intros, dsimp [algebra.sub], rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f] end lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') := assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end Z_bilin end add_comm_group open add_comm_group filter set function section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} -- α, β and G are abelian topological groups, G is a uniform space variables [topological_space α] [add_comm_group α] variables [topological_space β] [add_comm_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (nhds (x₁, 0)) (nhds 0) := begin have := continuous.tendsto hψ (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (nhds (0, y₁)) (nhds 0) := begin have := continuous.tendsto hψ (0, y₁), rwa [is_Z_bilin.zero_left ψ] at this end end section variables {α : Type*} {β : Type*} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ nhds (x₀, x₀)) (nhds 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← is_add_group_hom.map_sub e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (nhds (x₀, x₀)) (nhds (e 0)), { have := continuous.tendsto (continuous_sub'.comp continuous_swap) (x₀, x₀), simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.map_zero e)] using this }, have := de.tendsto_comap_nhds_nhds lim comm, simp [-sub_eq_add_neg, this] end end namespace dense_inducing variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated G] [complete_space G] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_inducing f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ nhds (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (nhds x₀), ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := nhds x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (nhds (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ nhds (x₀, x₀)) (nhds y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp (is_Z_bilin.tendsto_zero_right hφ y₁) lim1, rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (nhds x₀), ∃ V ∈ comap f (nhds y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := nhds x₀, let Ny := nhds y₀, let dp := dense_inducing.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto φ (nhds (0, 0)) (nhds 0), { have := continuous.tendsto hφ (0, 0), rwa [is_Z_bilin.zero φ] at this }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee $ nhds (x₀, x₀)) (comap ff $ nhds (y₀, y₀))) (nhds 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (nhds (x₀, x₀))) (comap ff (nhds (y₀, y₀)))) (filter.prod (nhds 0) (nhds 0)), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_φ lim_sub_sub }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (nhds x₀), ∃ V₁ ∈ comap f (nhds y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, have : ∃ x₁, x₁ ∈ U₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 de.comap_nhds_neq_bot U₁ U₁_nhd), rcases this with ⟨x₁, x₁_in⟩, have : ∃ y₁, y₁ ∈ V₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 df.comap_nhds_neq_bot V₁ V₁_nhd), rcases this with ⟨y₁, y₁_in⟩, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (hφ.comp continuous_swap) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y), { repeat { rw is_Z_bilin.sub_left φ }, repeat { rw is_Z_bilin.sub_right φ }, apply eq_of_sub_eq_zero, simp }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (de.prod df) φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_neq_bot, intros U h, rcases exists_mem_of_ne_empty (mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h) with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (filter.prod (nhds (x₀, y₀)) (nhds (x₀, y₀)))) ≤ nhds 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap_sets at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap_sets at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap_sets, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ nhds x₀ at U'_nhd, change V' ∈ nhds y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
ac21f7e5f6c94c9e536e7b065cefa7ef50276be9
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/meta/rb_map.lean
3cafe71361dc664731be43ae6617b33e32c5f150
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
6,292
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import data.option.defs /-! # rb_map This file defines additional operations on native rb_maps and rb_sets. These structures are defined in core in `init.meta.rb_map`. They are meta objects, and are generally the most efficient dictionary structures to use for pure metaprogramming right now. -/ namespace native namespace rb_set meta instance {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_set key) := ⟨mk_rb_set⟩ /-- `filter s P` returns the subset of elements of `s` satisfying `P`. -/ meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter s P` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union {key} (s t : rb_set key) : rb_set key := s.fold t (λ a t, t.insert a) /-- `of_list_core empty l` turns a list of keys into an `rb_set`. It takes a user_provided `rb_set` to use for the base case. This can be used to pre-seed the set with additional elements, and/or to use a custom comparison operator. -/ meta def of_list_core {key} (base : native.rb_set key) : list key → native.rb_map key unit | [] := base | (x::xs) := native.rb_set.insert (of_list_core xs) x end rb_set namespace rb_map meta instance {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_map key data) := ⟨mk_rb_map⟩ /-- `find_def default m k` returns the value corresponding to `k` in `m`, if it exists. Otherwise it returns `default`. -/ meta def find_def {key value} (default : value) (m : rb_map key value) (k : key) := (m.find k).get_or_else default /-- `ifind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns the default value of `value`. -/ meta def ifind {key value} [inhabited value] (m : rb_map key value) (k : key) : value := (m.find k).iget /-- `zfind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns 0. -/ meta def zfind {key value} [has_zero value] (m : rb_map key value) (k : key) : value := (m.find k).get_or_else 0 /-- Returns the pointwise sum of `m1` and `m2`, treating nonexistent values as 0. -/ meta def add {key value} [has_add value] [has_zero value] [decidable_eq value] (m1 m2 : rb_map key value) : rb_map key value := m1.fold m2 (λ n v m, let nv := v + m2.zfind n in if nv = 0 then m.erase n else m.insert n nv) variables {m : Type → Type*} [monad m] open function /-- `mfilter P s` filters `s` by the monadic predicate `P` on keys and values. -/ meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) := rb_map.of_list <$> s.to_list.mfilter (uncurry P) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') := rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b) /-- `scale b m` multiplies every value in `m` by `b`. -/ meta def scale {key value} [has_lt key] [decidable_rel ((<) : key → key → Prop)] [has_mul value] (b : value) (m : rb_map key value) : rb_map key value := m.map ((*) b) section open format prod variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data] private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format := do fk ← tactic.pp k, fd ← tactic.pp d, return $ (if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd meta instance : has_to_tactic_format (rb_map key data) := ⟨λ m, do (fmt, _) ← fold m (return (to_fmt "", tt)) (λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)), return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩ end end rb_map namespace rb_lmap meta instance (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : inhabited (rb_lmap key data) := ⟨rb_lmap.mk _ _⟩ /-- Construct a rb_lmap from a list of key-data pairs -/ protected meta def of_list {key : Type} {data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data | [] := rb_lmap.mk key data | ((k, v)::ls) := (of_list ls).insert k v /-- Returns the list of values of an `rb_lmap`. -/ protected meta def values {key data} (m : rb_lmap key data) : list data := m.fold [] (λ _, (++)) end rb_lmap end native namespace name_set meta instance : inhabited name_set := ⟨mk_name_set⟩ /-- `filter P s` returns the subset of elements of `s` satisfying `P`. -/ meta def filter (P : name → bool) (s : name_set) : name_set := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter P s` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set := s.fold (pure mk_name_set) (λ a m, do x ← m, b ← f a, (pure $ x.insert b)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union (s t : name_set) : name_set := s.fold t (λ a t, t.insert a) /-- `insert_list s l` inserts every element of `l` into `s`. -/ meta def insert_list (s : name_set) (l : list name) : name_set := l.foldr (λ n s', s'.insert n) s end name_set namespace name_map meta instance {data : Type} : inhabited (name_map data) := ⟨mk_name_map⟩ end name_map
4620b9bd658af80549f45086b0e72998e6389a21
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/data/nat/prime.lean
b8b526bd0c8b4187c968ab54e6c51db1405b2f98
[ "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
15,089
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro Prime numbers. -/ import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm open bool subtype namespace nat open decidable /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 := lt_of_succ_lt pp.gt_one theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 := lt_pred_of_succ_lt pp.gt_one theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_ge_two h a1).1 (dvd_mul_right _ _) section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := rfl | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_ge_two pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, m ≥ 2 → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : min_fac n > 0 := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p := ⟨λ pp, ⟨pp.ge_two, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ theorem exists_infinite_primes : ∀ n : ℕ, ∃ p, p ≥ n ∧ prime p := suffices ∀ {n}, n ≥ 2 → ∃ p, p ≥ n ∧ prime p, from λ n, let ⟨p, h, pp⟩ := this (nat.le_add_left 2 n) in ⟨p, le_trans (nat.le_add_right n 2) h, pp⟩, λ n n2, let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have n ≤ p, from le_of_not_ge $ λ h, have p ∣ fact n, from dvd_fact (min_fac_pos _) h, have p ∣ 1, from (nat.dvd_add_iff_right this).2 (min_fac_dvd _), pp.not_dvd_one this, ⟨p, this, pp⟩ theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_of_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) (h : p ∣ n) : p ∈ factors n := mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h) lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb], perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end end nat
368760fe8cc2595203800cf9899e9cf25f6ebb4d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/module/basic.lean
4aa56282af5f35ddbfc587bd37463f5326a4252d
[ "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
25,781
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 algebra.smul_with_zero import group_theory.group_action.group import tactic.abel /-! # Modules over a ring In this file we define * `module R M` : an additive commutative monoid `M` is a `module` 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. ## Implementation notes In typical mathematical usage, our definition of `module` corresponds to "semimodule", and the word "module" is reserved for `module R M` where `R` is a `ring` and `M` an `add_comm_group`. If `R` is a `field` and `M` an `add_comm_group`, `M` would be called an `R`-vector space. Since those assumptions can be made by changing the typeclasses applied to `R` and `M`, without changing the axioms in `module`, mathlib calls everything a `module`. In older versions of mathlib, we had separate `semimodule` and `vector_space` abbreviations. This caused inference issues in some cases, while not providing any real advantages, so we decided to use a canonical `module` typeclass throughout. ## Tags semimodule, module, vector space -/ open function universes u v variables {α R k S M M₂ M₃ ι : Type*} /-- A module 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. -/ @[ext, protect_proj] class module (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] [module R M] (r s : R) (x y : M) /-- A module over a semiring automatically inherits a `mul_action_with_zero` structure. -/ @[priority 100] -- see Note [lower instance priority] instance module.to_mul_action_with_zero : mul_action_with_zero R M := { smul_zero := smul_zero, zero_smul := module.zero_smul, ..(infer_instance : mul_action R M) } instance add_comm_monoid.nat_module : module ℕ M := { one_smul := one_nsmul, mul_smul := λ m n a, mul_nsmul a m n, smul_add := λ n a b, nsmul_add a b n, smul_zero := nsmul_zero, zero_smul := zero_nsmul, add_smul := λ r s x, add_nsmul x r s } lemma add_monoid.End.nat_cast_def (n : ℕ) : (↑n : add_monoid.End M) = distrib_mul_action.to_add_monoid_End ℕ M n := rfl theorem add_smul : (r + s) • x = r • x + s • x := module.add_smul r s x lemma convex.combo_self {a b : R} (h : a + b = 1) (x : M) : a • x + b • x = x := by rw [←add_smul, h, one_smul] variables (R) theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] theorem two_smul' : (2 : R) • x = bit0 x := two_smul R x @[simp] lemma inv_of_two_smul_add_inv_of_two_smul [invertible (2 : R)] (x : M) : (⅟2 : R) • x + (⅟2 : R) • x = x := convex.combo_self inv_of_two_add_inv_of_two _ /-- Pullback a `module` structure along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.module [add_comm_monoid M₂] [has_smul R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module 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 `module` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.module [add_comm_monoid M₂] [has_smul R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : module 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 } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →+* S`. See also `function.surjective.mul_action_left` and `function.surjective.distrib_mul_action_left`. -/ @[reducible] def function.surjective.module_left {R S M : Type*} [semiring R] [add_comm_monoid M] [module R M] [semiring S] [has_smul S M] (f : R →+* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : module S M := { smul := (•), zero_smul := λ x, by rw [← f.map_zero, hsmul, zero_smul], add_smul := hf.forall₂.mpr (λ a b x, by simp only [← f.map_add, hsmul, add_smul]), .. hf.distrib_mul_action_left f.to_monoid_hom hsmul } variables {R} (M) /-- Compose a `module` with a `ring_hom`, with action `f s • m`. See note [reducible non-instances]. -/ @[reducible] def module.comp_hom [semiring S] (f : S →+* R) : module S M := { smul := has_smul.comp.smul f, add_smul := λ r s x, by simp [add_smul], .. mul_action_with_zero.comp_hom M f.to_monoid_with_zero_hom, .. distrib_mul_action.comp_hom M (f : S →* R) } variables (R) (M) /-- `(•)` as an `add_monoid_hom`. This is a stronger version of `distrib_mul_action.to_add_monoid_End` -/ @[simps apply_apply] def module.to_add_monoid_End : R →+* add_monoid.End M := { map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul], ..distrib_mul_action.to_add_monoid_End R M } /-- A convenience alias for `module.to_add_monoid_End` as an `add_monoid_hom`, usually to allow the use of `add_monoid_hom.flip`. -/ def smul_add_hom : R →+ M →+ M := (module.to_add_monoid_End R M).to_add_monoid_hom variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma module.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] @[simp] lemma smul_add_one_sub_smul {R : Type*} [ring R] [module R M] {r : R} {m : M} : r • m + (1 - r) • m = m := by rw [← add_smul, add_sub_cancel'_right, one_smul] end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `module` over a `ring` carries a natural `add_comm_group` structure. See note [reducible non-instances]. -/ @[reducible] def module.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [module R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, show (-1 : R) • a + a = 0, 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] instance add_comm_group.int_module : module ℤ M := { one_smul := one_zsmul, mul_smul := λ m n a, mul_zsmul a m n, smul_add := λ n a b, zsmul_add a b n, smul_zero := zsmul_zero, zero_smul := zero_zsmul, add_smul := λ r s x, add_zsmul x r s } lemma add_monoid.End.int_cast_def (z : ℤ) : (↑z : add_monoid.End M) = distrib_mul_action.to_add_monoid_End ℤ M z := rfl /-- A structure containing most informations as in a module, 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 module structure by checking less properties, in `module.of_core`. -/ @[nolint has_nonempty_instance] structure module.core extends has_smul 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 `module` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `module.core`, when the underlying space is an `add_comm_group`. -/ def module.of_core (H : module.core R M) : module R M := by letI := H.to_has_smul; 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 } lemma convex.combo_eq_smul_sub_add [module R M] {x y : M} {a b : R} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + x : by rw [smul_sub, convex.combo_self h] end add_comm_group /-- A variant of `module.ext` that's convenient for term-mode. -/ -- We'll later use this to show `module ℕ M` and `module ℤ M` are subsingletons. lemma module.ext' {R : Type*} [semiring R] {M : Type*} [add_comm_monoid 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 ext, exact w _ _ 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_left $ by rw [← add_smul, add_left_neg, zero_smul] @[simp] lemma neg_smul_neg : -r • -x = r • x := by rw [neg_smul, smul_neg, neg_neg] @[simp] theorem units.neg_smul (u : Rˣ) (x : M) : -u • x = - (u • x) := by rw [units.smul_def, units.coe_neg, neg_smul, units.smul_def] 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] end module /-- A module over a `subsingleton` semiring is a `subsingleton`. We cannot register this as an instance because Lean has no way to guess `R`. -/ protected theorem module.subsingleton (R M : Type*) [semiring R] [subsingleton R] [add_comm_monoid M] [module R M] : subsingleton M := ⟨λ x y, by rw [← one_smul R x, ← one_smul R y, subsingleton.elim (1:R) 0, zero_smul, zero_smul]⟩ /-- A semiring is `nontrivial` provided that there exists a nontrivial module over this semiring. -/ protected theorem module.nontrivial (R M : Type*) [semiring R] [nontrivial M] [add_comm_monoid M] [module R M] : nontrivial R := (subsingleton_or_nontrivial R).resolve_left $ λ hR, not_subsingleton M $ by exactI module.subsingleton R M @[priority 910] -- see Note [lower instance priority] instance semiring.to_module [semiring R] : module R R := { smul_add := mul_add, add_smul := add_mul, zero_smul := zero_mul, smul_zero := mul_zero } /-- Like `semiring.to_module`, but multiplies on the right. -/ @[priority 910] -- see Note [lower instance priority] instance semiring.to_opposite_module [semiring R] : module Rᵐᵒᵖ R := { smul_add := λ r x y, add_mul _ _ _, add_smul := λ r x y, mul_add _ _ _, ..monoid_with_zero.to_opposite_mul_action_with_zero R} /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_module [semiring R] [semiring S] (f : R →+* S) : module R S := module.comp_hom S f /-- The tautological action by `R →+* R` on `R`. This generalizes `function.End.apply_mul_action`. -/ instance ring_hom.apply_distrib_mul_action [semiring R] : distrib_mul_action (R →+* R) R := { smul := ($), smul_zero := ring_hom.map_zero, smul_add := ring_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma ring_hom.smul_def [semiring R] (f : R →+* R) (a : R) : f • a = f a := rfl /-- `ring_hom.apply_distrib_mul_action` is faithful. -/ instance ring_hom.apply_has_faithful_smul [semiring R] : has_faithful_smul (R →+* R) R := ⟨ring_hom.ext⟩ section add_comm_monoid variables [semiring R] [add_comm_monoid M] [module R M] section variables (R) /-- `nsmul` is equal to any other module structure via a cast. -/ lemma nsmul_eq_smul_cast (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { rw [nat.succ_eq_add_one, nat.cast_succ, add_smul, add_smul, one_smul, ih, one_smul], } end end /-- Convert back any exotic `ℕ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_monoid`s should normally have exactly one `ℕ`-module structure by design. -/ lemma nat_smul_eq_nsmul (h : module ℕ M) (n : ℕ) (x : M) : @has_smul.smul ℕ M h.to_has_smul n x = n • x := by rw [nsmul_eq_smul_cast ℕ n x, nat.cast_id] /-- All `ℕ`-module structures are equal. Not an instance since in mathlib all `add_comm_monoid` should normally have exactly one `ℕ`-module structure by design. -/ def add_comm_monoid.nat_module.unique : unique (module ℕ M) := { default := by apply_instance, uniq := λ P, module.ext' P _ $ λ n, nat_smul_eq_nsmul P n } instance add_comm_monoid.nat_is_scalar_tower : is_scalar_tower ℕ R M := { smul_assoc := λ n x y, nat.rec_on n (by simp only [zero_smul]) (λ n ih, by simp only [nat.succ_eq_add_one, add_smul, one_smul, ih]) } end add_comm_monoid section add_comm_group variables [semiring S] [ring R] [add_comm_group M] [module S M] [module R M] section variables (R) /-- `zsmul` is equal to any other module structure via a cast. -/ lemma zsmul_eq_smul_cast (n : ℤ) (b : M) : n • b = (n : R) • b := have (smul_add_hom ℤ M).flip b = ((smul_add_hom R M).flip b).comp (int.cast_add_hom R), by { ext, simp }, add_monoid_hom.congr_fun this n end /-- Convert back any exotic `ℤ`-smul to the canonical instance. This should not be needed since in mathlib all `add_comm_group`s should normally have exactly one `ℤ`-module structure by design. -/ lemma int_smul_eq_zsmul (h : module ℤ M) (n : ℤ) (x : M) : @has_smul.smul ℤ M h.to_has_smul n x = n • x := by rw [zsmul_eq_smul_cast ℤ n x, int.cast_id] /-- All `ℤ`-module structures are equal. Not an instance since in mathlib all `add_comm_group` should normally have exactly one `ℤ`-module structure by design. -/ def add_comm_group.int_module.unique : unique (module ℤ M) := { default := by apply_instance, uniq := λ P, module.ext' P _ $ λ n, int_smul_eq_zsmul P n } end add_comm_group lemma map_int_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [ring R] [ring S] [module R M] [module S M₂] (x : ℤ) (a : M) : f ((x : R) • a) = (x : S) • f a := by simp only [←zsmul_eq_smul_cast, map_zsmul] lemma map_nat_cast_smul [add_comm_monoid M] [add_comm_monoid M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [semiring R] [semiring S] [module R M] [module S M₂] (x : ℕ) (a : M) : f ((x : R) • a) = (x : S) • f a := by simp only [←nsmul_eq_smul_cast, map_nsmul] lemma map_inv_int_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [division_ring R] [division_ring S] [module R M] [module S M₂] (n : ℤ) (x : M) : f ((n⁻¹ : R) • x) = (n⁻¹ : S) • f x := begin by_cases hR : (n : R) = 0; by_cases hS : (n : S) = 0, { simp [hR, hS] }, { suffices : ∀ y, f y = 0, by simp [this], clear x, intro x, rw [← inv_smul_smul₀ hS (f x), ← map_int_cast_smul f R S], simp [hR] }, { suffices : ∀ y, f y = 0, by simp [this], clear x, intro x, rw [← smul_inv_smul₀ hR x, map_int_cast_smul f R S, hS, zero_smul] }, { rw [← inv_smul_smul₀ hS (f _), ← map_int_cast_smul f R S, smul_inv_smul₀ hR] } end lemma map_inv_nat_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [division_ring R] [division_ring S] [module R M] [module S M₂] (n : ℕ) (x : M) : f ((n⁻¹ : R) • x) = (n⁻¹ : S) • f x := by exact_mod_cast map_inv_int_cast_smul f R S n x lemma map_rat_cast_smul [add_comm_group M] [add_comm_group M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (R S : Type*) [division_ring R] [division_ring S] [module R M] [module S M₂] (c : ℚ) (x : M) : f ((c : R) • x) = (c : S) • f x := by rw [rat.cast_def, rat.cast_def, div_eq_mul_inv, div_eq_mul_inv, mul_smul, mul_smul, map_int_cast_smul f R S, map_inv_nat_cast_smul f R S] lemma map_rat_smul [add_comm_group M] [add_comm_group M₂] [module ℚ M] [module ℚ M₂] {F : Type*} [add_monoid_hom_class F M M₂] (f : F) (c : ℚ) (x : M) : f (c • x) = c • f x := rat.cast_id c ▸ map_rat_cast_smul f ℚ ℚ c x /-- There can be at most one `module ℚ E` structure on an additive commutative group. -/ instance subsingleton_rat_module (E : Type*) [add_comm_group E] : subsingleton (module ℚ E) := ⟨λ P Q, module.ext' P Q $ λ r x, @map_rat_smul _ _ _ _ P Q _ _ (add_monoid_hom.id E) r x⟩ /-- If `E` is a vector space over two division rings `R` and `S`, then scalar multiplications agree on inverses of integer numbers in `R` and `S`. -/ lemma inv_int_cast_smul_eq {E : Type*} (R S : Type*) [add_comm_group E] [division_ring R] [division_ring S] [module R E] [module S E] (n : ℤ) (x : E) : (n⁻¹ : R) • x = (n⁻¹ : S) • x := map_inv_int_cast_smul (add_monoid_hom.id E) R S n x /-- If `E` is a vector space over two division rings `R` and `S`, then scalar multiplications agree on inverses of natural numbers in `R` and `S`. -/ lemma inv_nat_cast_smul_eq {E : Type*} (R S : Type*) [add_comm_group E] [division_ring R] [division_ring S] [module R E] [module S E] (n : ℕ) (x : E) : (n⁻¹ : R) • x = (n⁻¹ : S) • x := map_inv_nat_cast_smul (add_monoid_hom.id E) R S n x /-- If `E` is a vector space over a division rings `R` and has a monoid action by `α`, then that action commutes by scalar multiplication of inverses of integers in `R` -/ lemma inv_int_cast_smul_comm {α E : Type*} (R : Type*) [add_comm_group E] [division_ring R] [monoid α] [module R E] [distrib_mul_action α E] (n : ℤ) (s : α) (x : E) : (n⁻¹ : R) • s • x = s • (n⁻¹ : R) • x := (map_inv_int_cast_smul (distrib_mul_action.to_add_monoid_hom E s) R R n x).symm /-- If `E` is a vector space over a division rings `R` and has a monoid action by `α`, then that action commutes by scalar multiplication of inverses of natural numbers in `R`. -/ lemma inv_nat_cast_smul_comm {α E : Type*} (R : Type*) [add_comm_group E] [division_ring R] [monoid α] [module R E] [distrib_mul_action α E] (n : ℕ) (s : α) (x : E) : (n⁻¹ : R) • s • x = s • (n⁻¹ : R) • x := (map_inv_nat_cast_smul (distrib_mul_action.to_add_monoid_hom E s) R R n x).symm /-- If `E` is a vector space over two division rings `R` and `S`, then scalar multiplications agree on rational numbers in `R` and `S`. -/ lemma rat_cast_smul_eq {E : Type*} (R S : Type*) [add_comm_group E] [division_ring R] [division_ring S] [module R E] [module S E] (r : ℚ) (x : E) : (r : R) • x = (r : S) • x := map_rat_cast_smul (add_monoid_hom.id E) R S r x instance add_comm_group.int_is_scalar_tower {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M]: is_scalar_tower ℤ R M := { smul_assoc := λ n x y, ((smul_add_hom R M).flip y).map_zsmul x n } instance is_scalar_tower.rat {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] [module ℚ R] [module ℚ M] : is_scalar_tower ℚ R M := { smul_assoc := λ r x y, map_rat_smul ((smul_add_hom R M).flip y) r x } instance smul_comm_class.rat {R : Type u} {M : Type v} [semiring R] [add_comm_group M] [module R M] [module ℚ M] : smul_comm_class ℚ R M := { smul_comm := λ r x y, (map_rat_smul (smul_add_hom R M x) r y).symm } instance smul_comm_class.rat' {R : Type u} {M : Type v} [semiring R] [add_comm_group M] [module R M] [module ℚ M] : smul_comm_class R ℚ M := smul_comm_class.symm _ _ _ section no_zero_smul_divisors /-! ### `no_zero_smul_divisors` This section defines the `no_zero_smul_divisors` class, and includes some tests for the vanishing of elements (especially in modules over division rings). -/ /-- `no_zero_smul_divisors R M` states that a scalar multiple is `0` only if either argument is `0`. This a version of saying that `M` is torsion free, without assuming `R` is zero-divisor free. The main application of `no_zero_smul_divisors R M`, when `M` is a module, is the result `smul_eq_zero`: a scalar multiple is `0` iff either argument is `0`. It is a generalization of the `no_zero_divisors` class to heterogeneous multiplication. -/ class no_zero_smul_divisors (R M : Type*) [has_zero R] [has_zero M] [has_smul R M] : Prop := (eq_zero_or_eq_zero_of_smul_eq_zero : ∀ {c : R} {x : M}, c • x = 0 → c = 0 ∨ x = 0) export no_zero_smul_divisors (eq_zero_or_eq_zero_of_smul_eq_zero) /-- Pullback a `no_zero_smul_divisors` instance along an injective function. -/ lemma function.injective.no_zero_smul_divisors {R M N : Type*} [has_zero R] [has_zero M] [has_zero N] [has_smul R M] [has_smul R N] [no_zero_smul_divisors R N] (f : M → N) (hf : function.injective f) (h0 : f 0 = 0) (hs : ∀ (c : R) (x : M), f (c • x) = c • f x) : no_zero_smul_divisors R M := ⟨λ c m h, or.imp_right (@hf _ _) $ h0.symm ▸ eq_zero_or_eq_zero_of_smul_eq_zero (by rw [←hs, h, h0])⟩ @[priority 100] -- See note [lower instance priority] instance no_zero_divisors.to_no_zero_smul_divisors [has_zero R] [has_mul R] [no_zero_divisors R] : no_zero_smul_divisors R R := ⟨λ c x, eq_zero_or_eq_zero_of_mul_eq_zero⟩ lemma smul_ne_zero [has_zero R] [has_zero M] [has_smul R M] [no_zero_smul_divisors R M] {c : R} {x : M} (hc : c ≠ 0) (hx : x ≠ 0) : c • x ≠ 0 := λ h, (eq_zero_or_eq_zero_of_smul_eq_zero h).elim hc hx section smul_with_zero variables [has_zero R] [has_zero M] [smul_with_zero R M] [no_zero_smul_divisors R M] {c : R} {x : M} @[simp] lemma smul_eq_zero : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨eq_zero_or_eq_zero_of_smul_eq_zero, λ h, h.elim (λ h, h.symm ▸ zero_smul R x) (λ h, h.symm ▸ smul_zero c)⟩ lemma smul_ne_zero_iff : c • x ≠ 0 ↔ c ≠ 0 ∧ x ≠ 0 := by rw [ne.def, smul_eq_zero, not_or_distrib] end smul_with_zero section module variables [semiring R] [add_comm_monoid M] [module R M] section nat variables (R) (M) [no_zero_smul_divisors R M] [char_zero R] include R lemma nat.no_zero_smul_divisors : no_zero_smul_divisors ℕ M := ⟨by { intros c x, rw [nsmul_eq_smul_cast R, smul_eq_zero], simp }⟩ @[simp] lemma two_nsmul_eq_zero {v : M} : 2 • v = 0 ↔ v = 0 := by { haveI := nat.no_zero_smul_divisors R M, simp [smul_eq_zero] } end nat variables (R M) /-- If `M` is an `R`-module with one and `M` has characteristic zero, then `R` has characteristic zero as well. Usually `M` is an `R`-algebra. -/ lemma char_zero.of_module (M) [add_comm_monoid_with_one M] [char_zero M] [module R M] : char_zero R := begin refine ⟨λ m n h, @nat.cast_injective M _ _ _ _ _⟩, rw [← nsmul_one, ← nsmul_one, nsmul_eq_smul_cast R m (1 : M), nsmul_eq_smul_cast R n (1 : M), h] end end module section add_comm_group -- `R` can still be a semiring here variables [semiring R] [add_comm_group M] [module R M] section smul_injective variables (M) lemma smul_right_injective [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) : function.injective ((•) c : M → M) := (injective_iff_map_eq_zero (smul_add_hom R M c)).2 $ λ a ha, (smul_eq_zero.mp ha).resolve_left hc variables {M} lemma smul_right_inj [no_zero_smul_divisors R M] {c : R} (hc : c ≠ 0) {x y : M} : c • x = c • y ↔ x = y := (smul_right_injective M hc).eq_iff end smul_injective section nat variables (R M) [no_zero_smul_divisors R M] [char_zero R] include R lemma self_eq_neg {v : M} : v = - v ↔ v = 0 := by rw [← two_nsmul_eq_zero R M, two_smul, add_eq_zero_iff_eq_neg] lemma neg_eq_self {v : M} : - v = v ↔ v = 0 := by rw [eq_comm, self_eq_neg R M] lemma self_ne_neg {v : M} : v ≠ -v ↔ v ≠ 0 := (self_eq_neg R M).not lemma neg_ne_self {v : M} : -v ≠ v ↔ v ≠ 0 := (neg_eq_self R M).not end nat end add_comm_group section module variables [ring R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] section smul_injective variables (R) lemma smul_left_injective {x : M} (hx : x ≠ 0) : function.injective (λ (c : R), c • x) := λ c d h, sub_eq_zero.mp ((smul_eq_zero.mp (calc (c - d) • x = c • x - d • x : sub_smul c d x ... = 0 : sub_eq_zero.mpr h)).resolve_right hx) end smul_injective end module section group_with_zero variables [group_with_zero R] [add_monoid M] [distrib_mul_action R M] /-- This instance applies to `division_semiring`s, in particular `nnreal` and `nnrat`. -/ @[priority 100] -- see note [lower instance priority] instance group_with_zero.to_no_zero_smul_divisors : no_zero_smul_divisors R M := ⟨λ c x h, or_iff_not_imp_left.2 $ λ hc, (smul_eq_zero_iff_eq' hc).1 h⟩ end group_with_zero @[priority 100] -- see note [lower instance priority] instance rat_module.no_zero_smul_divisors [add_comm_group M] [module ℚ M] : no_zero_smul_divisors ℤ M := ⟨λ k x h, by simpa [zsmul_eq_smul_cast ℚ k x] using h⟩ end no_zero_smul_divisors @[simp] lemma nat.smul_one_eq_coe {R : Type*} [semiring R] (m : ℕ) : m • (1 : R) = ↑m := by rw [nsmul_eq_mul, mul_one] @[simp] lemma int.smul_one_eq_coe {R : Type*} [ring R] (m : ℤ) : m • (1 : R) = ↑m := by rw [zsmul_eq_mul, mul_one] assert_not_exists multiset
51dce3b91ac8b05b3456f6493290f41289fde3b3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed/field/basic.lean
ea3f874e13211330c292b80aaf5c5fc2f5b79650
[ "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
44,036
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.algebra.subalgebra.basic import analysis.normed.group.infinite_sum import topology.algebra.module.basic import topology.instances.ennreal import topology.instances.rat /-! # Normed fields In this file we define (semi)normed rings and fields. We also prove some theorems about these definitions. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} open filter metric open_locale topological_space big_operators nnreal ennreal uniformity pointwise /-- A non-unital seminormed ring is a not-necessarily-unital ring endowed with a seminorm which satisfies the inequality `‖x y‖ ≤ ‖x‖ ‖y‖`. -/ class non_unital_semi_normed_ring (α : Type*) extends has_norm α, non_unital_ring α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A seminormed ring is a ring endowed with a seminorm which satisfies the inequality `‖x y‖ ≤ ‖x‖ ‖y‖`. -/ class semi_normed_ring (α : Type*) extends has_norm α, ring α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A seminormed ring is a non-unital seminormed ring. -/ @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring.to_non_unital_semi_normed_ring [β : semi_normed_ring α] : non_unital_semi_normed_ring α := { ..β } /-- A non-unital normed ring is a not-necessarily-unital ring endowed with a norm which satisfies the inequality `‖x y‖ ≤ ‖x‖ ‖y‖`. -/ class non_unital_normed_ring (α : Type*) extends has_norm α, non_unital_ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A non-unital normed ring is a non-unital seminormed ring. -/ @[priority 100] -- see Note [lower instance priority] instance non_unital_normed_ring.to_non_unital_semi_normed_ring [β : non_unital_normed_ring α] : non_unital_semi_normed_ring α := { ..β } /-- A normed ring is a ring endowed with a norm which satisfies the inequality `‖x y‖ ≤ ‖x‖ ‖y‖`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed division ring is a division ring endowed with a seminorm which satisfies the equality `‖x y‖ = ‖x‖ ‖y‖`. -/ class normed_division_ring (α : Type*) extends has_norm α, division_ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A normed division ring is a normed ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_division_ring.to_normed_ring [β : normed_division_ring α] : normed_ring α := { norm_mul := λ a b, (normed_division_ring.norm_mul' a b).le, ..β } /-- A normed ring is a seminormed ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_semi_normed_ring [β : normed_ring α] : semi_normed_ring α := { ..β } /-- A normed ring is a non-unital normed ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_non_unital_normed_ring [β : normed_ring α] : non_unital_normed_ring α := { ..β } /-- A seminormed commutative ring is a commutative ring endowed with a seminorm which satisfies the inequality `‖x y‖ ≤ ‖x‖ ‖y‖`. -/ class semi_normed_comm_ring (α : Type*) extends semi_normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a commutative ring endowed with a norm which satisfies the inequality `‖x y‖ ≤ ‖x‖ ‖y‖`. -/ class normed_comm_ring (α : Type*) extends normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a seminormed commutative ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_comm_ring.to_semi_normed_comm_ring [β : normed_comm_ring α] : semi_normed_comm_ring α := { ..β } instance : normed_comm_ring punit := { norm_mul := λ _ _, by simp, ..punit.normed_add_comm_group, ..punit.comm_ring, } /-- A mixin class with the axiom `‖1‖ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this axiom. -/ class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop := (norm_one : ‖(1:α)‖ = 1) export norm_one_class (norm_one) attribute [simp] norm_one @[simp] lemma nnnorm_one [seminormed_add_comm_group α] [has_one α] [norm_one_class α] : ‖(1 : α)‖₊ = 1 := nnreal.eq norm_one lemma norm_one_class.nontrivial (α : Type*) [seminormed_add_comm_group α] [has_one α] [norm_one_class α] : nontrivial α := nontrivial_of_ne 0 1 $ ne_of_apply_ne norm $ by simp @[priority 100] -- see Note [lower instance priority] instance semi_normed_comm_ring.to_comm_ring [β : semi_normed_comm_ring α] : comm_ring α := { ..β } @[priority 100] -- see Note [lower instance priority] instance non_unital_normed_ring.to_normed_add_comm_group [β : non_unital_normed_ring α] : normed_add_comm_group α := { ..β } @[priority 100] -- see Note [lower instance priority] instance non_unital_semi_normed_ring.to_seminormed_add_comm_group [non_unital_semi_normed_ring α] : seminormed_add_comm_group α := { ..‹non_unital_semi_normed_ring α› } instance [seminormed_add_comm_group α] [has_one α] [norm_one_class α] : norm_one_class (ulift α) := ⟨by simp [ulift.norm_def]⟩ instance prod.norm_one_class [seminormed_add_comm_group α] [has_one α] [norm_one_class α] [seminormed_add_comm_group β] [has_one β] [norm_one_class β] : norm_one_class (α × β) := ⟨by simp [prod.norm_def]⟩ instance pi.norm_one_class {ι : Type*} {α : ι → Type*} [nonempty ι] [fintype ι] [Π i, seminormed_add_comm_group (α i)] [Π i, has_one (α i)] [∀ i, norm_one_class (α i)] : norm_one_class (Π i, α i) := ⟨by simp [pi.norm_def, finset.sup_const finset.univ_nonempty]⟩ section non_unital_semi_normed_ring variables [non_unital_semi_normed_ring α] lemma norm_mul_le (a b : α) : (‖a*b‖) ≤ (‖a‖) * (‖b‖) := non_unital_semi_normed_ring.norm_mul _ _ lemma nnnorm_mul_le (a b : α) : ‖a * b‖₊ ≤ ‖a‖₊ * ‖b‖₊ := by simpa only [←norm_to_nnreal, ←real.to_nnreal_mul (norm_nonneg _)] using real.to_nnreal_mono (norm_mul_le _ _) lemma one_le_norm_one (β) [normed_ring β] [nontrivial β] : 1 ≤ ‖(1 : β)‖ := (le_mul_iff_one_le_left $ norm_pos_iff.mpr (one_ne_zero : (1 : β) ≠ 0)).mp (by simpa only [mul_one] using norm_mul_le (1 : β) 1) lemma one_le_nnnorm_one (β) [normed_ring β] [nontrivial β] : 1 ≤ ‖(1 : β)‖₊ := one_le_norm_one β lemma filter.tendsto.zero_mul_is_bounded_under_le {f g : ι → α} {l : filter ι} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) : tendsto (λ x, f x * g x) l (𝓝 0) := hf.op_zero_is_bounded_under_le hg (*) norm_mul_le lemma filter.is_bounded_under_le.mul_tendsto_zero {f g : ι → α} {l : filter ι} (hf : is_bounded_under (≤) l (norm ∘ f)) (hg : tendsto g l (𝓝 0)) : tendsto (λ x, f x * g x) l (𝓝 0) := hg.op_zero_is_bounded_under_le hf (flip (*)) (λ x y, ((norm_mul_le y x).trans_eq (mul_comm _ _))) /-- In a seminormed ring, the left-multiplication `add_monoid_hom` is bounded. -/ lemma mul_left_bound (x : α) : ∀ (y:α), ‖add_monoid_hom.mul_left x y‖ ≤ ‖x‖ * ‖y‖ := norm_mul_le x /-- In a seminormed ring, the right-multiplication `add_monoid_hom` is bounded. -/ lemma mul_right_bound (x : α) : ∀ (y:α), ‖add_monoid_hom.mul_right x y‖ ≤ ‖x‖ * ‖y‖ := λ y, by {rw mul_comm, convert norm_mul_le y x} instance : non_unital_semi_normed_ring (ulift α) := { norm_mul := λ x y, (norm_mul_le x.down y.down : _), .. ulift.seminormed_add_comm_group } /-- Non-unital seminormed ring structure on the product of two non-unital seminormed rings, using the sup norm. -/ instance prod.non_unital_semi_normed_ring [non_unital_semi_normed_ring β] : non_unital_semi_normed_ring (α × β) := { norm_mul := assume x y, calc ‖x * y‖ = ‖(x.1*y.1, x.2*y.2)‖ : rfl ... = (max ‖x.1*y.1‖ ‖x.2*y.2‖) : rfl ... ≤ (max (‖x.1‖*‖y.1‖) (‖x.2‖*‖y.2‖)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (‖x.1‖*‖y.1‖) (‖y.2‖*‖x.2‖)) : by simp[mul_comm] ... ≤ (max (‖x.1‖) (‖x.2‖)) * (max (‖y.2‖) (‖y.1‖)) : by apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] ... = (max (‖x.1‖) (‖x.2‖)) * (max (‖y.1‖) (‖y.2‖)) : by simp [max_comm] ... = (‖x‖*‖y‖) : rfl, ..prod.seminormed_add_comm_group } /-- Non-unital seminormed ring structure on the product of finitely many non-unital seminormed rings, using the sup norm. -/ instance pi.non_unital_semi_normed_ring {π : ι → Type*} [fintype ι] [Π i, non_unital_semi_normed_ring (π i)] : non_unital_semi_normed_ring (Π i, π i) := { norm_mul := λ x y, nnreal.coe_mono $ calc finset.univ.sup (λ i, ‖x i * y i‖₊) ≤ finset.univ.sup ((λ i, ‖x i‖₊) * (λ i, ‖y i‖₊)) : finset.sup_mono_fun $ λ b hb, norm_mul_le _ _ ... ≤ finset.univ.sup (λ i, ‖x i‖₊) * finset.univ.sup (λ i, ‖y i‖₊) : finset.sup_mul_le_mul_sup_of_nonneg _ (λ i _, zero_le _) (λ i _, zero_le _), ..pi.seminormed_add_comm_group } end non_unital_semi_normed_ring section semi_normed_ring variables [semi_normed_ring α] /-- A subalgebra of a seminormed ring is also a seminormed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.semi_normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [semi_normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : semi_normed_ring s := { norm_mul := λ a b, norm_mul_le a.1 b.1, ..s.to_submodule.seminormed_add_comm_group } /-- A subalgebra of a normed ring is also a normed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : normed_ring s := { ..s.semi_normed_ring } lemma nat.norm_cast_le : ∀ n : ℕ, ‖(n : α)‖ ≤ n * ‖(1 : α)‖ | 0 := by simp | (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul], exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl } lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ‖l.prod‖ ≤ (l.map norm).prod | [] h := (h rfl).elim | [a] _ := by simp | (a :: b :: l) _ := begin rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ‖a‖], refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)), exact list.norm_prod_le' (list.cons_ne_nil b l) end lemma list.nnnorm_prod_le' {l : list α} (hl : l ≠ []) : ‖l.prod‖₊ ≤ (l.map nnnorm).prod := (list.norm_prod_le' hl).trans_eq $ by simp [nnreal.coe_list_prod, list.map_map] lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ‖l.prod‖ ≤ (l.map norm).prod | [] := by simp | (a::l) := list.norm_prod_le' (list.cons_ne_nil a l) lemma list.nnnorm_prod_le [norm_one_class α] (l : list α) : ‖l.prod‖₊ ≤ (l.map nnnorm).prod := l.norm_prod_le.trans_eq $ by simp [nnreal.coe_list_prod, list.map_map] lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty) (f : ι → α) : ‖∏ i in s, f i‖ ≤ ∏ i in s, ‖f i‖ := begin rcases s with ⟨⟨l⟩, hl⟩, have : l.map f ≠ [], by simpa using hs, simpa using list.norm_prod_le' this end lemma finset.nnnorm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty) (f : ι → α) : ‖∏ i in s, f i‖₊ ≤ ∏ i in s, ‖f i‖₊ := (s.norm_prod_le' hs f).trans_eq $ by simp [nnreal.coe_prod] lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : ‖∏ i in s, f i‖ ≤ ∏ i in s, ‖f i‖ := begin rcases s with ⟨⟨l⟩, hl⟩, simpa using (l.map f).norm_prod_le end lemma finset.nnnorm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : ‖∏ i in s, f i‖₊ ≤ ∏ i in s, ‖f i‖₊ := (s.norm_prod_le f).trans_eq $ by simp [nnreal.coe_prod] /-- If `α` is a seminormed ring, then `‖a ^ n‖₊ ≤ ‖a‖₊ ^ n` for `n > 0`. See also `nnnorm_pow_le`. -/ lemma nnnorm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ‖a ^ n‖₊ ≤ ‖a‖₊ ^ n | 1 h := by simp only [pow_one] | (n + 2) h := by simpa only [pow_succ _ (n + 1)] using le_trans (nnnorm_mul_le _ _) (mul_le_mul_left' (nnnorm_pow_le' n.succ_pos) _) /-- If `α` is a seminormed ring with `‖1‖₊ = 1`, then `‖a ^ n‖₊ ≤ ‖a‖₊ ^ n`. See also `nnnorm_pow_le'`.-/ lemma nnnorm_pow_le [norm_one_class α] (a : α) (n : ℕ) : ‖a ^ n‖₊ ≤ ‖a‖₊ ^ n := nat.rec_on n (by simp only [pow_zero, nnnorm_one]) (λ k hk, nnnorm_pow_le' a k.succ_pos) /-- If `α` is a seminormed ring, then `‖a ^ n‖ ≤ ‖a‖ ^ n` for `n > 0`. See also `norm_pow_le`. -/ lemma norm_pow_le' (a : α) {n : ℕ} (h : 0 < n) : ‖a ^ n‖ ≤ ‖a‖ ^ n := by simpa only [nnreal.coe_pow, coe_nnnorm] using nnreal.coe_mono (nnnorm_pow_le' a h) /-- If `α` is a seminormed ring with `‖1‖ = 1`, then `‖a ^ n‖ ≤ ‖a‖ ^ n`. See also `norm_pow_le'`.-/ lemma norm_pow_le [norm_one_class α] (a : α) (n : ℕ) : ‖a ^ n‖ ≤ ‖a‖ ^ n := nat.rec_on n (by simp only [pow_zero, norm_one]) (λ n hn, norm_pow_le' a n.succ_pos) lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ‖a ^ n‖ ≤ ‖a‖ ^ n := eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩ instance : semi_normed_ring (ulift α) := { .. ulift.non_unital_semi_normed_ring, .. ulift.seminormed_add_comm_group } /-- Seminormed ring structure on the product of two seminormed rings, using the sup norm. -/ instance prod.semi_normed_ring [semi_normed_ring β] : semi_normed_ring (α × β) := { ..prod.non_unital_semi_normed_ring, ..prod.seminormed_add_comm_group, } /-- Seminormed ring structure on the product of finitely many seminormed rings, using the sup norm. -/ instance pi.semi_normed_ring {π : ι → Type*} [fintype ι] [Π i, semi_normed_ring (π i)] : semi_normed_ring (Π i, π i) := { ..pi.non_unital_semi_normed_ring, ..pi.seminormed_add_comm_group, } end semi_normed_ring section non_unital_normed_ring variables [non_unital_normed_ring α] instance : non_unital_normed_ring (ulift α) := { .. ulift.non_unital_semi_normed_ring, .. ulift.seminormed_add_comm_group } /-- Non-unital normed ring structure on the product of two non-unital normed rings, using the sup norm. -/ instance prod.non_unital_normed_ring [non_unital_normed_ring β] : non_unital_normed_ring (α × β) := { norm_mul := norm_mul_le, ..prod.seminormed_add_comm_group } /-- Normed ring structure on the product of finitely many non-unital normed rings, using the sup norm. -/ instance pi.non_unital_normed_ring {π : ι → Type*} [fintype ι] [Π i, non_unital_normed_ring (π i)] : non_unital_normed_ring (Π i, π i) := { norm_mul := norm_mul_le, ..pi.normed_add_comm_group } end non_unital_normed_ring section normed_ring variables [normed_ring α] lemma units.norm_pos [nontrivial α] (x : αˣ) : 0 < ‖(x:α)‖ := norm_pos_iff.mpr (units.ne_zero x) lemma units.nnnorm_pos [nontrivial α] (x : αˣ) : 0 < ‖(x:α)‖₊ := x.norm_pos instance : normed_ring (ulift α) := { .. ulift.semi_normed_ring, .. ulift.normed_add_comm_group } /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring β] : normed_ring (α × β) := { norm_mul := norm_mul_le, ..prod.normed_add_comm_group } /-- Normed ring structure on the product of finitely many normed rings, using the sup norm. -/ instance pi.normed_ring {π : ι → Type*} [fintype ι] [Π i, normed_ring (π i)] : normed_ring (Π i, π i) := { norm_mul := norm_mul_le, ..pi.normed_add_comm_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring_top_monoid [non_unital_semi_normed_ring α] : has_continuous_mul α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ begin have : ∀ e : α × α, ‖e.1 * e.2 - x.1 * x.2‖ ≤ ‖e.1‖ * ‖e.2 - x.2‖ + ‖e.1 - x.1‖ * ‖x.2‖, { intro e, calc ‖e.1 * e.2 - x.1 * x.2‖ ≤ ‖e.1 * (e.2 - x.2) + (e.1 - x.1) * x.2‖ : by rw [mul_sub, sub_mul, sub_add_sub_cancel] ... ≤ ‖e.1‖ * ‖e.2 - x.2‖ + ‖e.1 - x.1‖ * ‖x.2‖ : norm_add_le_of_le (norm_mul_le _ _) (norm_mul_le _ _) }, refine squeeze_zero (λ e, norm_nonneg _) this _, convert ((continuous_fst.tendsto x).norm.mul ((continuous_snd.tendsto x).sub tendsto_const_nhds).norm).add (((continuous_fst.tendsto x).sub tendsto_const_nhds).norm.mul _), show tendsto _ _ _, from tendsto_const_nhds, simp end ⟩ /-- A seminormed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance semi_normed_top_ring [non_unital_semi_normed_ring α] : topological_ring α := { } section normed_division_ring variables [normed_division_ring α] @[simp] lemma norm_mul (a b : α) : ‖a * b‖ = ‖a‖ * ‖b‖ := normed_division_ring.norm_mul' a b @[priority 900] instance normed_division_ring.to_norm_one_class : norm_one_class α := ⟨mul_left_cancel₀ (mt norm_eq_zero.1 (one_ne_zero' α)) $ by rw [← norm_mul, mul_one, mul_one]⟩ @[simp] lemma nnnorm_mul (a b : α) : ‖a * b‖₊ = ‖a‖₊ * ‖b‖₊ := nnreal.eq $ norm_mul a b /-- `norm` as a `monoid_with_zero_hom`. -/ @[simps] def norm_hom : α →*₀ ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩ /-- `nnnorm` as a `monoid_with_zero_hom`. -/ @[simps] def nnnorm_hom : α →*₀ ℝ≥0 := ⟨nnnorm, nnnorm_zero, nnnorm_one, nnnorm_mul⟩ @[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ‖a ^ n‖ = ‖a‖ ^ n := (norm_hom.to_monoid_hom : α →* ℝ).map_pow a @[simp] lemma nnnorm_pow (a : α) (n : ℕ) : ‖a ^ n‖₊ = ‖a‖₊ ^ n := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_pow a n protected lemma list.norm_prod (l : list α) : ‖l.prod‖ = (l.map norm).prod := (norm_hom.to_monoid_hom : α →* ℝ).map_list_prod _ protected lemma list.nnnorm_prod (l : list α) : ‖l.prod‖₊ = (l.map nnnorm).prod := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_list_prod _ @[simp] lemma norm_div (a b : α) : ‖a / b‖ = ‖a‖ / ‖b‖ := map_div₀ (norm_hom : α →*₀ ℝ) a b @[simp] lemma nnnorm_div (a b : α) : ‖a / b‖₊ = ‖a‖₊ / ‖b‖₊ := map_div₀ (nnnorm_hom : α →*₀ ℝ≥0) a b @[simp] lemma norm_inv (a : α) : ‖a⁻¹‖ = ‖a‖⁻¹ := map_inv₀ (norm_hom : α →*₀ ℝ) a @[simp] lemma nnnorm_inv (a : α) : ‖a⁻¹‖₊ = ‖a‖₊⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_zpow : ∀ (a : α) (n : ℤ), ‖a^n‖ = ‖a‖^n := map_zpow₀ (norm_hom : α →*₀ ℝ) @[simp] lemma nnnorm_zpow : ∀ (a : α) (n : ℤ), ‖a ^ n‖₊ = ‖a‖₊ ^ n := map_zpow₀ (nnnorm_hom : α →*₀ ℝ≥0) /-- Multiplication on the left by a nonzero element of a normed division ring tends to infinity at infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`. -/ lemma filter.tendsto_mul_left_cobounded {a : α} (ha : a ≠ 0) : tendsto ((*) a) (comap norm at_top) (comap norm at_top) := by simpa only [tendsto_comap_iff, (∘), norm_mul] using tendsto_const_nhds.mul_at_top (norm_pos_iff.2 ha) tendsto_comap /-- Multiplication on the right by a nonzero element of a normed division ring tends to infinity at infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`. -/ lemma filter.tendsto_mul_right_cobounded {a : α} (ha : a ≠ 0) : tendsto (λ x, x * a) (comap norm at_top) (comap norm at_top) := by simpa only [tendsto_comap_iff, (∘), norm_mul] using tendsto_comap.at_top_mul (norm_pos_iff.2 ha) tendsto_const_nhds @[priority 100] -- see Note [lower instance priority] instance normed_division_ring.to_has_continuous_inv₀ : has_continuous_inv₀ α := begin refine ⟨λ r r0, tendsto_iff_norm_tendsto_zero.2 _⟩, have r0' : 0 < ‖r‖ := norm_pos_iff.2 r0, rcases exists_between r0' with ⟨ε, ε0, εr⟩, have : ∀ᶠ e in 𝓝 r, ‖e⁻¹ - r⁻¹‖ ≤ ‖r - e‖ / ‖r‖ / ε, { filter_upwards [(is_open_lt continuous_const continuous_norm).eventually_mem εr] with e he, have e0 : e ≠ 0 := norm_pos_iff.1 (ε0.trans he), calc ‖e⁻¹ - r⁻¹‖ = ‖r‖⁻¹ * ‖r - e‖ * ‖e‖⁻¹ : by { rw [←norm_inv, ←norm_inv, ←norm_mul, ←norm_mul, mul_sub, sub_mul, mul_assoc _ e, inv_mul_cancel r0, mul_inv_cancel e0, one_mul, mul_one] } ... = ‖r - e‖ / ‖r‖ / ‖e‖ : by field_simp [mul_comm] ... ≤ ‖r - e‖ / ‖r‖ / ε : div_le_div_of_le_left (div_nonneg (norm_nonneg _) (norm_nonneg _)) ε0 he.le }, refine squeeze_zero' (eventually_of_forall $ λ _, norm_nonneg _) this _, refine (continuous_const.sub continuous_id).norm.div_const.div_const.tendsto' _ _ _, simp, end lemma norm_one_of_pow_eq_one {x : α} {k : ℕ+} (h : x ^ (k : ℕ) = 1) : ‖x‖ = 1 := begin rw ( _ : ‖x‖ = 1 ↔ ‖x‖₊ = 1), apply (@pow_left_inj nnreal _ _ _ ↑k zero_le' zero_le' (pnat.pos k)).mp, { rw [← nnnorm_pow, one_pow, h, nnnorm_one], }, { exact subtype.mk_eq_mk.symm, }, end lemma norm_map_one_of_pow_eq_one [comm_monoid β] (φ : β →* α) {x : β} {k : ℕ+} (h : x ^ (k : ℕ) = 1) : ‖φ x‖ = 1 := begin have : (φ x) ^ (k : ℕ) = 1 := by rw [← monoid_hom.map_pow, h, monoid_hom.map_one], exact norm_one_of_pow_eq_one this, end end normed_division_ring /-- A normed field is a field with a norm satisfying ‖x y‖ = ‖x‖ ‖y‖. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nontrivially normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nontrivially_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃ x : α, 1 < ‖x‖) /-- A densely normed field is a normed field for which the image of the norm is dense in `ℝ≥0`, which means it is also nontrivially normed. However, not all nontrivally normed fields are densely normed; in particular, the `padic`s exhibit this fact. -/ class densely_normed_field (α : Type*) extends normed_field α := (lt_norm_lt : ∀ x y : ℝ, 0 ≤ x → x < y → ∃ a : α, x < ‖a‖ ∧ ‖a‖ < y) section normed_field /-- A densely normed field is always a nontrivially normed field. See note [lower instance priority]. -/ @[priority 100] instance densely_normed_field.to_nontrivially_normed_field [densely_normed_field α] : nontrivially_normed_field α := { non_trivial := let ⟨a, h, _⟩ := densely_normed_field.lt_norm_lt 1 2 zero_le_one one_lt_two in ⟨a, h⟩ } variables [normed_field α] @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_division_ring : normed_division_ring α := { ..‹normed_field α› } @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_comm_ring : normed_comm_ring α := { norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› } @[simp] lemma norm_prod (s : finset β) (f : β → α) : ‖∏ b in s, f b‖ = ∏ b in s, ‖f b‖ := (norm_hom.to_monoid_hom : α →* ℝ).map_prod f s @[simp] lemma nnnorm_prod (s : finset β) (f : β → α) : ‖∏ b in s, f b‖₊ = ∏ b in s, ‖f b‖₊ := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_prod f s end normed_field namespace normed_field section nontrivially variables (α) [nontrivially_normed_field α] lemma exists_one_lt_norm : ∃x : α, 1 < ‖x‖ := ‹nontrivially_normed_field α›.non_trivial lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ‖x‖ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ‖x‖ ∧ ‖x‖ < r := let ⟨w, hw⟩ := exists_lt_norm α r⁻¹ in ⟨w⁻¹, by rwa [← set.mem_Ioo, norm_inv, ← set.mem_inv, set.inv_Ioo_0_left hr]⟩ lemma exists_norm_lt_one : ∃x : α, 0 < ‖x‖ ∧ ‖x‖ < 1 := exists_norm_lt α one_pos variable {α} @[instance] lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[≠] x) := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end @[instance] lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) := by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α) end nontrivially section densely variables (α) [densely_normed_field α] lemma exists_lt_norm_lt {r₁ r₂ : ℝ} (h₀ : 0 ≤ r₁) (h : r₁ < r₂) : ∃ x : α, r₁ < ‖x‖ ∧ ‖x‖ < r₂ := densely_normed_field.lt_norm_lt r₁ r₂ h₀ h lemma exists_lt_nnnorm_lt {r₁ r₂ : ℝ≥0} (h : r₁ < r₂) : ∃ x : α, r₁ < ‖x‖₊ ∧ ‖x‖₊ < r₂ := by exact_mod_cast exists_lt_norm_lt α r₁.prop h instance densely_ordered_range_norm : densely_ordered (set.range (norm : α → ℝ)) := { dense := begin rintro ⟨-, x, rfl⟩ ⟨-, y, rfl⟩ hxy, exact let ⟨z, h⟩ := exists_lt_norm_lt α (norm_nonneg _) hxy in ⟨⟨‖z‖, z, rfl⟩, h⟩, end } instance densely_ordered_range_nnnorm : densely_ordered (set.range (nnnorm : α → ℝ≥0)) := { dense := begin rintro ⟨-, x, rfl⟩ ⟨-, y, rfl⟩ hxy, exact let ⟨z, h⟩ := exists_lt_nnnorm_lt α hxy in ⟨⟨‖z‖₊, z, rfl⟩, h⟩, end } lemma dense_range_nnnorm : dense_range (nnnorm : α → ℝ≥0) := dense_of_exists_between $ λ _ _ hr, let ⟨x, h⟩ := exists_lt_nnnorm_lt α hr in ⟨‖x‖₊, ⟨x, rfl⟩, h⟩ end densely end normed_field instance : normed_comm_ring ℝ := { norm_mul := λ x y, (abs_mul x y).le, .. real.normed_add_comm_group, .. real.comm_ring } noncomputable instance : normed_field ℝ := { norm_mul' := abs_mul, .. real.normed_add_comm_group } noncomputable instance : densely_normed_field ℝ := { lt_norm_lt := λ _ _ h₀ hr, let ⟨x, h⟩ := exists_between hr in ⟨x, by rwa [real.norm_eq_abs, abs_of_nonneg (h₀.trans h.1.le)]⟩ } namespace real lemma to_nnreal_mul_nnnorm {x : ℝ} (y : ℝ) (hx : 0 ≤ x) : x.to_nnreal * ‖y‖₊ = ‖x * y‖₊ := by simp [real.to_nnreal_of_nonneg, nnnorm, norm_of_nonneg, hx] lemma nnnorm_mul_to_nnreal (x : ℝ) {y : ℝ} (hy : 0 ≤ y) : ‖x‖₊ * y.to_nnreal = ‖x * y‖₊ := by simp [real.to_nnreal_of_nonneg, nnnorm, norm_of_nonneg, hy] /-- If `E` is a nontrivial topological module over `ℝ`, then `E` has no isolated points. This is a particular case of `module.punctured_nhds_ne_bot`. -/ instance punctured_nhds_module_ne_bot {E : Type*} [add_comm_group E] [topological_space E] [has_continuous_add E] [nontrivial E] [module ℝ E] [has_continuous_smul ℝ E] (x : E) : ne_bot (𝓝[≠] x) := module.punctured_nhds_ne_bot ℝ E x end real namespace nnreal open_locale nnreal @[simp] lemma norm_eq (x : ℝ≥0) : ‖(x : ℝ)‖ = x := by rw [real.norm_eq_abs, x.abs_eq] @[simp] lemma nnnorm_eq (x : ℝ≥0) : ‖(x : ℝ)‖₊ = x := nnreal.eq $ real.norm_of_nonneg x.2 end nnreal @[simp] lemma norm_norm [seminormed_add_comm_group α] (x : α) : ‖‖x‖‖ = ‖x‖ := real.norm_of_nonneg (norm_nonneg _) @[simp] lemma nnnorm_norm [seminormed_add_comm_group α] (a : α) : ‖‖a‖‖₊ = ‖a‖₊ := by simpa [real.nnnorm_of_nonneg (norm_nonneg a)] /-- A restatement of `metric_space.tendsto_at_top` in terms of the norm. -/ lemma normed_add_comm_group.tendsto_at_top [nonempty α] [semilattice_sup α] {β : Type*} [seminormed_add_comm_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → ‖f n - b‖ < ε := (at_top_basis.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) /-- A variant of `normed_add_comm_group.tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ lemma normed_add_comm_group.tendsto_at_top' [nonempty α] [semilattice_sup α] [no_max_order α] {β : Type*} [seminormed_add_comm_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N < n → ‖f n - b‖ < ε := (at_top_basis_Ioi.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) instance : normed_comm_ring ℤ := { norm := λ n, ‖(n : ℝ)‖, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub], mul_comm := mul_comm } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ‖(m : ℝ)‖ = ‖m‖ := rfl lemma int.norm_eq_abs (n : ℤ) : ‖n‖ = |n| := rfl lemma nnreal.coe_nat_abs (n : ℤ) : (n.nat_abs : ℝ≥0) = ‖n‖₊ := nnreal.eq $ calc ((n.nat_abs : ℝ≥0) : ℝ) = (n.nat_abs : ℤ) : by simp only [int.cast_coe_nat, nnreal.coe_nat_cast] ... = |n| : by simp only [← int.abs_eq_nat_abs, int.cast_abs] ... = ‖n‖ : rfl lemma int.abs_le_floor_nnreal_iff (z : ℤ) (c : ℝ≥0) : |z| ≤ ⌊c⌋₊ ↔ ‖z‖₊ ≤ c := begin rw [int.abs_eq_nat_abs, int.coe_nat_le, nat.le_floor_iff (zero_le c)], congr', exact nnreal.coe_nat_abs z, end instance : norm_one_class ℤ := ⟨by simp [← int.norm_cast_real]⟩ instance : normed_field ℚ := { norm := λ r, ‖(r : ℝ)‖, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : densely_normed_field ℚ := { lt_norm_lt := λ r₁ r₂ h₀ hr, let ⟨q, h⟩ := exists_rat_btwn hr in ⟨q, by { unfold norm, rwa abs_of_pos (h₀.trans_lt h.1) } ⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ‖(r : ℝ)‖ = ‖r‖ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ‖(m : ℚ)‖ = ‖m‖ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast -- Now that we've installed the norm on `ℤ`, -- we can state some lemmas about `nsmul` and `zsmul`. section variables [seminormed_add_comm_group α] lemma norm_nsmul_le (n : ℕ) (a : α) : ‖n • a‖ ≤ n * ‖a‖ := begin induction n with n ih, { simp only [norm_zero, nat.cast_zero, zero_mul, zero_smul] }, simp only [nat.succ_eq_add_one, add_smul, add_mul, one_mul, nat.cast_add, nat.cast_one, one_nsmul], exact norm_add_le_of_le ih le_rfl end lemma norm_zsmul_le (n : ℤ) (a : α) : ‖n • a‖ ≤ ‖n‖ * ‖a‖ := begin induction n with n n, { simp only [int.of_nat_eq_coe, coe_nat_zsmul], convert norm_nsmul_le n a, exact nat.abs_cast n }, { simp only [int.neg_succ_of_nat_coe, neg_smul, norm_neg, coe_nat_zsmul], convert norm_nsmul_le n.succ a, exact nat.abs_cast n.succ, } end lemma nnnorm_nsmul_le (n : ℕ) (a : α) : ‖n • a‖₊ ≤ n * ‖a‖₊ := by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_nat_cast] using norm_nsmul_le n a lemma nnnorm_zsmul_le (n : ℤ) (a : α) : ‖n • a‖₊ ≤ ‖n‖₊ * ‖a‖₊ := by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul] using norm_zsmul_le n a end section cauchy_product /-! ## Multiplying two infinite sums in a normed ring In this section, we prove various results about `(∑' x : ι, f x) * (∑' y : ι', g y)` in a normed ring. There are similar results proven in `topology/algebra/infinite_sum` (e.g `tsum_mul_tsum`), but in a normed ring we get summability results which aren't true in general. We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to `β = γ = ℕ` to prove the Cauchy product formula (see `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`). ### Arbitrary index types -/ variables {ι' : Type*} [normed_ring α] open finset open_locale classical lemma summable.mul_of_nonneg {f : ι → ℝ} {g : ι' → ℝ} (hf : summable f) (hg : summable g) (hf' : 0 ≤ f) (hg' : 0 ≤ g) : summable (λ (x : ι × ι'), f x.1 * g x.2) := let ⟨s, hf⟩ := hf in let ⟨t, hg⟩ := hg in suffices this : ∀ u : finset (ι × ι'), ∑ x in u, f x.1 * g x.2 ≤ s*t, from summable_of_sum_le (λ x, mul_nonneg (hf' _) (hg' _)) this, assume u, calc ∑ x in u, f x.1 * g x.2 ≤ ∑ x in u.image prod.fst ×ˢ u.image prod.snd, f x.1 * g x.2 : sum_mono_set_of_nonneg (λ x, mul_nonneg (hf' _) (hg' _)) subset_product ... = ∑ x in u.image prod.fst, ∑ y in u.image prod.snd, f x * g y : sum_product ... = ∑ x in u.image prod.fst, f x * ∑ y in u.image prod.snd, g y : sum_congr rfl (λ x _, mul_sum.symm) ... ≤ ∑ x in u.image prod.fst, f x * t : sum_le_sum (λ x _, mul_le_mul_of_nonneg_left (sum_le_has_sum _ (λ _ _, hg' _) hg) (hf' _)) ... = (∑ x in u.image prod.fst, f x) * t : sum_mul.symm ... ≤ s * t : mul_le_mul_of_nonneg_right (sum_le_has_sum _ (λ _ _, hf' _) hf) (hg.nonneg $ λ _, hg' _) lemma summable.mul_norm {f : ι → α} {g : ι' → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : summable (λ (x : ι × ι'), ‖f x.1 * g x.2‖) := summable_of_nonneg_of_le (λ x, norm_nonneg (f x.1 * g x.2)) (λ x, norm_mul_le (f x.1) (g x.2)) (hf.mul_of_nonneg hg (λ x, norm_nonneg $ f x) (λ x, norm_nonneg $ g x) : _) lemma summable_mul_of_summable_norm [complete_space α] {f : ι → α} {g : ι' → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : summable (λ (x : ι × ι'), f x.1 * g x.2) := summable_of_summable_norm (hf.mul_norm hg) /-- Product of two infinites sums indexed by arbitrary types. See also `tsum_mul_tsum` if `f` and `g` are *not* absolutely summable. -/ lemma tsum_mul_tsum_of_summable_norm [complete_space α] {f : ι → α} {g : ι' → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : (∑' x, f x) * (∑' y, g y) = (∑' z : ι × ι', f z.1 * g z.2) := tsum_mul_tsum (summable_of_summable_norm hf) (summable_of_summable_norm hg) (summable_mul_of_summable_norm hf hg) /-! ### `ℕ`-indexed families (Cauchy product) We prove two versions of the Cauchy product formula. The first one is `tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm`, where the `n`-th term is a sum over `finset.range (n+1)` involving `nat` substraction. In order to avoid `nat` substraction, we also provide `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`, where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the `finset` `finset.nat.antidiagonal n`. -/ section nat open finset.nat lemma summable_norm_sum_mul_antidiagonal_of_summable_norm {f g : ℕ → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : summable (λ n, ‖∑ kl in antidiagonal n, f kl.1 * g kl.2‖) := begin have := summable_sum_mul_antidiagonal_of_summable_mul (summable.mul_of_nonneg hf hg (λ _, norm_nonneg _) (λ _, norm_nonneg _)), refine summable_of_nonneg_of_le (λ _, norm_nonneg _) _ this, intros n, calc ‖∑ kl in antidiagonal n, f kl.1 * g kl.2‖ ≤ ∑ kl in antidiagonal n, ‖f kl.1 * g kl.2‖ : norm_sum_le _ _ ... ≤ ∑ kl in antidiagonal n, ‖f kl.1‖ * ‖g kl.2‖ : sum_le_sum (λ i _, norm_mul_le _ _) end /-- The Cauchy product formula for the product of two infinite sums indexed by `ℕ`, expressed by summing on `finset.nat.antidiagonal`. See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal` if `f` and `g` are *not* absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm [complete_space α] {f g : ℕ → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : (∑' n, f n) * (∑' n, g n) = ∑' n, ∑ kl in antidiagonal n, f kl.1 * g kl.2 := tsum_mul_tsum_eq_tsum_sum_antidiagonal (summable_of_summable_norm hf) (summable_of_summable_norm hg) (summable_mul_of_summable_norm hf hg) lemma summable_norm_sum_mul_range_of_summable_norm {f g : ℕ → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : summable (λ n, ‖∑ k in range (n+1), f k * g (n - k)‖) := begin simp_rw ← sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact summable_norm_sum_mul_antidiagonal_of_summable_norm hf hg end /-- The Cauchy product formula for the product of two infinite sums indexed by `ℕ`, expressed by summing on `finset.range`. See also `tsum_mul_tsum_eq_tsum_sum_range` if `f` and `g` are *not* absolutely summable. -/ lemma tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm [complete_space α] {f g : ℕ → α} (hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) : (∑' n, f n) * (∑' n, g n) = ∑' n, ∑ k in range (n+1), f k * g (n - k) := begin simp_rw ← sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l), exact tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm hf hg end end nat end cauchy_product section ring_hom_isometric variables {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} /-- This class states that a ring homomorphism is isometric. This is a sufficient assumption for a continuous semilinear map to be bounded and this is the main use for this typeclass. -/ class ring_hom_isometric [semiring R₁] [semiring R₂] [has_norm R₁] [has_norm R₂] (σ : R₁ →+* R₂) : Prop := (is_iso : ∀ {x : R₁}, ‖σ x‖ = ‖x‖) attribute [simp] ring_hom_isometric.is_iso variables [semi_normed_ring R₁] [semi_normed_ring R₂] [semi_normed_ring R₃] instance ring_hom_isometric.ids : ring_hom_isometric (ring_hom.id R₁) := ⟨λ x, rfl⟩ end ring_hom_isometric /-! ### Induced normed structures -/ section induced variables {F : Type*} (R S : Type*) /-- A non-unital ring homomorphism from an `non_unital_ring` to a `non_unital_semi_normed_ring` induces a `non_unital_semi_normed_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def non_unital_semi_normed_ring.induced [non_unital_ring R] [non_unital_semi_normed_ring S] [non_unital_ring_hom_class F R S] (f : F) : non_unital_semi_normed_ring R := { norm_mul := λ x y, by { unfold norm, exact (map_mul f x y).symm ▸ norm_mul_le (f x) (f y) }, .. seminormed_add_comm_group.induced R S f } /-- An injective non-unital ring homomorphism from an `non_unital_ring` to a `non_unital_normed_ring` induces a `non_unital_normed_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def non_unital_normed_ring.induced [non_unital_ring R] [non_unital_normed_ring S] [non_unital_ring_hom_class F R S] (f : F) (hf : function.injective f) : non_unital_normed_ring R := { .. non_unital_semi_normed_ring.induced R S f, .. normed_add_comm_group.induced R S f hf } /-- A non-unital ring homomorphism from an `ring` to a `semi_normed_ring` induces a `semi_normed_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def semi_normed_ring.induced [ring R] [semi_normed_ring S] [non_unital_ring_hom_class F R S] (f : F) : semi_normed_ring R := { .. non_unital_semi_normed_ring.induced R S f, .. seminormed_add_comm_group.induced R S f } /-- An injective non-unital ring homomorphism from an `ring` to a `normed_ring` induces a `normed_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def normed_ring.induced [ring R] [normed_ring S] [non_unital_ring_hom_class F R S] (f : F) (hf : function.injective f) : normed_ring R := { .. non_unital_semi_normed_ring.induced R S f, .. normed_add_comm_group.induced R S f hf } /-- A non-unital ring homomorphism from a `comm_ring` to a `semi_normed_ring` induces a `semi_normed_comm_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def semi_normed_comm_ring.induced [comm_ring R] [semi_normed_ring S] [non_unital_ring_hom_class F R S] (f : F) : semi_normed_comm_ring R := { mul_comm := mul_comm, .. non_unital_semi_normed_ring.induced R S f, .. seminormed_add_comm_group.induced R S f } /-- An injective non-unital ring homomorphism from an `comm_ring` to a `normed_ring` induces a `normed_comm_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def normed_comm_ring.induced [comm_ring R] [normed_ring S] [non_unital_ring_hom_class F R S] (f : F) (hf : function.injective f) : normed_comm_ring R := { .. semi_normed_comm_ring.induced R S f, .. normed_add_comm_group.induced R S f hf } /-- An injective non-unital ring homomorphism from an `division_ring` to a `normed_ring` induces a `normed_division_ring` structure on the domain. See note [reducible non-instances] -/ @[reducible] def normed_division_ring.induced [division_ring R] [normed_division_ring S] [non_unital_ring_hom_class F R S] (f : F) (hf : function.injective f) : normed_division_ring R := { norm_mul' := λ x y, by { unfold norm, exact (map_mul f x y).symm ▸ norm_mul (f x) (f y) }, .. normed_add_comm_group.induced R S f hf } /-- An injective non-unital ring homomorphism from an `field` to a `normed_ring` induces a `normed_field` structure on the domain. See note [reducible non-instances] -/ @[reducible] def normed_field.induced [field R] [normed_field S] [non_unital_ring_hom_class F R S] (f : F) (hf : function.injective f) : normed_field R := { .. normed_division_ring.induced R S f hf } /-- A ring homomorphism from a `ring R` to a `semi_normed_ring S` which induces the norm structure `semi_normed_ring.induced` makes `R` satisfy `‖(1 : R)‖ = 1` whenever `‖(1 : S)‖ = 1`. -/ lemma norm_one_class.induced {F : Type*} (R S : Type*) [ring R] [semi_normed_ring S] [norm_one_class S] [ring_hom_class F R S] (f : F) : @norm_one_class R (semi_normed_ring.induced R S f).to_has_norm _ := { norm_one := (congr_arg norm (map_one f)).trans norm_one } end induced namespace subring_class variables {S R : Type*} [set_like S R] instance to_semi_normed_ring [semi_normed_ring R] [subring_class S R] (s : S) : semi_normed_ring s := semi_normed_ring.induced s R (subring_class.subtype s) instance to_normed_ring [normed_ring R] [subring_class S R] (s : S) : normed_ring s := normed_ring.induced s R (subring_class.subtype s) subtype.val_injective instance to_semi_normed_comm_ring [semi_normed_comm_ring R] [h : subring_class S R] (s : S) : semi_normed_comm_ring s := { mul_comm := mul_comm, .. subring_class.to_semi_normed_ring s } instance to_normed_comm_ring [normed_comm_ring R] [subring_class S R] (s : S) : normed_comm_ring s := { mul_comm := mul_comm, .. subring_class.to_normed_ring s } end subring_class -- Guard again import creep. assert_not_exists restrict_scalars
2fb6c0b9e25e7a94052df985ea03ea7ba41bda84
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/calculus/parametric_interval_integral.lean
f6e82e4cef6736eaa489464ba81365828e339f04
[ "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
6,494
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.calculus.parametric_integral import measure_theory.integral.interval_integral /-! # Derivatives of interval integrals depending on parameters In this file we restate theorems about derivatives of integrals depending on parameters for interval integrals. -/ open topological_space measure_theory filter metric open_locale topological_space filter interval variables {𝕜 : Type*} [is_R_or_C 𝕜] {μ : measure ℝ} {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [normed_space 𝕜 E] [complete_space E] {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {a b ε : ℝ} {bound : ℝ → ℝ} namespace interval_integral /-- Differentiation under integral of `x ↦ ∫ t in a..b, F x t` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_integral_of_dominated_loc_of_lip {F : H → ℝ → E} {F' : ℝ → (H →L[𝕜] E)} {x₀ : H} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable F' (μ.restrict (Ι a b))) (h_lip : ∀ᵐ t ∂μ, t ∈ Ι a b → lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → has_fderiv_at (λ x, F x t) (F' t) x₀) : interval_integrable F' μ a b ∧ has_fderiv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc, ← ae_restrict_iff' measurable_set_uIoc] at *, have := has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas h_lip bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_integral_of_dominated_of_fderiv_le {F : H → ℝ → E} {F' : H → ℝ → (H →L[𝕜] E)} {x₀ : H} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable (F' x₀) (μ.restrict (Ι a b))) (h_bound : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, ‖F' x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x t) (F' x t) x) : has_fderiv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' x₀ t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc, ← ae_restrict_iff' measurable_set_uIoc] at *, exact (has_fderiv_at_integral_of_dominated_of_fderiv_le ε_pos hF_meas hF_int hF'_meas h_bound bound_integrable h_diff).const_smul _ end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_integral_of_dominated_loc_of_lip {F : 𝕜 → ℝ → E} {F' : ℝ → E} {x₀ : 𝕜} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable F' (μ.restrict (Ι a b))) (h_lipsch : ∀ᵐ t ∂μ, t ∈ Ι a b → lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable (bound : ℝ → ℝ) μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → has_deriv_at (λ x, F x t) (F' t) x₀) : (interval_integrable F' μ a b) ∧ has_deriv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc, ← ae_restrict_iff' measurable_set_uIoc] at *, have := has_deriv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas h_lipsch bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_integral_of_dominated_loc_of_deriv_le {F : 𝕜 → ℝ → E} {F' : 𝕜 → ℝ → E} {x₀ : 𝕜} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable (F' x₀) (μ.restrict (Ι a b))) (h_bound : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, ‖F' x t‖ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x t) (F' x t) x) : (interval_integrable (F' x₀) μ a b) ∧ has_deriv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' x₀ t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_uIoc, ← ae_restrict_iff' measurable_set_uIoc] at *, have := has_deriv_at_integral_of_dominated_loc_of_deriv_le ε_pos hF_meas hF_int hF'_meas h_bound bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end end interval_integral
47cdfe8c6711422a2eae39b48b190ea3944e500a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/attrCmd.lean
dbf13411dd402d5082341c1d52b0a1348be08543
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
132
lean
def M := StateM Nat def f1 : M Nat := pure 0 -- failed to synthesize `Pure M` attribute [reducible] M def f2 : M Nat := pure 0
88156068deebe5f196c98f01353579adc237564a
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/tensor_algebra/basic.lean
98229da93f80286766a471a8132e83fe345f7645
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
10,849
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import algebra.free_algebra import algebra.ring_quot import algebra.triv_sq_zero_ext import algebra.algebra.operations import linear_algebra.multilinear.basic /-! # Tensor Algebras Given a commutative semiring `R`, and an `R`-module `M`, we construct the tensor algebra of `M`. This is the free `R`-algebra generated (`R`-linearly) by the module `M`. ## Notation 1. `tensor_algebra R M` is the tensor algebra itself. It is endowed with an R-algebra structure. 2. `tensor_algebra.ι R` is the canonical R-linear map `M → tensor_algebra R M`. 3. Given a linear map `f : M → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an `R`-algebra morphism `tensor_algebra R M → A`. ## Theorems 1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`. 2. `lift_unique` states that whenever an R-algebra morphism `g : tensor_algebra R M → A` is given whose composition with `ι R` is `f`, then one has `g = lift R f`. 3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem. 4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift of the composition of an algebra morphism with `ι` is the algebra morphism itself. ## Implementation details As noted above, the tensor algebra of `M` is constructed as the free `R`-algebra generated by `M`, modulo the additional relations making the inclusion of `M` into an `R`-linear map. -/ variables (R : Type*) [comm_semiring R] variables (M : Type*) [add_comm_monoid M] [module R M] namespace tensor_algebra /-- An inductively defined relation on `pre R M` used to force the initial algebra structure on the associated quotient. -/ inductive rel : free_algebra R M → free_algebra R M → Prop -- force `ι` to be linear | add {a b : M} : rel (free_algebra.ι R (a+b)) (free_algebra.ι R a + free_algebra.ι R b) | smul {r : R} {a : M} : rel (free_algebra.ι R (r • a)) (algebra_map R (free_algebra R M) r * free_algebra.ι R a) end tensor_algebra /-- The tensor algebra of the module `M` over the commutative semiring `R`. -/ @[derive [inhabited, semiring, algebra R]] def tensor_algebra := ring_quot (tensor_algebra.rel R M) namespace tensor_algebra instance {S : Type*} [comm_ring S] [module S M] : ring (tensor_algebra S M) := ring_quot.ring (rel S M) variables {M} /-- The canonical linear map `M →ₗ[R] tensor_algebra R M`. -/ @[irreducible] def ι : M →ₗ[R] (tensor_algebra R M) := { to_fun := λ m, (ring_quot.mk_alg_hom R _ (free_algebra.ι R m)), map_add' := λ x y, by { rw [←alg_hom.map_add], exact ring_quot.mk_alg_hom_rel R rel.add, }, map_smul' := λ r x, by { rw [←alg_hom.map_smul], exact ring_quot.mk_alg_hom_rel R rel.smul, } } lemma ring_quot_mk_alg_hom_free_algebra_ι_eq_ι (m : M) : ring_quot.mk_alg_hom R (rel R M) (free_algebra.ι R m) = ι R m := by { rw [ι], refl } /-- Given a linear map `f : M → A` where `A` is an `R`-algebra, `lift R f` is the unique lift of `f` to a morphism of `R`-algebras `tensor_algebra R M → A`. -/ @[irreducible, simps symm_apply] def lift {A : Type*} [semiring A] [algebra R A] : (M →ₗ[R] A) ≃ (tensor_algebra R M →ₐ[R] A) := { to_fun := ring_quot.lift_alg_hom R ∘ λ f, ⟨free_algebra.lift R ⇑f, λ x y (h : rel R M x y), by induction h; simp only [algebra.smul_def, free_algebra.lift_ι_apply, linear_map.map_smulₛₗ, ring_hom.id_apply, map_mul, alg_hom.commutes, map_add]⟩, inv_fun := λ F, F.to_linear_map.comp (ι R), left_inv := λ f, begin rw [ι], ext1 x, exact (ring_quot.lift_alg_hom_mk_alg_hom_apply _ _ _ _).trans (free_algebra.lift_ι_apply f x), end, right_inv := λ F, ring_quot.ring_quot_ext' _ _ _ $ free_algebra.hom_ext $ funext $ λ x, begin rw [ι], exact (ring_quot.lift_alg_hom_mk_alg_hom_apply _ _ _ _).trans (free_algebra.lift_ι_apply _ _) end } variables {R} @[simp] theorem ι_comp_lift {A : Type*} [semiring A] [algebra R A] (f : M →ₗ[R] A) : (lift R f).to_linear_map.comp (ι R) = f := by { convert (lift R).symm_apply_apply f, simp only [lift, equiv.coe_fn_symm_mk] } @[simp] theorem lift_ι_apply {A : Type*} [semiring A] [algebra R A] (f : M →ₗ[R] A) (x) : lift R f (ι R x) = f x := by { conv_rhs { rw ← ι_comp_lift f}, refl } @[simp] theorem lift_unique {A : Type*} [semiring A] [algebra R A] (f : M →ₗ[R] A) (g : tensor_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R f := by { rw ← (lift R).symm_apply_eq, simp only [lift, equiv.coe_fn_symm_mk] } -- Marking `tensor_algebra` irreducible makes `ring` instances inaccessible on quotients. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. @[simp] theorem lift_comp_ι {A : Type*} [semiring A] [algebra R A] (g : tensor_algebra R M →ₐ[R] A) : lift R (g.to_linear_map.comp (ι R)) = g := by { rw ←lift_symm_apply, exact (lift R).apply_symm_apply g } /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {A : Type*} [semiring A] [algebra R A] {f g : tensor_algebra R M →ₐ[R] A} (w : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g := begin rw [←lift_symm_apply, ←lift_symm_apply] at w, exact (lift R).symm.injective w, end /-- If `C` holds for the `algebra_map` of `r : R` into `tensor_algebra R M`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `tensor_algebra R M`. -/ -- This proof closely follows `free_algebra.induction` @[elab_as_eliminator] lemma induction {C : tensor_algebra R M → Prop} (h_grade0 : ∀ r, C (algebra_map R (tensor_algebra R M) r)) (h_grade1 : ∀ x, C (ι R x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : tensor_algebra R M) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from M let s : subalgebra R (tensor_algebra R M) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : M →ₗ[R] s := (ι R).cod_restrict s.to_submodule h_grade1, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (tensor_algebra R M) = s.val.comp (lift R of), { ext, simp [of], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift R of a), exact alg_hom.congr_fun of_id a, end /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : tensor_algebra R M →ₐ[R] R := lift R (0 : M →ₗ[R] R) variables (M) lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ tensor_algebra R M) := λ x, by simp [algebra_map_inv] @[simp] lemma algebra_map_inj (x y : R) : algebra_map R (tensor_algebra R M) x = algebra_map R (tensor_algebra R M) y ↔ x = y := (algebra_map_left_inverse M).injective.eq_iff @[simp] lemma algebra_map_eq_zero_iff (x : R) : algebra_map R (tensor_algebra R M) x = 0 ↔ x = 0 := map_eq_zero_iff (algebra_map _ _) (algebra_map_left_inverse _).injective @[simp] lemma algebra_map_eq_one_iff (x : R) : algebra_map R (tensor_algebra R M) x = 1 ↔ x = 1 := map_eq_one_iff (algebra_map _ _) (algebra_map_left_inverse _).injective variables {M} /-- The canonical map from `tensor_algebra R M` into `triv_sq_zero_ext R M` that sends `tensor_algebra.ι` to `triv_sq_zero_ext.inr`. -/ def to_triv_sq_zero_ext [module Rᵐᵒᵖ M] [is_central_scalar R M] : tensor_algebra R M →ₐ[R] triv_sq_zero_ext R M := lift R (triv_sq_zero_ext.inr_hom R M) @[simp] lemma to_triv_sq_zero_ext_ι (x : M) [module Rᵐᵒᵖ M] [is_central_scalar R M] : to_triv_sq_zero_ext (ι R x) = triv_sq_zero_ext.inr x := lift_ι_apply _ _ /-- The left-inverse of `ι`. As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable algebra structure. -/ def ι_inv : tensor_algebra R M →ₗ[R] M := begin letI : module Rᵐᵒᵖ M := module.comp_hom _ ((ring_hom.id R).from_opposite mul_comm), haveI : is_central_scalar R M := ⟨λ r m, rfl⟩, exact (triv_sq_zero_ext.snd_hom R M).comp to_triv_sq_zero_ext.to_linear_map end lemma ι_left_inverse : function.left_inverse ι_inv (ι R : M → tensor_algebra R M) := λ x, by simp [ι_inv] variables (R) @[simp] lemma ι_inj (x y : M) : ι R x = ι R y ↔ x = y := ι_left_inverse.injective.eq_iff @[simp] lemma ι_eq_zero_iff (x : M) : ι R x = 0 ↔ x = 0 := by rw [←ι_inj R x 0, linear_map.map_zero] variables {R} @[simp] lemma ι_eq_algebra_map_iff (x : M) (r : R) : ι R x = algebra_map R _ r ↔ x = 0 ∧ r = 0 := begin refine ⟨λ h, _, _⟩, { letI : module Rᵐᵒᵖ M := module.comp_hom _ ((ring_hom.id R).from_opposite mul_comm), haveI : is_central_scalar R M := ⟨λ r m, rfl⟩, have hf0 : to_triv_sq_zero_ext (ι R x) = (0, x), from lift_ι_apply _ _, rw [h, alg_hom.commutes] at hf0, have : r = 0 ∧ 0 = x := prod.ext_iff.1 hf0, exact this.symm.imp_left eq.symm, }, { rintro ⟨rfl, rfl⟩, rw [linear_map.map_zero, ring_hom.map_zero] } end @[simp] lemma ι_ne_one [nontrivial R] (x : M) : ι R x ≠ 1 := begin rw [←(algebra_map R (tensor_algebra R M)).map_one, ne.def, ι_eq_algebra_map_iff], exact one_ne_zero ∘ and.right, end /-- The generators of the tensor algebra are disjoint from its scalars. -/ lemma ι_range_disjoint_one : disjoint (linear_map.range (ι R : M →ₗ[R] tensor_algebra R M)) (1 : submodule R (tensor_algebra R M)) := begin rw submodule.disjoint_def, rintros _ ⟨x, hx⟩ ⟨r, (rfl : algebra_map _ _ _ = _)⟩, rw ι_eq_algebra_map_iff x at hx, rw [hx.2, ring_hom.map_zero] end variables (R M) /-- Construct a product of `n` elements of the module within the tensor algebra. See also `pi_tensor_product.tprod`. -/ def tprod (n : ℕ) : multilinear_map R (λ i : fin n, M) (tensor_algebra R M) := (multilinear_map.mk_pi_algebra_fin R n (tensor_algebra R M)).comp_linear_map $ λ _, ι R @[simp] lemma tprod_apply {n : ℕ} (x : fin n → M) : tprod R M n x = (list.of_fn (λ i, ι R (x i))).prod := rfl variables {R M} end tensor_algebra namespace free_algebra variables {R M} /-- The canonical image of the `free_algebra` in the `tensor_algebra`, which maps `free_algebra.ι R x` to `tensor_algebra.ι R x`. -/ def to_tensor : free_algebra R M →ₐ[R] tensor_algebra R M := free_algebra.lift R (tensor_algebra.ι R) @[simp] lemma to_tensor_ι (m : M) : (free_algebra.ι R m).to_tensor = tensor_algebra.ι R m := by simp [to_tensor] end free_algebra
594a41978834da9b25bf0c5d2f603c53c18808d8
649957717d58c43b5d8d200da34bf374293fe739
/src/topology/algebra/group_completion.lean
c773ac5b45cc471a4270b77d7c7530599cdf78b5
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
5,497
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Completion of topological groups: -/ import topology.uniform_space.completion topology.algebra.uniform_group noncomputable theory section group open uniform_space Cauchy filter set variables {α : Type*} [uniform_space α] instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩ instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩ instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩ -- TODO: switch sides once #1103 is fixed @[elim_cast] lemma coe_zero [has_zero α] : 0 = ((0 : α) : completion α) := rfl end group namespace uniform_space.completion section uniform_add_group open uniform_space uniform_space.completion variables {α : Type*} [uniform_space α] [add_group α] [uniform_add_group α] @[move_cast] lemma coe_neg (a : α) : ((- a : α) : completion α) = - a := (map_coe uniform_continuous_neg' a).symm @[move_cast] lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b := (map₂_coe_coe a b (+) uniform_continuous_add').symm instance : add_group (completion α) := { zero_add := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id) (assume a, show 0 + (a : completion α) = a, by rw_mod_cast zero_add), add_zero := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id) (assume a, show (a : completion α) + 0 = a, by rw_mod_cast add_zero), add_left_neg := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const) (assume a, show - (a : completion α) + a = 0, by rw_mod_cast add_left_neg), add_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_map₂ (continuous_map₂ continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous_map₂ continuous_fst (continuous_map₂ (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, show (a : completion α) + b + c = a + (b + c), by repeat { rw_mod_cast add_assoc }), .. completion.has_zero, .. completion.has_neg, ..completion.has_add } instance : uniform_add_group (completion α) := ⟨((uniform_continuous_map₂ (+)).comp (uniform_continuous.prod_mk uniform_continuous_fst (uniform_continuous_map.comp uniform_continuous_snd)) : _)⟩ instance is_add_group_hom_coe : is_add_group_hom (coe : α → completion α) := ⟨ coe_add ⟩ variables {β : Type*} [uniform_space β] [add_group β] [uniform_add_group β] lemma is_add_group_hom_extension [complete_space β] [separated β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, ⟨assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add') (continuous_add (continuous_extension.comp continuous_fst) (continuous_extension.comp continuous_snd))) (assume a b, by rw_mod_cast [extension_coe hf, extension_coe hf, extension_coe hf, is_add_group_hom.map_add f])⟩ lemma is_add_group_hom_map [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.map f) := is_add_group_hom_extension ((continuous_coe _).comp hf) section instance_max_depth -- TODO: continuous_add requires some long proofs through -- uniform_add_group / topological_add_group w.r.t prod / completion etc set_option class.instance_max_depth 52 lemma is_add_group_hom_prod [add_group β] [uniform_add_group β] : is_add_group_hom (@completion.prod α β _ _) := ⟨assume ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, begin refine completion.induction_on₄ a₁ a₂ b₁ b₂ (is_closed_eq _ _) _, { refine continuous.comp uniform_continuous_prod.continuous _ , refine continuous_add _ _, exact continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous_snd.comp continuous_fst), exact continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd) }, { refine continuous_add _ _, refine continuous.comp uniform_continuous_prod.continuous _, exact continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous_snd.comp continuous_fst), refine continuous.comp uniform_continuous_prod.continuous _, exact continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd) }, { assume a b c d, show completion.prod (↑a + ↑c, ↑b + ↑d) = completion.prod (↑a, ↑b) + completion.prod (↑c, ↑d), norm_cast } end⟩ end instance_max_depth instance {α : Type*} [uniform_space α] [add_comm_group α] [uniform_add_group α] : add_comm_group (completion α) := { add_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_snd continuous_fst)) (assume x y, by { change ↑x + ↑y = ↑y + ↑x, rw [← coe_add, ← coe_add, add_comm]}), .. completion.add_group } end uniform_add_group end uniform_space.completion
e563a1a10c181fc182f038a68b262065d4f8aec3
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/paracompact.lean
5d4f89a52e1027ce59175cdfdeec1a8c39186a3d
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,279
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Yury Kudryashov -/ import topology.subset_properties import topology.separation import data.option.basic /-! # Paracompact topological spaces A topological space `X` is said to be paracompact if every open covering of `X` admits a locally finite refinement. The definition requires that each set of the new covering is a subset of one of the sets of the initial covering. However, one can ensure that each open covering `s : ι → set X` admits a *precise* locally finite refinement, i.e., an open covering `t : ι → set X` with the same index set such that `∀ i, t i ⊆ s i`, see lemma `precise_refinement`. We also provide a convenience lemma `precise_refinement_set` that deals with open coverings of a closed subset of `X` instead of the whole space. We also prove the following facts. * Every compact space is paracompact, see instance `paracompact_of_compact`. * A locally compact sigma compact Hausdorff space is paracompact, see instance `paracompact_of_locally_compact_sigma_compact`. Moreover, we can choose a locally finite refinement with sets in a given collection of filter bases of `𝓝 x, `x : X`, see `refinement_of_locally_compact_sigma_compact_of_nhds_basis`. For example, in a proper metric space every open covering `⋃ i, s i` admits a refinement `⋃ i, metric.ball (c i) (r i)`. * Every paracompact Hausdorff space is normal. This statement is not an instance to avoid loops in the instance graph. * Every `emetric_space` is a paracompact space, see instance `emetric_space.paracompact_space` in `topology/metric_space/emetric_space`. ## TODO Prove (some of) [Michael's theorems](https://ncatlab.org/nlab/show/Michael%27s+theorem). ## Tags compact space, paracompact space, locally finite covering -/ open set filter function open_locale filter topological_space universes u v /-- A topological space is called paracompact, if every open covering of this space admits a locally finite refinement. We use the same universe for all types in the definition to avoid creating a class like `paracompact_space.{u v}`. Due to lemma `precise_refinement` below, every open covering `s : α → set X` indexed on `α : Type v` has a *precise* locally finite refinement, i.e., a locally finite refinement `t : α → set X` indexed on the same type such that each `∀ i, t i ⊆ s i`. -/ class paracompact_space (X : Type v) [topological_space X] : Prop := (locally_finite_refinement : ∀ (α : Type v) (s : α → set X) (ho : ∀ a, is_open (s a)) (hc : (⋃ a, s a) = univ), ∃ (β : Type v) (t : β → set X) (ho : ∀ b, is_open (t b)) (hc : (⋃ b, t b) = univ), locally_finite t ∧ ∀ b, ∃ a, t b ⊆ s a) variables {ι : Type u} {X : Type v} [topological_space X] /-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is, one indexed on the same type with each open set contained in the corresponding original one. -/ lemma precise_refinement [paracompact_space X] (u : ι → set X) (uo : ∀ a, is_open (u a)) (uc : (⋃ i, u i) = univ) : ∃ v : ι → set X, (∀ a, is_open (v a)) ∧ (⋃ i, v i) = univ ∧ locally_finite v ∧ (∀ a, v a ⊆ u a) := begin -- Apply definition to `range u`, then turn existence quantifiers into functions using `choose` have := paracompact_space.locally_finite_refinement (range u) coe (set_coe.forall.2 $ forall_range_iff.2 uo) (by rwa [← sUnion_range, subtype.range_coe]), simp only [set_coe.exists, subtype.coe_mk, exists_range_iff', Union_eq_univ_iff, exists_prop] at this, choose α t hto hXt htf ind hind, choose t_inv ht_inv using hXt, choose U hxU hU using htf, -- Send each `i` to the union of `t a` over `a ∈ ind ⁻¹' {i}` refine ⟨λ i, ⋃ (a : α) (ha : ind a = i), t a, _, _, _, _⟩, { exact λ a, is_open_Union (λ a, is_open_Union $ λ ha, hto a) }, { simp only [eq_univ_iff_forall, mem_Union], exact λ x, ⟨ind (t_inv x), _, rfl, ht_inv _⟩ }, { refine λ x, ⟨U x, hxU x, ((hU x).image ind).subset _⟩, simp only [subset_def, mem_Union, mem_set_of_eq, set.nonempty, mem_inter_eq], rintro i ⟨y, ⟨a, rfl, hya⟩, hyU⟩, exact mem_image_of_mem _ ⟨y, hya, hyU⟩ }, { simp only [subset_def, mem_Union], rintro i x ⟨a, rfl, hxa⟩, exact hind _ hxa } end /-- In a paracompact space, every open covering of a closed set admits a locally finite refinement indexed by the same type. -/ lemma precise_refinement_set [paracompact_space X] {s : set X} (hs : is_closed s) (u : ι → set X) (uo : ∀ i, is_open (u i)) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, (∀ i, is_open (v i)) ∧ (s ⊆ ⋃ i, v i) ∧ locally_finite v ∧ (∀ i, v i ⊆ u i) := begin rcases precise_refinement (λ i, option.elim i sᶜ u) (option.forall.2 ⟨is_open_compl_iff.2 hs, uo⟩) _ with ⟨v, vo, vc, vf, vu⟩, refine ⟨v ∘ some, λ i, vo _, _, vf.comp_injective (option.some_injective _), λ i, vu _⟩, { simp only [Union_option, ← compl_subset_iff_union] at vc, exact subset.trans (subset_compl_comm.1 $ vu option.none) vc }, { simpa only [Union_option, option.elim, ← compl_subset_iff_union, compl_compl] } end /-- A compact space is paracompact. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_compact [compact_space X] : paracompact_space X := begin -- the proof is trivial: we choose a finite subcover using compactness, and use it refine ⟨λ ι s ho hu, _⟩, rcases compact_univ.elim_finite_subcover _ ho hu.ge with ⟨T, hT⟩, have := hT, simp only [subset_def, mem_Union] at this, choose i hiT hi using λ x, this x (mem_univ x), refine ⟨(T : set ι), λ t, s t, λ t, ho _, _, locally_finite_of_fintype _, λ t, ⟨t, subset.rfl⟩⟩, rwa [Union_subtype, finset.set_bUnion_coe, ← univ_subset_iff], end /-- Let `X` be a locally compact sigma compact Hausdorff topological space, let `s` be a closed set in `X`. Suppose that for each `x ∈ s` the sets `B x : ι x → set X` with the predicate `p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `λ i, B (c i) (r i)` of `s` such that all “centers” `c i` belong to `s` and each `r i` satisfies `p (c i)`. The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a version of this lemma dealing with a covering of the whole space. In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible to choose `α = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis_set [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ι : X → Type u} {p : Π x, ι x → Prop} {B : Π x, ι x → set X} {s : set X} (hs : is_closed s) (hB : ∀ x ∈ s, (𝓝 x).has_basis (p x) (B x)) : ∃ (α : Type v) (c : α → X) (r : Π a, ι (c a)), (∀ a, c a ∈ s ∧ p (c a) (r a)) ∧ (s ⊆ ⋃ a, B (c a) (r a)) ∧ locally_finite (λ a, B (c a) (r a)) := begin classical, -- For technical reasons we prepend two empty sets to the sequence `compact_exhaustion.choice X` set K' : compact_exhaustion X := compact_exhaustion.choice X, set K : compact_exhaustion X := K'.shiftr.shiftr, set Kdiff := λ n, K (n + 1) \ interior (K n), -- Now we restate some properties of `compact_exhaustion` for `K`/`Kdiff` have hKcov : ∀ x, x ∈ Kdiff (K'.find x + 1), { intro x, simpa only [K'.find_shiftr] using diff_subset_diff_right interior_subset (K'.shiftr.mem_diff_shiftr_find x) }, have Kdiffc : ∀ n, is_compact (Kdiff n ∩ s), from λ n, ((K.is_compact _).diff is_open_interior).inter_right hs, -- Next we choose a finite covering `B (c n i) (r n i)` of each -- `Kdiff (n + 1) ∩ s` such that `B (c n i) (r n i) ∩ s` is disjoint with `K n` have : ∀ n (x : Kdiff (n + 1) ∩ s), (K n)ᶜ ∈ 𝓝 (x : X), from λ n x, is_open.mem_nhds (K.is_closed n).is_open_compl (λ hx', x.2.1.2 $ K.subset_interior_succ _ hx'), haveI : ∀ n (x : Kdiff n ∩ s), nonempty (ι x) := λ n x, (hB x x.2.2).nonempty, choose! r hrp hr using (λ n (x : Kdiff (n + 1) ∩ s), (hB x x.2.2).mem_iff.1 (this n x)), have hxr : ∀ n x (hx : x ∈ Kdiff (n + 1) ∩ s), B x (r n ⟨x, hx⟩) ∈ 𝓝 x, from λ n x hx, (hB x hx.2).mem_of_mem (hrp _ ⟨x, hx⟩), choose T hT using λ n, (Kdiffc (n + 1)).elim_nhds_subcover' _ (hxr n), set T' : Π n, set ↥(Kdiff (n + 1) ∩ s) := λ n, T n, -- Finally, we take the union of all these coverings refine ⟨Σ n, T' n, λ a, a.2, λ a, r a.1 a.2, _, _, _⟩, { rintro ⟨n, x, hx⟩, exact ⟨x.2.2, hrp _ _⟩ }, { refine (λ x hx, mem_Union.2 _), rcases mem_bUnion_iff.1 (hT _ ⟨hKcov x, hx⟩) with ⟨⟨c, hc⟩, hcT, hcx⟩, exact ⟨⟨_, ⟨c, hc⟩, hcT⟩, hcx⟩ }, { intro x, refine ⟨interior (K (K'.find x + 3)), is_open.mem_nhds is_open_interior (K.subset_interior_succ _ (hKcov x).1), _⟩, have : (⋃ k ≤ K'.find x + 2, (range $ sigma.mk k) : set (Σ n, T' n)).finite, from (finite_le_nat _).bUnion (λ k hk, finite_range _), apply this.subset, rintro ⟨k, c, hc⟩, simp only [mem_Union, mem_set_of_eq, mem_image_eq, subtype.coe_mk], rintro ⟨x, hxB : x ∈ B c (r k c), hxK⟩, refine ⟨k, _, ⟨c, hc⟩, rfl⟩, have := (mem_compl_iff _ _).1 (hr k c hxB), contrapose! this with hnk, exact K.subset hnk (interior_subset hxK) }, end /-- Let `X` be a locally compact sigma compact Hausdorff topological space. Suppose that for each `x` the sets `B x : ι x → set X` with the predicate `p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `λ i, B (c i) (r i)` of `X` such that each `r i` satisfies `p (c i)` The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis_set` for a version of this lemma dealing with a covering of a closed set. In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible to choose `α = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ι : X → Type u} {p : Π x, ι x → Prop} {B : Π x, ι x → set X} (hB : ∀ x, (𝓝 x).has_basis (p x) (B x)) : ∃ (α : Type v) (c : α → X) (r : Π a, ι (c a)), (∀ a, p (c a) (r a)) ∧ (⋃ a, B (c a) (r a)) = univ ∧ locally_finite (λ a, B (c a) (r a)) := let ⟨α, c, r, hp, hU, hfin⟩ := refinement_of_locally_compact_sigma_compact_of_nhds_basis_set is_closed_univ (λ x _, hB x) in ⟨α, c, r, λ a, (hp a).2, univ_subset_iff.1 hU, hfin⟩ /-- A locally compact sigma compact Hausdorff space is paracompact. See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a more precise statement. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_locally_compact_sigma_compact [locally_compact_space X] [sigma_compact_space X] [t2_space X] : paracompact_space X := begin refine ⟨λ α s ho hc, _⟩, choose i hi using Union_eq_univ_iff.1 hc, have : ∀ x : X, (𝓝 x).has_basis (λ t : set X, (x ∈ t ∧ is_open t) ∧ t ⊆ s (i x)) id, from λ x : X, (nhds_basis_opens x).restrict_subset (is_open.mem_nhds (ho (i x)) (hi x)), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis this with ⟨β, c, t, hto, htc, htf⟩, exact ⟨β, t, λ x, (hto x).1.2, htc, htf, λ b, ⟨i $ c b, (hto b).2⟩⟩ end /- Dieudonné‘s theorem: a paracompact Hausdorff space is normal. Formalization is based on the proof at [ncatlab](https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal). -/ lemma normal_of_paracompact_t2 [t2_space X] [paracompact_space X] : normal_space X := begin /- First we show how to go from points to a set on one side. -/ have : ∀ (s t : set X), is_closed s → is_closed t → (∀ x ∈ s, ∃ u v, is_open u ∧ is_open v ∧ x ∈ u ∧ t ⊆ v ∧ disjoint u v) → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v, { /- For each `x ∈ s` we choose open disjoint `u x ∋ x` and `v x ⊇ t`. The sets `u x` form an open covering of `s`. We choose a locally finite refinement `u' : s → set X`, then `⋃ i, u' i` and `(closure (⋃ i, u' i))ᶜ` are disjoint open neighborhoods of `s` and `t`. -/ intros s t hs ht H, choose u v hu hv hxu htv huv using set_coe.forall'.1 H, rcases precise_refinement_set hs u hu (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu _⟩) with ⟨u', hu'o, hcov', hu'fin, hsub⟩, refine ⟨⋃ i, u' i, (closure (⋃ i, u' i))ᶜ, is_open_Union hu'o, is_closed_closure.is_open_compl, hcov', _, disjoint_compl_right.mono le_rfl (compl_le_compl subset_closure)⟩, rw [hu'fin.closure_Union, compl_Union, subset_Inter_iff], refine λ i x hxt hxu, absurd (htv i hxt) (closure_minimal _ (is_closed_compl_iff.2 $ hv _) hxu), exact λ y hyu hyv, huv i ⟨hsub _ hyu, hyv⟩ }, /- Now we apply the lemma twice: first to `s` and `t`, then to `t` and each point of `s`. -/ refine ⟨λ s t hs ht hst, this s t hs ht (λ x hx, _)⟩, rcases this t {x} ht is_closed_singleton (λ y hyt, _) with ⟨v, u, hv, hu, htv, hxu, huv⟩, { exact ⟨u, v, hu, hv, singleton_subset_iff.1 hxu, htv, huv.symm⟩ }, { have : x ≠ y, by { rintro rfl, exact hst ⟨hx, hyt⟩ }, rcases t2_separation this with ⟨v, u, hv, hu, hxv, hyu, hd⟩, exact ⟨u, v, hu, hv, hyu, singleton_subset_iff.2 hxv, disjoint.symm hd.le⟩ } end
36ca3f94f708b0c3c23dc3f050ca73c87c940c56
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/types/bool.hlean
7b3453d23e84e876a08b8b3ee2c00d69a82bb155
[ "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
5,145
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Floris van Doorn Partially ported from the standard library -/ open eq eq.ops decidable namespace bool local attribute bor [reducible] local attribute band [reducible] theorem dichotomy (b : bool) : b = ff ⊎ b = tt := bool.cases_on b (sum.inl rfl) (sum.inr rfl) theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem eq_tt_of_ne_ff : Π {a : bool}, a ≠ ff → a = tt | @eq_tt_of_ne_ff tt H := rfl | @eq_tt_of_ne_ff ff H := absurd rfl H theorem eq_ff_of_ne_tt : Π {a : bool}, a ≠ tt → a = ff | @eq_ff_of_ne_tt tt H := absurd rfl H | @eq_ff_of_ne_tt ff H := rfl theorem absurd_of_eq_ff_of_eq_tt {B : Type} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := absurd (H₁⁻¹ ⬝ H₂) ff_ne_tt theorem tt_bor (a : bool) : bor tt a = tt := rfl notation a || b := bor a b theorem bor_tt (a : bool) : a || tt = tt := bool.cases_on a rfl rfl theorem ff_bor (a : bool) : ff || a = a := bool.cases_on a rfl rfl theorem bor_ff (a : bool) : a || ff = a := bool.cases_on a rfl rfl theorem bor_self (a : bool) : a || a = a := bool.cases_on a rfl rfl theorem bor.comm (a b : bool) : a || b = b || a := by cases a; repeat (cases b | reflexivity) theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) := match a with | ff := by rewrite *ff_bor | tt := by rewrite *tt_bor end theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ⊎ b = tt := bool.rec_on a (suppose ff || b = tt, have b = tt, from !ff_bor ▸ this, sum.inr this) (suppose tt || b = tt, sum.inl rfl) theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by rewrite H theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := bool.rec_on a (by rewrite H) (by rewrite H) theorem ff_band (a : bool) : ff && a = ff := rfl theorem tt_band (a : bool) : tt && a = a := bool.cases_on a rfl rfl theorem band_ff (a : bool) : a && ff = ff := bool.cases_on a rfl rfl theorem band_tt (a : bool) : a && tt = a := bool.cases_on a rfl rfl theorem band_self (a : bool) : a && a = a := bool.cases_on a rfl rfl theorem band.comm (a b : bool) : a && b = b && a := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := match a with | ff := by rewrite *ff_band | tt := by rewrite *tt_band end theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := sum.elim (dichotomy a) (suppose a = ff, absurd (calc ff = ff && b : ff_band ... = a && b : this ... = tt : H) ff_ne_tt) (suppose a = tt, this) theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := by rewrite [H₁, H₂] theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := band_elim_left (!band.comm ⬝ H) theorem bnot_bnot (a : bool) : bnot (bnot a) = a := bool.cases_on a rfl rfl theorem bnot_empty : bnot ff = tt := rfl theorem bnot_unit : bnot tt = ff := rfl theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := bool.cases_on a (by contradiction) (λ h, rfl) theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := bool.cases_on a (λ h, rfl) (by contradiction) definition bxor (x:bool) (y:bool) := cond x (bnot y) y /- HoTT-related stuff -/ open is_equiv equiv function is_trunc option unit decidable definition is_equiv_bnot [constructor] [instance] [priority 500] : is_equiv bnot := begin fapply is_equiv.mk, exact bnot, all_goals (intro b;cases b), do 6 reflexivity -- all_goals (focus (intro b;cases b;all_goals reflexivity)), end definition bnot_ne : Π(b : bool), bnot b ≠ b | bnot_ne tt := ff_ne_tt | bnot_ne ff := ne.symm ff_ne_tt definition equiv_bnot [constructor] : bool ≃ bool := equiv.mk bnot _ definition eq_bnot : bool = bool := ua equiv_bnot definition eq_bnot_ne_idp : eq_bnot ≠ idp := assume H : eq_bnot = idp, have H2 : bnot = id, from !cast_ua_fn⁻¹ ⬝ ap cast H, absurd (ap10 H2 tt) ff_ne_tt theorem is_set_bool : is_set bool := _ theorem not_is_prop_bool_eq_bool : ¬ is_prop (bool = bool) := λ H, eq_bnot_ne_idp !is_prop.elim definition bool_equiv_option_unit [constructor] : bool ≃ option unit := begin fapply equiv.MK, { intro b, cases b, exact none, exact some star}, { intro u, cases u, exact ff, exact tt}, { intro u, cases u with u, reflexivity, cases u, reflexivity}, { intro b, cases b, reflexivity, reflexivity}, end /- pointed and truncated bool -/ open pointed definition pointed_bool [instance] [constructor] : pointed bool := pointed.mk ff definition pbool [constructor] : Set* := pSet.mk' bool definition tbool [constructor] : Set := trunctype.mk bool _ notation `bool*` := pbool end bool
77110de1355feaa0835a1f893ee43dea0e846c7a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/model_theory/satisfiability.lean
c528b7d6b91599da67584e4f2f93156b23ed5199
[ "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
26,741
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 model_theory.ultraproducts import model_theory.bundled import model_theory.skolem /-! # First-Order Satisfiability This file deals with the satisfiability of first-order theories, as well as equivalence over them. ## Main Definitions * `first_order.language.Theory.is_satisfiable`: `T.is_satisfiable` indicates that `T` has a nonempty model. * `first_order.language.Theory.is_finitely_satisfiable`: `T.is_finitely_satisfiable` indicates that every finite subset of `T` is satisfiable. * `first_order.language.Theory.is_complete`: `T.is_complete` indicates that `T` is satisfiable and models each sentence or its negation. * `first_order.language.Theory.semantically_equivalent`: `T.semantically_equivalent φ ψ` indicates that `φ` and `ψ` are equivalent formulas or sentences in models of `T`. * `cardinal.categorical`: A theory is `κ`-categorical if all models of size `κ` are isomorphic. ## Main Results * The Compactness Theorem, `first_order.language.Theory.is_satisfiable_iff_is_finitely_satisfiable`, shows that a theory is satisfiable iff it is finitely satisfiable. * `first_order.language.complete_theory.is_complete`: The complete theory of a structure is complete. * `first_order.language.Theory.exists_large_model_of_infinite_model` shows that any theory with an infinite model has arbitrarily large models. * `first_order.language.Theory.exists_elementary_embedding_card_eq`: The Upward Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then `M` has an elementary extension of cardinality `κ`. ## Implementation Details * Satisfiability of an `L.Theory` `T` is defined in the minimal universe containing all the symbols of `L`. By Löwenheim-Skolem, this is equivalent to satisfiability in any universe. -/ universes u v w w' open cardinal category_theory open_locale cardinal first_order namespace first_order namespace language variables {L : language.{u v}} {T : L.Theory} {α : Type w} {n : ℕ} namespace Theory variable (T) /-- A theory is satisfiable if a structure models it. -/ def is_satisfiable : Prop := nonempty (Model.{u v (max u v)} T) /-- A theory is finitely satisfiable if all of its finite subtheories are satisfiable. -/ def is_finitely_satisfiable : Prop := ∀ (T0 : finset L.sentence), (T0 : L.Theory) ⊆ T → (T0 : L.Theory).is_satisfiable variables {T} {T' : L.Theory} lemma model.is_satisfiable (M : Type w) [n : nonempty M] [S : L.Structure M] [M ⊨ T] : T.is_satisfiable := ⟨((⊥ : substructure _ (Model.of T M)).elementary_skolem₁_reduct.to_Model T).shrink⟩ lemma is_satisfiable.mono (h : T'.is_satisfiable) (hs : T ⊆ T') : T.is_satisfiable := ⟨(Theory.model.mono (Model.is_model h.some) hs).bundled⟩ lemma is_satisfiable_empty (L : language.{u v}) : is_satisfiable (∅ : L.Theory) := ⟨default⟩ lemma is_satisfiable_of_is_satisfiable_on_Theory {L' : language.{w w'}} (φ : L →ᴸ L') (h : (φ.on_Theory T).is_satisfiable) : T.is_satisfiable := model.is_satisfiable (h.some.reduct φ) lemma is_satisfiable_on_Theory_iff {L' : language.{w w'}} {φ : L →ᴸ L'} (h : φ.injective) : (φ.on_Theory T).is_satisfiable ↔ T.is_satisfiable := begin classical, refine ⟨is_satisfiable_of_is_satisfiable_on_Theory φ, λ h', _⟩, haveI : inhabited (h'.some) := classical.inhabited_of_nonempty', exact model.is_satisfiable (h'.some.default_expansion h), end lemma is_satisfiable.is_finitely_satisfiable (h : T.is_satisfiable) : T.is_finitely_satisfiable := λ _, h.mono /-- The Compactness Theorem of first-order logic: A theory is satisfiable if and only if it is finitely satisfiable. -/ theorem is_satisfiable_iff_is_finitely_satisfiable {T : L.Theory} : T.is_satisfiable ↔ T.is_finitely_satisfiable := ⟨Theory.is_satisfiable.is_finitely_satisfiable, λ h, begin classical, set M : Π (T0 : finset T), Type (max u v) := λ T0, (h (T0.map (function.embedding.subtype (λ x, x ∈ T))) T0.map_subtype_subset).some with hM, let M' := filter.product ↑(ultrafilter.of (filter.at_top : filter (finset T))) M, haveI h' : M' ⊨ T, { refine ⟨λ φ hφ, _⟩, rw ultraproduct.sentence_realize, refine filter.eventually.filter_mono (ultrafilter.of_le _) (filter.eventually_at_top.2 ⟨{⟨φ, hφ⟩}, λ s h', Theory.realize_sentence_of_mem (s.map (function.embedding.subtype (λ x, x ∈ T))) _⟩), simp only [finset.coe_map, function.embedding.coe_subtype, set.mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], exact ⟨hφ, h' (finset.mem_singleton_self _)⟩ }, exact ⟨Model.of T M'⟩, end⟩ theorem is_satisfiable_directed_union_iff {ι : Type*} [nonempty ι] {T : ι → L.Theory} (h : directed (⊆) T) : Theory.is_satisfiable (⋃ i, T i) ↔ ∀ i, (T i).is_satisfiable := begin refine ⟨λ h' i, h'.mono (set.subset_Union _ _), λ h', _⟩, rw [is_satisfiable_iff_is_finitely_satisfiable, is_finitely_satisfiable], intros T0 hT0, obtain ⟨i, hi⟩ := h.exists_mem_subset_of_finset_subset_bUnion hT0, exact (h' i).mono hi, end theorem is_satisfiable_union_distinct_constants_theory_of_card_le (T : L.Theory) (s : set α) (M : Type w') [nonempty M] [L.Structure M] [M ⊨ T] (h : cardinal.lift.{w'} (# s) ≤ cardinal.lift.{w} (# M)) : ((L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s).is_satisfiable := begin haveI : inhabited M := classical.inhabited_of_nonempty infer_instance, rw [cardinal.lift_mk_le'] at h, letI : (constants_on α).Structure M := constants_on.Structure (function.extend coe h.some default), haveI : M ⊨ (L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s, { refine ((Lhom.on_Theory_model _ _).2 infer_instance).union _, rw [model_distinct_constants_theory], refine λ a as b bs ab, _, rw [← subtype.coe_mk a as, ← subtype.coe_mk b bs, ← subtype.ext_iff], exact h.some.injective ((subtype.coe_injective.extend_apply h.some default ⟨a, as⟩).symm.trans (ab.trans (subtype.coe_injective.extend_apply h.some default ⟨b, bs⟩))), }, exact model.is_satisfiable M, end theorem is_satisfiable_union_distinct_constants_theory_of_infinite (T : L.Theory) (s : set α) (M : Type w') [L.Structure M] [M ⊨ T] [infinite M] : ((L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s).is_satisfiable := begin classical, rw [distinct_constants_theory_eq_Union, set.union_Union, is_satisfiable_directed_union_iff], { exact λ t, is_satisfiable_union_distinct_constants_theory_of_card_le T _ M ((lift_le_aleph_0.2 ((finset_card_lt_aleph_0 _).le)).trans (aleph_0_le_lift.2 (aleph_0_le_mk M))) }, { refine (monotone_const.union (monotone_distinct_constants_theory.comp _)).directed_le, simp only [finset.coe_map, function.embedding.coe_subtype], exact set.monotone_image.comp (λ _ _, finset.coe_subset.2) } end /-- Any theory with an infinite model has arbitrarily large models. -/ lemma exists_large_model_of_infinite_model (T : L.Theory) (κ : cardinal.{w}) (M : Type w') [L.Structure M] [M ⊨ T] [infinite M] : ∃ (N : Model.{_ _ (max u v w)} T), cardinal.lift.{max u v w} κ ≤ # N := begin obtain ⟨N⟩ := is_satisfiable_union_distinct_constants_theory_of_infinite T (set.univ : set κ.out) M, refine ⟨(N.is_model.mono (set.subset_union_left _ _)).bundled.reduct _, _⟩, haveI : N ⊨ distinct_constants_theory _ _ := N.is_model.mono (set.subset_union_right _ _), simp only [Model.reduct_carrier, coe_of, Model.carrier_eq_coe], refine trans (lift_le.2 (le_of_eq (cardinal.mk_out κ).symm)) _, rw [← mk_univ], refine (card_le_of_model_distinct_constants_theory L set.univ N).trans (lift_le.1 _), rw lift_lift, end lemma is_satisfiable_Union_iff_is_satisfiable_Union_finset {ι : Type*} (T : ι → L.Theory) : is_satisfiable (⋃ i, T i) ↔ ∀ (s : finset ι), is_satisfiable (⋃ (i ∈ s), T i) := begin classical, refine ⟨λ h s, h.mono (set.Union_mono (λ _, set.Union_subset_iff.2 (λ _, refl _))), λ h, _⟩, rw is_satisfiable_iff_is_finitely_satisfiable, intros s hs, rw set.Union_eq_Union_finset at hs, obtain ⟨t, ht⟩ := directed.exists_mem_subset_of_finset_subset_bUnion _ hs, { exact (h t).mono ht }, { exact (monotone.directed_le (λ t1 t2 h, set.Union_mono (λ _, set.Union_mono' (λ h1, ⟨h h1, refl _⟩)))) }, end end Theory variables (L) /-- A version of The Downward Löwenheim–Skolem theorem where the structure `N` elementarily embeds into `M`, but is not by type a substructure of `M`, and thus can be chosen to belong to the universe of the cardinal `κ`. -/ lemma exists_elementary_embedding_card_eq_of_le (M : Type w') [L.Structure M] [nonempty M] (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : lift.{w} L.card ≤ cardinal.lift.{max u v} κ) (h3 : lift.{w'} κ ≤ cardinal.lift.{w} (# M)) : ∃ (N : bundled L.Structure), nonempty (N ↪ₑ[L] M) ∧ # N = κ := begin obtain ⟨S, _, hS⟩ := exists_elementary_substructure_card_eq L ∅ κ h1 (by simp) h2 h3, haveI : small.{w} S, { rw [← lift_inj.{_ (w + 1)}, lift_lift, lift_lift] at hS, exact small_iff_lift_mk_lt_univ.2 (lt_of_eq_of_lt hS κ.lift_lt_univ') }, refine ⟨(equiv_shrink S).bundled_induced L, ⟨S.subtype.comp (equiv.bundled_induced_equiv L _).symm.to_elementary_embedding⟩, lift_inj.1 (trans _ hS)⟩, simp only [equiv.bundled_induced_α, lift_mk_shrink'], end /-- The Upward Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then `M` has an elementary extension of cardinality `κ`. -/ theorem exists_elementary_embedding_card_eq_of_ge (M : Type w') [L.Structure M] [iM : infinite M] (κ : cardinal.{w}) (h1 : cardinal.lift.{w} L.card ≤ cardinal.lift.{max u v} κ) (h2 : cardinal.lift.{w} (# M) ≤ cardinal.lift.{w'} κ) : ∃ (N : bundled L.Structure), nonempty (M ↪ₑ[L] N) ∧ # N = κ := begin obtain ⟨N0, hN0⟩ := (L.elementary_diagram M).exists_large_model_of_infinite_model κ M, let f0 := elementary_embedding.of_models_elementary_diagram L M N0, rw [← lift_le.{(max w w') (max u v)}, lift_lift, lift_lift] at h2, obtain ⟨N, ⟨NN0⟩, hN⟩ := exists_elementary_embedding_card_eq_of_le (L[[M]]) N0 κ (aleph_0_le_lift.1 ((aleph_0_le_lift.2 (aleph_0_le_mk M)).trans h2)) _ (hN0.trans _), { letI := (Lhom_with_constants L M).reduct N, haveI h : N ⊨ L.elementary_diagram M := (NN0.Theory_model_iff (L.elementary_diagram M)).2 infer_instance, refine ⟨bundled.of N, ⟨_⟩, hN⟩, apply elementary_embedding.of_models_elementary_diagram L M N, }, { simp only [card_with_constants, lift_add, lift_lift], rw [add_comm, add_eq_max (aleph_0_le_lift.2 (infinite_iff.1 iM)), max_le_iff], rw [← lift_le.{_ w'}, lift_lift, lift_lift] at h1, exact ⟨h2, h1⟩, }, { rw [← lift_umax', lift_id] }, end /-- The Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then there is an elementary embedding in the appropriate direction between then `M` and a structure of cardinality `κ`. -/ theorem exists_elementary_embedding_card_eq (M : Type w') [L.Structure M] [iM : infinite M] (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : lift.{w} L.card ≤ cardinal.lift.{max u v} κ) : ∃ (N : bundled L.Structure), (nonempty (N ↪ₑ[L] M) ∨ nonempty (M ↪ₑ[L] N)) ∧ # N = κ := begin cases le_or_gt (lift.{w'} κ) (cardinal.lift.{w} (# M)), { obtain ⟨N, hN1, hN2⟩ := exists_elementary_embedding_card_eq_of_le L M κ h1 h2 h, exact ⟨N, or.inl hN1, hN2⟩ }, { obtain ⟨N, hN1, hN2⟩ := exists_elementary_embedding_card_eq_of_ge L M κ h2 (le_of_lt h), exact ⟨N, or.inr hN1, hN2⟩ } end /-- A consequence of the Löwenheim–Skolem Theorem: If `κ` is a cardinal greater than the cardinalities of `L` and an infinite `L`-structure `M`, then there is a structure of cardinality `κ` elementarily equivalent to `M`. -/ lemma exists_elementarily_equivalent_card_eq (M : Type w') [L.Structure M] [infinite M] (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : lift.{w} L.card ≤ cardinal.lift.{max u v} κ) : ∃ (N : category_theory.bundled L.Structure), M ≅[L] N ∧ # N = κ := begin obtain ⟨N, (NM | MN), hNκ⟩ := exists_elementary_embedding_card_eq L M κ h1 h2, { exact ⟨N, NM.some.elementarily_equivalent.symm, hNκ⟩ }, { exact ⟨N, MN.some.elementarily_equivalent, hNκ⟩ } end variable {L} namespace Theory theorem exists_model_card_eq (h : ∃ (M : Model.{u v (max u v)} T), infinite M) (κ : cardinal.{w}) (h1 : ℵ₀ ≤ κ) (h2 : cardinal.lift.{w} L.card ≤ cardinal.lift.{max u v} κ) : ∃ (N : Model.{u v w} T), # N = κ := begin casesI h with M MI, obtain ⟨N, hN, rfl⟩ := exists_elementarily_equivalent_card_eq L M κ h1 h2, haveI : nonempty N := hN.nonempty, exact ⟨hN.Theory_model.bundled, rfl⟩, end variable (T) /-- A theory models a (bounded) formula when any of its nonempty models realizes that formula on all inputs.-/ def models_bounded_formula (φ : L.bounded_formula α n) : Prop := ∀ (M : Model.{u v (max u v)} T) (v : α → M) (xs : fin n → M), φ.realize v xs -- input using \|= or \vDash, but not using \models infix (name := models_bounded_formula) ` ⊨ `:51 := models_bounded_formula variable {T} lemma models_formula_iff {φ : L.formula α} : T ⊨ φ ↔ ∀ (M : Model.{u v (max u v)} T) (v : α → M), φ.realize v := forall_congr (λ M, forall_congr (λ v, unique.forall_iff)) lemma models_sentence_iff {φ : L.sentence} : T ⊨ φ ↔ ∀ (M : Model.{u v (max u v)} T), M ⊨ φ := models_formula_iff.trans (forall_congr (λ M, unique.forall_iff)) lemma models_sentence_of_mem {φ : L.sentence} (h : φ ∈ T) : T ⊨ φ := models_sentence_iff.2 (λ _, realize_sentence_of_mem T h) lemma models_iff_not_satisfiable (φ : L.sentence) : T ⊨ φ ↔ ¬ is_satisfiable (T ∪ {φ.not}) := begin rw [models_sentence_iff, is_satisfiable], refine ⟨λ h1 h2, (sentence.realize_not _).1 (realize_sentence_of_mem (T ∪ {formula.not φ}) (set.subset_union_right _ _ (set.mem_singleton _))) (h1 (h2.some.subtheory_Model (set.subset_union_left _ _))), λ h M, _⟩, contrapose! h, rw ← sentence.realize_not at h, refine ⟨{ carrier := M, is_model := ⟨λ ψ hψ, hψ.elim (realize_sentence_of_mem _) (λ h', _)⟩, }⟩, rw set.mem_singleton_iff.1 h', exact h, end /-- A theory is complete when it is satisfiable and models each sentence or its negation. -/ def is_complete (T : L.Theory) : Prop := T.is_satisfiable ∧ ∀ (φ : L.sentence), (T ⊨ φ) ∨ (T ⊨ φ.not) /-- A theory is maximal when it is satisfiable and contains each sentence or its negation. Maximal theories are complete. -/ def is_maximal (T : L.Theory) : Prop := T.is_satisfiable ∧ ∀ (φ : L.sentence), φ ∈ T ∨ φ.not ∈ T lemma is_maximal.is_complete (h : T.is_maximal) : T.is_complete := h.imp_right (forall_imp (λ _, or.imp models_sentence_of_mem models_sentence_of_mem)) lemma is_maximal.mem_or_not_mem (h : T.is_maximal) (φ : L.sentence) : φ ∈ T ∨ φ.not ∈ T := h.2 φ lemma is_maximal.mem_of_models (h : T.is_maximal) {φ : L.sentence} (hφ : T ⊨ φ) : φ ∈ T := begin refine (h.mem_or_not_mem φ).resolve_right (λ con, _), rw [models_iff_not_satisfiable, set.union_singleton, set.insert_eq_of_mem con] at hφ, exact hφ h.1, end lemma is_maximal.mem_iff_models (h : T.is_maximal) (φ : L.sentence) : φ ∈ T ↔ T ⊨ φ := ⟨models_sentence_of_mem, h.mem_of_models⟩ /-- Two (bounded) formulas are semantically equivalent over a theory `T` when they have the same interpretation in every model of `T`. (This is also known as logical equivalence, which also has a proof-theoretic definition.) -/ def semantically_equivalent (T : L.Theory) (φ ψ : L.bounded_formula α n) : Prop := T ⊨ φ.iff ψ @[refl] lemma semantically_equivalent.refl (φ : L.bounded_formula α n) : T.semantically_equivalent φ φ := λ M v xs, by rw bounded_formula.realize_iff instance : is_refl (L.bounded_formula α n) T.semantically_equivalent := ⟨semantically_equivalent.refl⟩ @[symm] lemma semantically_equivalent.symm {φ ψ : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent ψ φ := λ M v xs, begin rw [bounded_formula.realize_iff, iff.comm, ← bounded_formula.realize_iff], exact h M v xs, end @[trans] lemma semantically_equivalent.trans {φ ψ θ : L.bounded_formula α n} (h1 : T.semantically_equivalent φ ψ) (h2 : T.semantically_equivalent ψ θ) : T.semantically_equivalent φ θ := λ M v xs, begin have h1' := h1 M v xs, have h2' := h2 M v xs, rw [bounded_formula.realize_iff] at *, exact ⟨h2'.1 ∘ h1'.1, h1'.2 ∘ h2'.2⟩, end lemma semantically_equivalent.realize_bd_iff {φ ψ : L.bounded_formula α n} {M : Type (max u v)} [ne : nonempty M] [str : L.Structure M] [hM : T.model M] (h : T.semantically_equivalent φ ψ) {v : α → M} {xs : (fin n → M)} : φ.realize v xs ↔ ψ.realize v xs := bounded_formula.realize_iff.1 (h (Model.of T M) v xs) lemma semantically_equivalent.realize_iff {φ ψ : L.formula α} {M : Type (max u v)} [ne : nonempty M] [str : L.Structure M] (hM : T.model M) (h : T.semantically_equivalent φ ψ) {v : α → M} : φ.realize v ↔ ψ.realize v := h.realize_bd_iff /-- Semantic equivalence forms an equivalence relation on formulas. -/ def semantically_equivalent_setoid (T : L.Theory) : setoid (L.bounded_formula α n) := { r := semantically_equivalent T, iseqv := ⟨λ _, refl _, λ a b h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩ } protected lemma semantically_equivalent.all {φ ψ : L.bounded_formula α (n + 1)} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.all ψ.all := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_all], exact λ M v xs, forall_congr (λ a, h.realize_bd_iff), end protected lemma semantically_equivalent.ex {φ ψ : L.bounded_formula α (n + 1)} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.ex ψ.ex := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_ex], exact λ M v xs, exists_congr (λ a, h.realize_bd_iff), end protected lemma semantically_equivalent.not {φ ψ : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.not ψ.not := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_not], exact λ M v xs, not_congr h.realize_bd_iff, end protected lemma semantically_equivalent.imp {φ ψ φ' ψ' : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) (h' : T.semantically_equivalent φ' ψ') : T.semantically_equivalent (φ.imp φ') (ψ.imp ψ') := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_imp], exact λ M v xs, imp_congr h.realize_bd_iff h'.realize_bd_iff, end end Theory namespace complete_theory variables (L) (M : Type w) [L.Structure M] lemma is_satisfiable [nonempty M] : (L.complete_theory M).is_satisfiable := Theory.model.is_satisfiable M lemma mem_or_not_mem (φ : L.sentence) : φ ∈ L.complete_theory M ∨ φ.not ∈ L.complete_theory M := by simp_rw [complete_theory, set.mem_set_of_eq, sentence.realize, formula.realize_not, or_not] lemma is_maximal [nonempty M] : (L.complete_theory M).is_maximal := ⟨is_satisfiable L M, mem_or_not_mem L M⟩ lemma is_complete [nonempty M] : (L.complete_theory M).is_complete := (complete_theory.is_maximal L M).is_complete end complete_theory namespace bounded_formula variables (φ ψ : L.bounded_formula α n) lemma semantically_equivalent_not_not : T.semantically_equivalent φ φ.not.not := λ M v xs, by simp lemma imp_semantically_equivalent_not_sup : T.semantically_equivalent (φ.imp ψ) (φ.not ⊔ ψ) := λ M v xs, by simp [imp_iff_not_or] lemma sup_semantically_equivalent_not_inf_not : T.semantically_equivalent (φ ⊔ ψ) (φ.not ⊓ ψ.not).not := λ M v xs, by simp [imp_iff_not_or] lemma inf_semantically_equivalent_not_sup_not : T.semantically_equivalent (φ ⊓ ψ) (φ.not ⊔ ψ.not).not := λ M v xs, by simp [and_iff_not_or_not] lemma all_semantically_equivalent_not_ex_not (φ : L.bounded_formula α (n + 1)) : T.semantically_equivalent φ.all φ.not.ex.not := λ M v xs, by simp lemma ex_semantically_equivalent_not_all_not (φ : L.bounded_formula α (n + 1)) : T.semantically_equivalent φ.ex φ.not.all.not := λ M v xs, by simp lemma semantically_equivalent_all_lift_at : T.semantically_equivalent φ (φ.lift_at 1 n).all := λ M v xs, by { resetI, rw [realize_iff, realize_all_lift_at_one_self] } end bounded_formula namespace formula variables (φ ψ : L.formula α) lemma semantically_equivalent_not_not : T.semantically_equivalent φ φ.not.not := φ.semantically_equivalent_not_not lemma imp_semantically_equivalent_not_sup : T.semantically_equivalent (φ.imp ψ) (φ.not ⊔ ψ) := φ.imp_semantically_equivalent_not_sup ψ lemma sup_semantically_equivalent_not_inf_not : T.semantically_equivalent (φ ⊔ ψ) (φ.not ⊓ ψ.not).not := φ.sup_semantically_equivalent_not_inf_not ψ lemma inf_semantically_equivalent_not_sup_not : T.semantically_equivalent (φ ⊓ ψ) (φ.not ⊔ ψ.not).not := φ.inf_semantically_equivalent_not_sup_not ψ end formula namespace bounded_formula lemma is_qf.induction_on_sup_not {P : L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_qf φ) (hf : P (⊥ : L.bounded_formula α n)) (ha : ∀ (ψ : L.bounded_formula α n), is_atomic ψ → P ψ) (hsup : ∀ {φ₁ φ₂} (h₁ : P φ₁) (h₂ : P φ₂), P (φ₁ ⊔ φ₂)) (hnot : ∀ {φ} (h : P φ), P φ.not) (hse : ∀ {φ₁ φ₂ : L.bounded_formula α n} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := is_qf.rec_on h hf ha (λ φ₁ φ₂ _ _ h1 h2, (hse (φ₁.imp_semantically_equivalent_not_sup φ₂)).2 (hsup (hnot h1) h2)) lemma is_qf.induction_on_inf_not {P : L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_qf φ) (hf : P (⊥ : L.bounded_formula α n)) (ha : ∀ (ψ : L.bounded_formula α n), is_atomic ψ → P ψ) (hinf : ∀ {φ₁ φ₂} (h₁ : P φ₁) (h₂ : P φ₂), P (φ₁ ⊓ φ₂)) (hnot : ∀ {φ} (h : P φ), P φ.not) (hse : ∀ {φ₁ φ₂ : L.bounded_formula α n} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := h.induction_on_sup_not hf ha (λ φ₁ φ₂ h1 h2, ((hse (φ₁.sup_semantically_equivalent_not_inf_not φ₂)).2 (hnot (hinf (hnot h1) (hnot h2))))) (λ _, hnot) (λ _ _, hse) lemma semantically_equivalent_to_prenex (φ : L.bounded_formula α n) : (∅ : L.Theory).semantically_equivalent φ φ.to_prenex := λ M v xs, by rw [realize_iff, realize_to_prenex] lemma induction_on_all_ex {P : Π {m}, L.bounded_formula α m → Prop} (φ : L.bounded_formula α n) (hqf : ∀ {m} {ψ : L.bounded_formula α m}, is_qf ψ → P ψ) (hall : ∀ {m} {ψ : L.bounded_formula α (m + 1)} (h : P ψ), P ψ.all) (hex : ∀ {m} {φ : L.bounded_formula α (m + 1)} (h : P φ), P φ.ex) (hse : ∀ {m} {φ₁ φ₂ : L.bounded_formula α m} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := begin suffices h' : ∀ {m} {φ : L.bounded_formula α m}, φ.is_prenex → P φ, { exact (hse φ.semantically_equivalent_to_prenex).2 (h' φ.to_prenex_is_prenex) }, intros m φ hφ, induction hφ with _ _ hφ _ _ _ hφ _ _ _ hφ, { exact hqf hφ }, { exact hall hφ, }, { exact hex hφ, }, end lemma induction_on_exists_not {P : Π {m}, L.bounded_formula α m → Prop} (φ : L.bounded_formula α n) (hqf : ∀ {m} {ψ : L.bounded_formula α m}, is_qf ψ → P ψ) (hnot : ∀ {m} {φ : L.bounded_formula α m} (h : P φ), P φ.not) (hex : ∀ {m} {φ : L.bounded_formula α (m + 1)} (h : P φ), P φ.ex) (hse : ∀ {m} {φ₁ φ₂ : L.bounded_formula α m} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := φ.induction_on_all_ex (λ _ _, hqf) (λ _ φ hφ, (hse φ.all_semantically_equivalent_not_ex_not).2 (hnot (hex (hnot hφ)))) (λ _ _, hex) (λ _ _ _, hse) end bounded_formula end language end first_order namespace cardinal open first_order first_order.language variables {L : language.{u v}} (κ : cardinal.{w}) (T : L.Theory) /-- A theory is `κ`-categorical if all models of size `κ` are isomorphic. -/ def categorical : Prop := ∀ (M N : T.Model), # M = κ → # N = κ → nonempty (M ≃[L] N) /-- The Łoś–Vaught Test : a criterion for categorical theories to be complete. -/ lemma categorical.is_complete (h : κ.categorical T) (h1 : ℵ₀ ≤ κ) (h2 : cardinal.lift.{w} L.card ≤ cardinal.lift.{max u v} κ) (hS : T.is_satisfiable) (hT : ∀ (M : Theory.Model.{u v max u v} T), infinite M) : T.is_complete := ⟨hS, λ φ, begin obtain ⟨N, hN⟩ := Theory.exists_model_card_eq ⟨hS.some, hT hS.some⟩ κ h1 h2, rw [Theory.models_sentence_iff, Theory.models_sentence_iff], by_contra con, push_neg at con, obtain ⟨⟨MF, hMF⟩, MT, hMT⟩ := con, rw [sentence.realize_not, not_not] at hMT, refine hMF _, haveI := hT MT, haveI := hT MF, obtain ⟨NT, MNT, hNT⟩ := exists_elementarily_equivalent_card_eq L MT κ h1 h2, obtain ⟨NF, MNF, hNF⟩ := exists_elementarily_equivalent_card_eq L MF κ h1 h2, obtain ⟨TF⟩ := h (MNT.to_Model T) (MNF.to_Model T) hNT hNF, exact ((MNT.realize_sentence φ).trans ((TF.realize_sentence φ).trans (MNF.realize_sentence φ).symm)).1 hMT, end⟩ theorem empty_Theory_categorical (T : language.empty.Theory) : κ.categorical T := λ M N hM hN, by rw [empty.nonempty_equiv_iff, hM, hN] theorem empty_infinite_Theory_is_complete : language.empty.infinite_theory.is_complete := (empty_Theory_categorical ℵ₀ _).is_complete ℵ₀ _ le_rfl (by simp) ⟨Theory.model.bundled ((model_infinite_theory_iff language.empty).2 nat.infinite)⟩ (λ M, (model_infinite_theory_iff language.empty).1 M.is_model) end cardinal
9ddb2bc609fc4af71a5d5e1d1f7c6cd9fdd19fb5
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/kernel.lean
057f4c211052538a82a55fcceec91780ae041842
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
2,284
lean
import .group_representation import .morphism import .sub_module universe variables u v w w' w'' w''' variables {G : Type u} [group G] {R : Type v}[ring R] variables {M1 : Type w} [add_comm_group M1] [module R M1] {M2 : Type w'} [add_comm_group M2] [module R M2] {ρ1 : group_representation G R M1} {ρ2 : group_representation G R M2} (f : ρ1 ⟶ ρ2 ) open stability morphism namespace Kernel /-- The kernel of `f : ρ1 ⟶ ρ2` is define to be the kernel of `↑f : M1 →ₗ[R] M2` -/ def Ker := linear_map.ker (f.ℓ) /-- bof -/ lemma Ker_ext_iff(x : M1) : x ∈ Ker f ↔ x ∈ linear_map.ker (f.ℓ) := iff.rfl --- brouh not good ! lemma mem_ker (x : M1) : x ∈ Ker f ↔ f x = 0 := linear_map.mem_ker lemma Ker_ext (x : M1 ) : f x = 0 → x ∈ Ker f := begin intros, rw Ker_ext_iff,rw linear_map.mem_ker,assumption, end lemma Ker_f_mem (x : M1) : (x ∈ Ker f) → f x =0 := begin rw ← mem_ker,intros, assumption, end /-- The kernel of `f : ρ1 ⟶ ρ2` is an stable sub-stape of M1. -/ theorem ker_is_stable_submodule : stable_submodule ρ1 (Ker f) := begin intros g,intros x,apply Ker_ext, rw morphism.commute_apply, rw Ker_f_mem,rw (ρ2 g).map_zero, rcases x,unfold Ker at ⊢ x_property , assumption, end /-- The Kernel of `f : ρ1 ⟶ ρ2` has representation. -/ def ker : group_representation G R (Ker f) := Res (ker_is_stable_submodule f) end Kernel namespace range open linear_map /-- Range is stable. Let `y ∈ Im f`, let `g ∈ G`, we want : `ρ g y ∈ Im f`. Take `x ∈ M1` s.t `f x = y`. We have (from `f.commute`) : `(f ∘ ρ1 g) x = ρ2 g ∘ f x` i.e `ρ2 g y = f ( ρ1 g x)` and so `ρ2 g y ∈ Im f` -/ theorem range_is_stable_submodule : stable_submodule ρ2 (range (f.ℓ : M1→ₗ[R] M2)) := begin intros g,intros y,rcases y with ⟨y, ⟨x,hyp⟩⟩, apply linear_map.mem_range.mpr, use ρ1 g x, erw commute_apply, exact congr_arg ⇑(ρ2 g) hyp.right, end /-- For a morphism `f : ρ1 ⟶ ρ2` between `representation` we define a sub representation of `M2` -/ def Range : group_representation G R (range (f.ℓ : M1→ₗ[R] M2)) := Res (range_is_stable_submodule f) end range
c8e70bef1f8ed0c17af8b1a4eebc3d3312e96bf8
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebraic_geometry/Gamma_Spec_adjunction.lean
ebe6c4c29ea3fb3f05242b9dbd6e6b2d641fcc9c
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
16,140
lean
/- Copyright (c) 2021 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import algebraic_geometry.Scheme import category_theory.adjunction.limits import category_theory.adjunction.reflective /-! # Adjunction between `Γ` and `Spec` We define the adjunction `Γ_Spec.adjunction : Γ ⊣ Spec` by defining the unit (`to_Γ_Spec`, in multiple steps in this file) and counit (done in Spec.lean) and checking that they satisfy the left and right triangle identities. The constructions and proofs make use of maps and lemmas defined and proved in structure_sheaf.lean extensively. Notice that since the adjunction is between contravariant functors, you get to choose one of the two categories to have arrows reversed, and it is equally valid to present the adjunction as `Spec ⊣ Γ` (`Spec.to_LocallyRingedSpace.right_op ⊣ Γ`), in which case the unit and the counit would switch to each other. ## Main definition * `algebraic_geometry.identity_to_Γ_Spec` : The natural transformation `𝟭 _ ⟶ Γ ⋙ Spec`. * `algebraic_geometry.Γ_Spec.LocallyRingedSpace_adjunction` : The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `LocallyRingedSpace`. * `algebraic_geometry.Γ_Spec.adjunction` : The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `Scheme`. -/ noncomputable theory universes u open prime_spectrum namespace algebraic_geometry open opposite open category_theory open structure_sheaf Spec (structure_sheaf) open topological_space open algebraic_geometry.LocallyRingedSpace open Top.presheaf open Top.presheaf.sheaf_condition namespace LocallyRingedSpace variable (X : LocallyRingedSpace.{u}) /-- The map from the global sections to a stalk. -/ def Γ_to_stalk (x : X) : Γ.obj (op X) ⟶ X.presheaf.stalk x := X.presheaf.germ (⟨x,trivial⟩ : (⊤ : opens X)) /-- The canonical map from the underlying set to the prime spectrum of `Γ(X)`. -/ def to_Γ_Spec_fun : X → prime_spectrum (Γ.obj (op X)) := λ x, comap (X.Γ_to_stalk x) (local_ring.closed_point (X.presheaf.stalk x)) lemma not_mem_prime_iff_unit_in_stalk (r : Γ.obj (op X)) (x : X) : r ∉ (X.to_Γ_Spec_fun x).as_ideal ↔ is_unit (X.Γ_to_stalk x r) := by erw [local_ring.mem_maximal_ideal, not_not] /-- The preimage of a basic open in `Spec Γ(X)` under the unit is the basic open in `X` defined by the same element (they are equal as sets). -/ lemma to_Γ_Spec_preim_basic_open_eq (r : Γ.obj (op X)) : X.to_Γ_Spec_fun⁻¹' (basic_open r).1 = (X.to_RingedSpace.basic_open r).1 := by { ext, erw X.to_RingedSpace.mem_top_basic_open, apply not_mem_prime_iff_unit_in_stalk } /-- `to_Γ_Spec_fun` is continuous. -/ lemma to_Γ_Spec_continuous : continuous X.to_Γ_Spec_fun := begin apply is_topological_basis_basic_opens.continuous, rintro _ ⟨r, rfl⟩, erw X.to_Γ_Spec_preim_basic_open_eq r, exact (X.to_RingedSpace.basic_open r).2, end /-- The canonical (bundled) continuous map from the underlying topological space of `X` to the prime spectrum of its global sections. -/ @[simps] def to_Γ_Spec_base : X.to_Top ⟶ Spec.Top_obj (Γ.obj (op X)) := { to_fun := X.to_Γ_Spec_fun, continuous_to_fun := X.to_Γ_Spec_continuous } variable (r : Γ.obj (op X)) /-- The preimage in `X` of a basic open in `Spec Γ(X)` (as an open set). -/ abbreviation to_Γ_Spec_map_basic_open : opens X := (opens.map X.to_Γ_Spec_base).obj (basic_open r) /-- The preimage is the basic open in `X` defined by the same element `r`. -/ lemma to_Γ_Spec_map_basic_open_eq : X.to_Γ_Spec_map_basic_open r = X.to_RingedSpace.basic_open r := opens.ext (X.to_Γ_Spec_preim_basic_open_eq r) /-- The map from the global sections `Γ(X)` to the sections on the (preimage of) a basic open. -/ abbreviation to_to_Γ_Spec_map_basic_open : X.presheaf.obj (op ⊤) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r) := X.presheaf.map (X.to_Γ_Spec_map_basic_open r).le_top.op /-- `r` is a unit as a section on the basic open defined by `r`. -/ lemma is_unit_res_to_Γ_Spec_map_basic_open : is_unit (X.to_to_Γ_Spec_map_basic_open r r) := begin convert (X.presheaf.map $ (eq_to_hom $ X.to_Γ_Spec_map_basic_open_eq r).op) .is_unit_map (X.to_RingedSpace.is_unit_res_basic_open r), rw ← comp_apply, erw ← functor.map_comp, congr end /-- Define the sheaf hom on individual basic opens for the unit. -/ def to_Γ_Spec_c_app : (structure_sheaf $ Γ.obj $ op X).val.obj (op $ basic_open r) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r) := is_localization.away.lift r (is_unit_res_to_Γ_Spec_map_basic_open _ r) /-- Characterization of the sheaf hom on basic opens, direction ← (next lemma) is used at various places, but → is not used in this file. -/ lemma to_Γ_Spec_c_app_iff (f : (structure_sheaf $ Γ.obj $ op X).val.obj (op $ basic_open r) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r)) : to_open _ (basic_open r) ≫ f = X.to_to_Γ_Spec_map_basic_open r ↔ f = X.to_Γ_Spec_c_app r := begin rw ← (is_localization.away.away_map.lift_comp r (X.is_unit_res_to_Γ_Spec_map_basic_open r)), swap 5, exact is_localization.to_basic_open _ r, split, { intro h, refine is_localization.ring_hom_ext _ _, swap 5, exact is_localization.to_basic_open _ r, exact h }, apply congr_arg, end lemma to_Γ_Spec_c_app_spec : to_open _ (basic_open r) ≫ X.to_Γ_Spec_c_app r = X.to_to_Γ_Spec_map_basic_open r := (X.to_Γ_Spec_c_app_iff r _).2 rfl /-- The sheaf hom on all basic opens, commuting with restrictions. -/ def to_Γ_Spec_c_basic_opens : (induced_functor basic_open).op ⋙ (structure_sheaf (Γ.obj (op X))).1 ⟶ (induced_functor basic_open).op ⋙ ((Top.sheaf.pushforward X.to_Γ_Spec_base).obj X.𝒪).1 := { app := λ r, X.to_Γ_Spec_c_app r.unop, naturality' := λ r s f, begin apply (structure_sheaf.to_basic_open_epi (Γ.obj (op X)) r.unop).1, simp only [← category.assoc], erw X.to_Γ_Spec_c_app_spec r.unop, convert X.to_Γ_Spec_c_app_spec s.unop, symmetry, apply X.presheaf.map_comp end } /-- The canonical morphism of sheafed spaces from `X` to the spectrum of its global sections. -/ @[simps] def to_Γ_Spec_SheafedSpace : X.to_SheafedSpace ⟶ Spec.to_SheafedSpace.obj (op (Γ.obj (op X))) := { base := X.to_Γ_Spec_base, c := Top.sheaf.restrict_hom_equiv_hom (structure_sheaf (Γ.obj (op X))).1 _ is_basis_basic_opens X.to_Γ_Spec_c_basic_opens } lemma to_Γ_Spec_SheafedSpace_app_eq : X.to_Γ_Spec_SheafedSpace.c.app (op (basic_open r)) = X.to_Γ_Spec_c_app r := Top.sheaf.extend_hom_app _ _ _ _ _ lemma to_Γ_Spec_SheafedSpace_app_spec (r : Γ.obj (op X)) : to_open _ (basic_open r) ≫ X.to_Γ_Spec_SheafedSpace.c.app (op (basic_open r)) = X.to_to_Γ_Spec_map_basic_open r := (X.to_Γ_Spec_SheafedSpace_app_eq r).symm ▸ X.to_Γ_Spec_c_app_spec r /-- The map on stalks induced by the unit commutes with maps from `Γ(X)` to stalks (in `Spec Γ(X)` and in `X`). -/ lemma to_stalk_stalk_map_to_Γ_Spec (x : X) : to_stalk _ _ ≫ PresheafedSpace.stalk_map X.to_Γ_Spec_SheafedSpace x = X.Γ_to_stalk x := begin rw PresheafedSpace.stalk_map, erw ← to_open_germ _ (basic_open (1 : Γ.obj (op X))) ⟨X.to_Γ_Spec_fun x, by rw basic_open_one; trivial⟩, rw [← category.assoc, category.assoc (to_open _ _)], erw stalk_functor_map_germ, rw [← category.assoc (to_open _ _), X.to_Γ_Spec_SheafedSpace_app_spec 1], unfold Γ_to_stalk, rw ← stalk_pushforward_germ _ X.to_Γ_Spec_base X.presheaf ⊤, congr' 1, change (X.to_Γ_Spec_base _* X.presheaf).map le_top.hom.op ≫ _ = _, apply germ_res, end /-- The canonical morphism from `X` to the spectrum of its global sections. -/ @[simps val_base] def to_Γ_Spec : X ⟶ Spec.LocallyRingedSpace_obj (Γ.obj (op X)) := { val := X.to_Γ_Spec_SheafedSpace, prop := begin intro x, let p : prime_spectrum (Γ.obj (op X)) := X.to_Γ_Spec_fun x, constructor, /- show stalk map is local hom ↓ -/ let S := (structure_sheaf _).presheaf.stalk p, rintros (t : S) ht, obtain ⟨⟨r, s⟩, he⟩ := is_localization.surj p.as_ideal.prime_compl t, dsimp at he, apply is_unit_of_mul_is_unit_left, rw he, refine is_localization.map_units S (⟨r, _⟩ : p.as_ideal.prime_compl), apply (not_mem_prime_iff_unit_in_stalk _ _ _).mpr, rw [← to_stalk_stalk_map_to_Γ_Spec, comp_apply], erw ← he, rw ring_hom.map_mul, exact ht.mul ((is_localization.map_units S s : _).map (PresheafedSpace.stalk_map X.to_Γ_Spec_SheafedSpace x)) end } lemma comp_ring_hom_ext {X : LocallyRingedSpace} {R : CommRing} {f : R ⟶ Γ.obj (op X)} {β : X ⟶ Spec.LocallyRingedSpace_obj R} (w : X.to_Γ_Spec.1.base ≫ (Spec.LocallyRingedSpace_map f).1.base = β.1.base) (h : ∀ r : R, f ≫ X.presheaf.map (hom_of_le le_top : (opens.map β.1.base).obj (basic_open r) ⟶ _).op = to_open R (basic_open r) ≫ β.1.c.app (op (basic_open r))) : X.to_Γ_Spec ≫ Spec.LocallyRingedSpace_map f = β := begin ext1, apply Spec.basic_open_hom_ext, { intros r _, rw LocallyRingedSpace.comp_val_c_app, erw to_open_comp_comap_assoc, rw category.assoc, erw [to_Γ_Spec_SheafedSpace_app_spec, ← X.presheaf.map_comp], convert h r }, exact w, end /-- `to_Spec_Γ _` is an isomorphism so these are mutually two-sided inverses. -/ lemma Γ_Spec_left_triangle : to_Spec_Γ (Γ.obj (op X)) ≫ X.to_Γ_Spec.1.c.app (op ⊤) = 𝟙 _ := begin unfold to_Spec_Γ, rw ← to_open_res _ (basic_open (1 : Γ.obj (op X))) ⊤ (eq_to_hom basic_open_one.symm), erw category.assoc, rw [nat_trans.naturality, ← category.assoc], erw [X.to_Γ_Spec_SheafedSpace_app_spec 1, ← functor.map_comp], convert eq_to_hom_map X.presheaf _, refl, end end LocallyRingedSpace /-- The unit as a natural transformation. -/ def identity_to_Γ_Spec : 𝟭 LocallyRingedSpace.{u} ⟶ Γ.right_op ⋙ Spec.to_LocallyRingedSpace := { app := LocallyRingedSpace.to_Γ_Spec, naturality' := λ X Y f, begin symmetry, apply LocallyRingedSpace.comp_ring_hom_ext, { ext1 x, dsimp [Spec.Top_map, LocallyRingedSpace.to_Γ_Spec_fun], rw [← local_ring.comap_closed_point (PresheafedSpace.stalk_map _ x), ← prime_spectrum.comap_comp_apply, ← prime_spectrum.comap_comp_apply], congr' 2, exact (PresheafedSpace.stalk_map_germ f.1 ⊤ ⟨x,trivial⟩).symm, apply_instance }, { intro r, rw [LocallyRingedSpace.comp_val_c_app, ← category.assoc], erw [Y.to_Γ_Spec_SheafedSpace_app_spec, f.1.c.naturality], refl }, end } namespace Γ_Spec lemma left_triangle (X : LocallyRingedSpace) : Spec_Γ_identity.inv.app (Γ.obj (op X)) ≫ (identity_to_Γ_Spec.app X).val.c.app (op ⊤) = 𝟙 _ := X.Γ_Spec_left_triangle /-- `Spec_Γ_identity` is iso so these are mutually two-sided inverses. -/ lemma right_triangle (R : CommRing) : identity_to_Γ_Spec.app (Spec.to_LocallyRingedSpace.obj $ op R) ≫ Spec.to_LocallyRingedSpace.map (Spec_Γ_identity.inv.app R).op = 𝟙 _ := begin apply LocallyRingedSpace.comp_ring_hom_ext, { ext (p : prime_spectrum R) x, erw ← is_localization.at_prime.to_map_mem_maximal_iff ((structure_sheaf R).presheaf.stalk p) p.as_ideal x, refl }, { intro r, apply to_open_res }, end -- Removing this makes the following definition time out. local attribute [irreducible] Spec_Γ_identity identity_to_Γ_Spec Spec.to_LocallyRingedSpace /-- The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `LocallyRingedSpace`. -/ @[simps unit counit] def LocallyRingedSpace_adjunction : Γ.right_op ⊣ Spec.to_LocallyRingedSpace := adjunction.mk_of_unit_counit { unit := identity_to_Γ_Spec, counit := (nat_iso.op Spec_Γ_identity).inv, left_triangle' := by { ext X, erw category.id_comp, exact congr_arg quiver.hom.op (left_triangle X) }, right_triangle' := by { ext1, ext1 R, erw category.id_comp, exact right_triangle R.unop } } local attribute [semireducible] Spec.to_LocallyRingedSpace /-- The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `Scheme`. -/ def adjunction : Scheme.Γ.right_op ⊣ Scheme.Spec := LocallyRingedSpace_adjunction.restrict_fully_faithful Scheme.forget_to_LocallyRingedSpace (𝟭 _) (nat_iso.of_components (λ X, iso.refl _) (λ _ _ f, by simpa)) (nat_iso.of_components (λ X, iso.refl _) (λ _ _ f, by simpa)) lemma adjunction_hom_equiv_apply {X : Scheme} {R : CommRingᵒᵖ} (f : (op $ Scheme.Γ.obj $ op X) ⟶ R) : Γ_Spec.adjunction.hom_equiv X R f = LocallyRingedSpace_adjunction.hom_equiv X.1 R f := by { dsimp [adjunction, adjunction.restrict_fully_faithful], simp } local attribute [irreducible] LocallyRingedSpace_adjunction Γ_Spec.adjunction lemma adjunction_hom_equiv (X : Scheme) (R : CommRingᵒᵖ) : Γ_Spec.adjunction.hom_equiv X R = LocallyRingedSpace_adjunction.hom_equiv X.1 R := equiv.ext $ λ f, adjunction_hom_equiv_apply f lemma adjunction_hom_equiv_symm_apply {X : Scheme} {R : CommRingᵒᵖ} (f : X ⟶ Scheme.Spec.obj R) : (Γ_Spec.adjunction.hom_equiv X R).symm f = (LocallyRingedSpace_adjunction.hom_equiv X.1 R).symm f := by { congr' 2, exact adjunction_hom_equiv _ _ } @[simp] lemma adjunction_counit_app {R : CommRingᵒᵖ} : Γ_Spec.adjunction.counit.app R = LocallyRingedSpace_adjunction.counit.app R := by { rw [← adjunction.hom_equiv_symm_id, ← adjunction.hom_equiv_symm_id, adjunction_hom_equiv_symm_apply], refl } @[simp] lemma adjunction_unit_app {X : Scheme} : Γ_Spec.adjunction.unit.app X = LocallyRingedSpace_adjunction.unit.app X.1 := by { rw [← adjunction.hom_equiv_id, ← adjunction.hom_equiv_id, adjunction_hom_equiv_apply], refl } local attribute [semireducible] LocallyRingedSpace_adjunction Γ_Spec.adjunction instance is_iso_LocallyRingedSpace_adjunction_counit : is_iso LocallyRingedSpace_adjunction.counit := is_iso.of_iso_inv _ instance is_iso_adjunction_counit : is_iso Γ_Spec.adjunction.counit := begin apply_with nat_iso.is_iso_of_is_iso_app { instances := ff }, intro R, rw adjunction_counit_app, apply_instance, end -- This is just -- `(Γ_Spec.adjunction.unit.app X).1.c.app (op ⊤) = Spec_Γ_identity.hom.app (X.presheaf.obj (op ⊤))` -- But lean times out when trying to unify the types of the two sides. lemma adjunction_unit_app_app_top (X : Scheme) : @eq ((Scheme.Spec.obj (op $ X.presheaf.obj (op ⊤))).presheaf.obj (op ⊤) ⟶ ((Γ_Spec.adjunction.unit.app X).1.base _* X.presheaf).obj (op ⊤)) ((Γ_Spec.adjunction.unit.app X).val.c.app (op ⊤)) (Spec_Γ_identity.hom.app (X.presheaf.obj (op ⊤))) := begin have := congr_app Γ_Spec.adjunction.left_triangle X, dsimp at this, rw ← is_iso.eq_comp_inv at this, simp only [Γ_Spec.LocallyRingedSpace_adjunction_counit, nat_trans.op_app, category.id_comp, Γ_Spec.adjunction_counit_app] at this, rw [← op_inv, nat_iso.inv_inv_app, quiver.hom.op_inj.eq_iff] at this, exact this end end Γ_Spec /-! Immediate consequences of the adjunction. -/ /-- Spec preserves limits. -/ instance : limits.preserves_limits Spec.to_LocallyRingedSpace := Γ_Spec.LocallyRingedSpace_adjunction.right_adjoint_preserves_limits instance Spec.preserves_limits : limits.preserves_limits Scheme.Spec := Γ_Spec.adjunction.right_adjoint_preserves_limits /-- Spec is a full functor. -/ instance : full Spec.to_LocallyRingedSpace := R_full_of_counit_is_iso Γ_Spec.LocallyRingedSpace_adjunction instance Spec.full : full Scheme.Spec := R_full_of_counit_is_iso Γ_Spec.adjunction /-- Spec is a faithful functor. -/ instance : faithful Spec.to_LocallyRingedSpace := R_faithful_of_counit_is_iso Γ_Spec.LocallyRingedSpace_adjunction instance Spec.faithful : faithful Scheme.Spec := R_faithful_of_counit_is_iso Γ_Spec.adjunction instance : is_right_adjoint Spec.to_LocallyRingedSpace := ⟨_, Γ_Spec.LocallyRingedSpace_adjunction⟩ instance : is_right_adjoint Scheme.Spec := ⟨_, Γ_Spec.adjunction⟩ instance : reflective Spec.to_LocallyRingedSpace := ⟨⟩ instance Spec.reflective : reflective Scheme.Spec := ⟨⟩ end algebraic_geometry
aec9b58877670e47fb15392cfac6abdb6920ceb1
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/crypto/merkle/merkle_construction.lean
32b205060ea9f31c8aa0f605ecd6aa17cd508212
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,241
lean
import galois.data.bounded_list import galois.list.take_drop_lemmas universes u v namespace ksi namespace merkle structure combine_result (Link Data : Type) := (root : Data) (left : Link) (right : Link) /-- Operations needed to build a Merkle tree.-/ structure merkle_ops (Leaf Link Data : Type) := (empty_root : Data) (leaf_data : Leaf → Data) (apply_link : Link → Data → Data) (combine_data : Data -> Data → combine_result Link Data) (apply_left_correct : ∀(x y : Data), apply_link (combine_data x y).left x = (combine_data x y).root) (apply_right_correct : ∀(x y : Data), apply_link (combine_data x y).right y = (combine_data x y).root) section types parameters {Leaf Link Data : Type} parameter (s : merkle_ops Leaf Link Data) /-- This stores information about a path from a leaf to a root. max_req_level bounds the length of the links. -/ structure path (max_req_level : ℕ) (root : Data) := (leaf : Leaf) (links : bounded_list Link max_req_level) -- Proof theat the (root_valid : links.val.foldr s.apply_link (s.leaf_data leaf) = root) /-- This represents-/ structure merkle_result (max_req_level : ℕ) (l : list Leaf) := -- what we are aggregating (root : Data) -- the paths through the tree to get to this point (paths : list (path max_req_level root)) -- what we have not yet aggregated (remaining : list Leaf) -- Proof we include all the original paths. (paths_valid : paths.map path.leaf ++ remaining = l) -- The length of the paths (remaining_valid : remaining = l.drop (2^max_req_level)) end types section merkle -- This contains the types for the leaves of the tree and link elements parameters {Leaf Link Data : Type} parameter (ops : merkle_ops Leaf Link Data) def path.extend_none {n:ℕ} {root : Data} (p : path ops n root) : path ops n.succ root := { links := p.links.extend 1 , leaf := p.leaf , root_valid := begin cases p, cases links, exact root_valid, end } theorem path_extend_none (n : ℕ) (root : Data) : path.leaf ∘ @path.extend_none n root = path.leaf := begin apply funext, intro p, cases p, simp [function.comp, path.extend_none], end def gpath.extend_sibling (n : ℕ) {r r' : Data} (l : Link) (eq : ops.apply_link l r = r') (p : path ops n r) : path ops n.succ r' := { links := p.links.cons l , leaf := p.leaf , root_valid := begin cases p, cases links, simp [bounded_list.cons, root_valid, eq], end } theorem path_extend_sibling (n : ℕ) (r r' : Data) (l : Link) (eq : ops.apply_link l r = r') : path.leaf ∘ @gpath.extend_sibling n r r' l eq = path.leaf := begin apply funext, intro p, cases p, simp [function.comp, gpath.extend_sibling], end def dcases_on {T : Type u} {C : list T → Sort v} (n : list T) (base : n = [] → C []) (ind : Π (h : T) (r : list T), n = h::r → C (h :: r)) : C n := @list.cases_on T (λl, n = l → C l) n base ind rfl def merkle_core : Π (n : ℕ) (e : Leaf) (rest : list Leaf), merkle_result ops n (e::rest) | 0 e rest := { root := ops.leaf_data e , paths := [{ leaf := e , links := bounded_list.nil , root_valid := rfl, }] , remaining := rest , paths_valid := rfl , remaining_valid := rfl } | (nat.succ n) e rest := do let left_result := merkle_core n e rest in @dcases_on _ (λr, merkle_result ops n.succ (e::rest)) left_result.remaining (λ(eq : left_result.remaining = []), { root := left_result.root , paths := left_result.paths.map path.extend_none , remaining := left_result.remaining , paths_valid := begin simp [path_extend_none, left_result.paths_valid], end , remaining_valid := begin have h : (2^nat.succ n) = 2^n + 2^n, { simp [nat.pow, nat.succ_mul], }, have g := left_result.remaining_valid, rw [h, list.drop_add, ← g, eq, list.drop_nil], end }) (λ(e' : Leaf) (rest' : list Leaf) (eq : left_result.remaining = e' :: rest'), let right_result := merkle_core n e' rest' in let z := ops.combine_data left_result.root right_result.root in let l_eq := ops.apply_left_correct left_result.root right_result.root in let r_eq := ops.apply_right_correct left_result.root right_result.root in { root := z.root , paths := left_result.paths.map (gpath.extend_sibling n z.left l_eq) ++ right_result.paths.map (gpath.extend_sibling n z.right r_eq) , remaining := right_result.remaining , paths_valid := begin simp [path_extend_sibling, right_result.paths_valid], rw [← eq], exact left_result.paths_valid, end , remaining_valid := begin have h : (2^nat.succ n) = 2^n + 2^n, { simp [nat.pow, nat.succ_mul], }, rw [h, list.drop_add, ← left_result.remaining_valid, eq], exact right_result.remaining_valid, end }) def merkle : Π (n : ℕ) (l : list Leaf), merkle_result ops n l | n [] := { root := ops.empty_root , paths := [] , remaining := [] , paths_valid := rfl , remaining_valid := by simp [list.drop_nil], } | n (e::r) := merkle_core n e r end merkle end merkle end ksi
dab2fdea08c3a08be77ad412919dfec91b5451e7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/t2.lean
df84a5cb3418ee1c456bc4b75c40dff9407f0c5f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,966
lean
/- Benchmark for new code generator -/ inductive Expr | Val : Int → Expr | Var : String → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr | Pow : Expr → Expr → Expr | Ln : Expr → Expr namespace Expr partial def pown : Int → Int → Int | a, 0 => 1 | a, 1 => a | a, n => let b := pown a (n / 2); b * b * (if n % 2 = 0 then 1 else a) partial def add : Expr → Expr → Expr | Val n, Val m => Val (n + m) | Val 0, f => f | f, Val 0 => f | f, Val n => add (Val n) f | Val n, Add (Val m) f => add (Val (n+m)) f | f, Add (Val n) g => add (Val n) (add f g) | Add f g, h => add f (add g h) | f, g => Add f g partial def mul : Expr → Expr → Expr | Val n, Val m => Val (n*m) | Val 0, _ => Val 0 | _, Val 0 => Val 0 | Val 1, f => f | f, Val 1 => f | f, Val n => mul (Val n) f | Val n, Mul (Val m) f => mul (Val (n*m)) f | f, Mul (Val n) g => mul (Val n) (mul f g) | Mul f g, h => mul f (mul g h) | f, g => Mul f g def pow : Expr → Expr → Expr | Val m, Val n => Val (pown m n) | _, Val 0 => Val 1 | f, Val 1 => f | Val 0, _ => Val 0 | f, g => Pow f g def ln : Expr → Expr | Val 1 => Val 0 | f => Ln f def d (x : String) : Expr → Expr | Val _ => Val 0 | Var y => if x = y then Val 1 else Val 0 | Add f g => add (d x f) (d x g) | Mul f g => add (mul f (d x g)) (mul g (d x f)) | Pow f g => mul (pow f g) (add (mul (mul g (d x f)) (pow f (Val (-1)))) (mul (ln f) (d x g))) | Ln f => mul (d x f) (pow f (Val (-1))) def count : Expr → Nat | Val _ => 1 | Var _ => 1 | Add f g => count f + count g | Mul f g => count f + count g | Pow f g => count f + count g | Ln f => count f protected def Expr.toString : Expr → String | Val n => toString n | Var x => x | Add f g => "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")" | Mul f g => "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")" | Pow f g => "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")" | Ln f => "ln(" ++ Expr.toString f ++ ")" instance : ToString Expr := ⟨Expr.toString⟩ def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr | 0, x => pure x | m@(n+1), x => f (s - m) x >>= nestAux s f n def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr := nestAux n f n e def deriv (i : Nat) (f : Expr) : IO Expr := do let d := d "x" f; IO.println (toString (i+1) ++ " count: " ++ (toString $ count d)); pure d end Expr def main (xs : List String) : IO UInt32 := do let x := Expr.Var "x" let f := Expr.pow x x discard <| Expr.nest Expr.deriv 7 f pure 0 -- setOption profiler True -- #eval main []
d37f368689c5a5543ee66ee48d1b7805ea8eecf3
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/typeMismatch.lean
a8e9bdd5393dcabf6bf70225ad0f28cf5ec6111d
[ "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
185
lean
import Lean -- Test type mismatch error messages for "liftable" methods def test (x : Nat) : IO Nat := IO.println "" open Lean def test (x : Expr) : MetaM Unit := Meta.isDefEq x x
329237efe9e6785d335c49215dab97499fbfa035
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/data/set/finite.lean
b4abd24f1a1a0130e05c3dbd17beaed61f364111
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,263
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.finset.sort /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ h.fintype @[simp] lemma not_infinite {s : set α} : ¬ s.infinite ↔ s.finite := by simp [infinite] @[simp] theorem finite.mem_to_finset {s : set α} (h : finite s) {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) : h.to_finset.nonempty ↔ s.nonempty := show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s), from exists_congr (λ _, h.mem_to_finset) @[simp] lemma finite.coe_to_finset {s : set α} (h : finite s) : ↑h.to_finset = s := @set.coe_to_finset _ s h.fintype @[simp] lemma finite.coe_sort_to_finset {s : set α} (h : finite s) : (h.to_finset : Type*) = s := by rw [← finset.coe_sort_coe _, h.coe_to_finset] @[simp] lemma finite_empty_to_finset (h : finite (∅ : set α)) : h.to_finset = ∅ := by rw [← finset.coe_inj, h.coe_to_finset, finset.coe_empty] @[simp] lemma finite.to_finset_inj {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset = ht.to_finset ↔ s = t := by simp [←finset.coe_inj] @[simp] lemma finite_to_finset_eq_empty_iff {s : set α} {h : finite s} : h.to_finset = ∅ ↔ s = ∅ := by simp [←finset.coe_inj] theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩ lemma finite.fin_embedding {s : set α} (h : finite s) : ∃ (n : ℕ) (f : fin n ↪ α), range f = s := ⟨_, (fintype.equiv_fin (h.to_finset : set α)).symm.as_embedding, by simp⟩ lemma finite.fin_param {s : set α} (h : finite s) : ∃ (n : ℕ) (f : fin n → α), injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding in ⟨n, f, f.injective, hf⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩ /-- A `fintype` structure on `insert a s`. -/ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (hs.insert a).to_finset = insert a hs.to_finset := finset.ext $ by simp @[simp] lemma insert_to_finset [decidable_eq α] {a : α} {s : set α} [fintype s] : (insert a s).to_finset = insert a s.to_finset := by simp [finset.ext_iff, mem_insert_iff] @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := unique.fintype @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ lemma subsingleton.finite {s : set α} (h : s.subsingleton) : finite s := h.induction_on finite_empty finite_singleton instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ /-- If `(set.univ : set α)` is finite then `α` is a finite type. -/ noncomputable def fintype_of_univ_finite (H : (univ : set α).finite ) : fintype α := @fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _) lemma univ_finite_iff_nonempty_fintype : (univ : set α).finite ↔ nonempty (fintype α) := begin split, { intro h, exact ⟨fintype_of_univ_finite h⟩ }, { rintro ⟨_i⟩, exactI finite_univ } end theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ h₂, h₁ (fintype_of_univ_finite h₂)⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s := ⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩ theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s := infinite_coe_iff.2 h /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty := let a := infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩ instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ lemma finite.sup {s t : set α} : finite s → finite t → finite (s ⊔ t) := finite.union lemma infinite_of_finite_compl {α : Type} [_root_.infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma finite.infinite_compl {α : Type} [_root_.infinite α] {s : set α} (hs : s.finite) : sᶜ.infinite := λ h, set.infinite_univ (by simpa using hs.union h) instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s ∩ t : set α) := set.fintype_sep s t /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred (∈ t)] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ lemma finite.union_iff {s t : set α} : finite (s ∪ t) ↔ finite s ∧ finite t := ⟨λ h, ⟨h.subset (subset_union_left _ _), h.subset (subset_union_right _ _)⟩, λ ⟨hs, ht⟩, hs.union ht⟩ lemma finite.diff {s t u : set α} (hs : s.finite) (ht : t.finite) (h : u \ t ≤ s) : u.finite := begin refine finite.subset (ht.union hs) _, exact diff_subset_iff.mp h end theorem finite.inter_of_left {s : set α} (h : finite s) (t : set α) : finite (s ∩ t) := h.subset (inter_subset_left _ _) theorem finite.inter_of_right {s : set α} (h : finite s) (t : set α) : finite (t ∩ s) := h.subset (inter_subset_right _ _) theorem finite.inf_of_left {s : set α} (h : finite s) (t : set α) : finite (s ⊓ t) := h.inter_of_left t theorem finite.inf_of_right {s : set α} (h : finite s) (t : set α) : finite (t ⊓ s) := h.inter_of_right t theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t := mt (λ ht, ht.subset h) instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs lemma finite.dependent_image {s : set α} (hs : finite s) (F : Π i ∈ s, β) : finite {y : β | ∃ x (hx : x ∈ s), y = F x hx} := begin letI : fintype s := hs.fintype, convert finite_range (λ x : s, F x x.2), simp only [set_coe.exists, subtype.coe_mk, eq_comm], end theorem finite.of_preimage {f : α → β} {s : set β} (h : finite (f ⁻¹' s)) (hf : surjective f) : finite s := hf.image_preimage s ▸ h.image _ instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite.map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite.image /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image hi, finite.image _⟩ theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : infinite (f '' s) ↔ infinite s := not_congr $ finite_image_iff hi theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t := infinite_mono (maps_to'.mp hm) $ (infinite_image_iff hi).2 hs theorem infinite.exists_ne_map_eq_of_maps_to {s : set α} {t : set β} {f : α → β} (hs : infinite s) (hf : maps_to f s t) (ht : finite t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin unfreezingI { contrapose! ht }, exact infinite_of_inj_on_maps_to (λ x hx y hy, not_imp_not.1 (ht x hx y hy)) hf hs end theorem infinite.exists_lt_map_eq_of_maps_to [linear_order α] {s : set α} {t : set β} {f : α → β} (hs : infinite s) (hf : maps_to f s t) (ht : finite t) : ∃ (x ∈ s) (y ∈ s), x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_maps_to hf ht in hxy.lt_or_lt.elim (λ hxy, ⟨x, hx, y, hy, hxy, hf⟩) (λ hyx, ⟨y, hy, x, hx, hyx, hf.symm⟩) theorem infinite_range_of_injective [_root_.infinite α] {f : α → β} (hi : injective f) : infinite (range f) := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [_root_.infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : infinite s := by { rw ←range_subset_iff at hf, exact infinite_mono hf (infinite_range_of_injective hi) } theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (h.subset (image_preimage_subset f s)) theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := finite.preimage (λ _ _ _ _ h', f.injective h') h lemma finite_option {s : set (option α)} : finite s ↔ finite {x : α | some x ∈ s} := ⟨λ h, h.preimage_embedding embedding.some, λ h, ((h.image some).insert none).subset $ λ x, option.cases_on x (λ _, or.inl rfl) (λ x hx, or.inr $ mem_image_of_mem _ hx)⟩ instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bUnion (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} : finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _) theorem finite_Union_Prop {p : Prop} {f : p → set α} (hf : ∀ h, finite (f h)) : finite (⋃ h : p, f h) := by by_cases p; simp * instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ /-- `image2 f s t` is finitype if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (image2 f s t) := by { rw ← image_prod, exact (hs.prod ht).image _ } /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite.bind {α β} {s : set α} {f : α → set β} (h : finite s) (hf : ∀ a ∈ s, finite (f a)) : finite (s >>= f) := h.bUnion hf instance fintype_seq [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f.seq s) := by { rw seq_def, apply set.fintype_bUnion' } instance fintype_seq' {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := set.fintype_seq f s theorem finite.seq {f : set (α → β)} {s : set α} (hf : finite f) (hs : finite s) : finite (f.seq s) := by { rw seq_def, exact hf.bUnion (λ f _, hs.image _) } theorem finite.seq' {α β : Type u} {f : set (α → β)} {s : set α} (hf : finite f) (hs : finite s) : finite (f <*> s) := hf.seq hs /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)), have : finite s := (finite_mem_finset _).image _, apply this.subset, refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩, simpa [finset.subset_iff] end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_min_image f ⟨x, h1.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩ theorem exists_lower_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f a ≤ f b := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_min_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end theorem exists_upper_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f b ≤ f a := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_max_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end end set namespace finset variables [decidable_eq β] variables {s : finset α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bUnion {f : α → finset β} : ↑(s.bUnion f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) : (finite_to_set s).to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace set /-- Finite product of finite sets is finite -/ lemma finite.pi {δ : Type*} [fintype δ] {κ : δ → Type*} {t : Π d, set (κ d)} (ht : ∀ d, (t d).finite) : (pi univ t).finite := begin classical, convert (fintype.pi_finset (λ d, (ht d).to_finset)).finite_to_set, ext, simp, end /-- A finite union of finsets is finite. -/ lemma union_finset_finite_of_range_finite (f : α → finset β) (h : (range f).finite) : (⋃ a, (f a : set β)).finite := begin classical, have w : (⋃ (a : α), ↑(f a)) = (h.to_finset.bUnion id : set β), { ext x, simp only [mem_Union, finset.mem_coe, finset.mem_bUnion, id.def], use λ ⟨a, ha⟩, ⟨f a, h.mem_to_finset.2 (mem_range_self a), ha⟩, rintro ⟨s, hs, hx⟩, obtain ⟨a, rfl⟩ := h.mem_to_finset.1 hs, exact ⟨a, hx⟩, }, rw w, apply set.finite_mem_finset, end lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, λ x hx, _⟩, rw [bUnion_range, mem_Union], exact ⟨⟨x, hx⟩, hf _⟩ end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [linear_order ι'] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := begin ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩, simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx, obtain ⟨j₀⟩ := show nonempty ι', by apply_instance, refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩, rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)], exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩ end instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) := fintype.of_finset (finset.range n) $ by simp /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := (finite_singleton c).subset range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := (finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $ λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma subset_iff_to_finset_subset (s t : set α) [fintype s] [fintype t] : s ⊆ t ↔ s.to_finset ⊆ t.to_finset := by simp @[simp, mono] lemma finite.to_finset_mono {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset ⊆ ht.to_finset ↔ s ⊆ t := begin split, { intros h x, rw [←finite.mem_to_finset hs, ←finite.mem_to_finset ht], exact λ hx, h hx }, { intros h x, rw [finite.mem_to_finset hs, finite.mem_to_finset ht], exact λ hx, h hx } end @[simp, mono] lemma finite.to_finset_strict_mono {s t : set α} {hs : finite s} {ht : finite t} : hs.to_finset ⊂ ht.to_finset ↔ s ⊂ t := begin rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne], simp end lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective f hf lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, exact absurd h empty_not_nonempty }, assume a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext, rw set.finite.mem_to_finset } section decidable_eq lemma to_finset_compl {α : Type*} [fintype α] [decidable_eq α] (s : set α) [fintype (sᶜ : set α)] [fintype s] : sᶜ.to_finset = (s.to_finset)ᶜ := by ext; simp lemma to_finset_inter {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∩ t : set α)] [fintype s] [fintype t] : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp lemma to_finset_union {α : Type*} [decidable_eq α] (s t : set α) [fintype (s ∪ t : set α)] [fintype s] [fintype t] : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp lemma to_finset_ne_eq_erase {α : Type*} [decidable_eq α] [fintype α] (a : α) [fintype {x : α | x ≠ a}] : {x : α | x ≠ a}.to_finset = finset.univ.erase a := by ext; simp lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] : fintype.card {x : α | x ≠ a} = fintype.card α - 1 := begin haveI := classical.dec_eq α, rw [←to_finset_card, to_finset_ne_eq_erase, finset.card_erase_of_mem (finset.mem_univ _), finset.card_univ, nat.pred_eq_sub_one], end end decidable_eq section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : finite s) : bdd_below s := @finite.bdd_above (order_dual α) _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset namespace fintype variables [fintype α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] @[simp] lemma card_subtype_compl : fintype.card {x // ¬ p x} = fintype.card α - fintype.card {x // p x} := begin classical, rw [fintype.card_of_subtype (set.to_finset pᶜ), set.to_finset_compl p, finset.card_compl, fintype.card_of_subtype (set.to_finset p)]; intros; simp; refl end /-- If two subtypes of a fintype have equal cardinality, so do their complements. -/ lemma card_compl_eq_card_compl (h : fintype.card {x // p x} = fintype.card {x // q x}) : fintype.card {x // ¬ p x} = fintype.card {x // ¬ q x} := by simp only [card_subtype_compl, h] end fintype /-- If a set `s` does not contain any elements between any pair of elements `x, z ∈ s` with `x ≤ z` (i.e if given `x, y, z ∈ s` such that `x ≤ y ≤ z`, then `y` is either `x` or `z`), then `s` is finite. -/ lemma set.finite_of_forall_between_eq_endpoints {α : Type*} [linear_order α] (s : set α) (h : ∀ (x ∈ s) (y ∈ s) (z ∈ s), x ≤ y → y ≤ z → x = y ∨ y = z) : set.finite s := begin by_contra hinf, change s.infinite at hinf, rcases hinf.exists_subset_card_eq 3 with ⟨t, hts, ht⟩, let f := t.order_iso_of_fin ht, let x := f 0, let y := f 1, let z := f 2, have := h x (hts x.2) y (hts y.2) z (hts z.2) (f.monotone $ by dec_trivial) (f.monotone $ by dec_trivial), have key₁ : (0 : fin 3) ≠ 1 := by dec_trivial, have key₂ : (1 : fin 3) ≠ 2 := by dec_trivial, cases this, { dsimp only [x, y] at this, exact key₁ (f.injective $ subtype.coe_injective this) }, { dsimp only [y, z] at this, exact key₂ (f.injective $ subtype.coe_injective this) } end
ffb8583a31097a5881f11a470212670898b61f08
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/locally_convex/balanced_core_hull.lean
65e6cf2b31a427aef0903ec0e86d08f00981cb28
[ "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
9,647
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.locally_convex.basic import order.closure /-! # Balanced Core and Balanced Hull ## Main definitions * `balanced_core`: The largest balanced subset of a set `s`. * `balanced_hull`: The smallest balanced superset of a set `s`. ## Main statements * `balanced_core_eq_Inter`: Characterization of the balanced core as an intersection over subsets. * `nhds_basis_closed_balanced`: The closed balanced sets form a basis of the neighborhood filter. ## Implementation details The balanced core and hull are implemented differently: for the core we take the obvious definition of the union over all balanced sets that are contained in `s`, whereas for the hull, we take the union over `r • s`, for `r` the scalars with `∥r∥ ≤ 1`. We show that `balanced_hull` has the defining properties of a hull in `balanced.hull_minimal` and `subset_balanced_hull`. For the core we need slightly stronger assumptions to obtain a characterization as an intersection, this is `balanced_core_eq_Inter`. ## References * [Bourbaki, *Topological Vector Spaces*][bourbaki1987] ## Tags balanced -/ open set open_locale pointwise topological_space filter variables {𝕜 E ι : Type*} section balanced_hull section semi_normed_ring variables [semi_normed_ring 𝕜] section has_smul variables (𝕜) [has_smul 𝕜 E] {s t : set E} {x : E} /-- The largest balanced subset of `s`.-/ def balanced_core (s : set E) := ⋃₀ {t : set E | balanced 𝕜 t ∧ t ⊆ s} /-- Helper definition to prove `balanced_core_eq_Inter`-/ def balanced_core_aux (s : set E) := ⋂ (r : 𝕜) (hr : 1 ≤ ∥r∥), r • s /-- The smallest balanced superset of `s`.-/ def balanced_hull (s : set E) := ⋃ (r : 𝕜) (hr : ∥r∥ ≤ 1), r • s variables {𝕜} lemma balanced_core_subset (s : set E) : balanced_core 𝕜 s ⊆ s := sUnion_subset $ λ t ht, ht.2 lemma balanced_core_empty : balanced_core 𝕜 (∅ : set E) = ∅ := eq_empty_of_subset_empty (balanced_core_subset _) lemma mem_balanced_core_iff : x ∈ balanced_core 𝕜 s ↔ ∃ t, balanced 𝕜 t ∧ t ⊆ s ∧ x ∈ t := by simp_rw [balanced_core, mem_sUnion, mem_set_of_eq, exists_prop, and_assoc] lemma smul_balanced_core_subset (s : set E) {a : 𝕜} (ha : ∥a∥ ≤ 1) : a • balanced_core 𝕜 s ⊆ balanced_core 𝕜 s := begin rintro x ⟨y, hy, rfl⟩, rw mem_balanced_core_iff at hy, rcases hy with ⟨t, ht1, ht2, hy⟩, exact ⟨t, ⟨ht1, ht2⟩, ht1 a ha (smul_mem_smul_set hy)⟩, end lemma balanced_core_balanced (s : set E) : balanced 𝕜 (balanced_core 𝕜 s) := λ _, smul_balanced_core_subset s /-- The balanced core of `t` is maximal in the sense that it contains any balanced subset `s` of `t`.-/ lemma balanced.subset_core_of_subset (hs : balanced 𝕜 s) (h : s ⊆ t) : s ⊆ balanced_core 𝕜 t := subset_sUnion_of_mem ⟨hs, h⟩ lemma mem_balanced_core_aux_iff : x ∈ balanced_core_aux 𝕜 s ↔ ∀ r : 𝕜, 1 ≤ ∥r∥ → x ∈ r • s := mem_Inter₂ lemma mem_balanced_hull_iff : x ∈ balanced_hull 𝕜 s ↔ ∃ (r : 𝕜) (hr : ∥r∥ ≤ 1), x ∈ r • s := mem_Union₂ /-- The balanced hull of `s` is minimal in the sense that it is contained in any balanced superset `t` of `s`. -/ lemma balanced.hull_subset_of_subset (ht : balanced 𝕜 t) (h : s ⊆ t) : balanced_hull 𝕜 s ⊆ t := λ x hx, by { obtain ⟨r, hr, y, hy, rfl⟩ := mem_balanced_hull_iff.1 hx, exact ht.smul_mem hr (h hy) } end has_smul section module variables [add_comm_group E] [module 𝕜 E] {s : set E} lemma balanced_core_zero_mem (hs : (0 : E) ∈ s) : (0 : E) ∈ balanced_core 𝕜 s := mem_balanced_core_iff.2 ⟨0, balanced_zero, zero_subset.2 hs, zero_mem_zero⟩ lemma balanced_core_nonempty_iff : (balanced_core 𝕜 s).nonempty ↔ (0 : E) ∈ s := ⟨λ h, zero_subset.1 $ (zero_smul_set h).superset.trans $ (balanced_core_balanced s (0 : 𝕜) $ norm_zero.trans_le zero_le_one).trans $ balanced_core_subset _, λ h, ⟨0, balanced_core_zero_mem h⟩⟩ variables (𝕜) lemma subset_balanced_hull [norm_one_class 𝕜] {s : set E} : s ⊆ balanced_hull 𝕜 s := λ _ hx, mem_balanced_hull_iff.2 ⟨1, norm_one.le, _, hx, one_smul _ _⟩ variables {𝕜} lemma balanced_hull.balanced (s : set E) : balanced 𝕜 (balanced_hull 𝕜 s) := begin intros a ha, simp_rw [balanced_hull, smul_set_Union₂, subset_def, mem_Union₂], rintro x ⟨r, hr, hx⟩, rw ←smul_assoc at hx, exact ⟨a • r, (semi_normed_ring.norm_mul _ _).trans (mul_le_one ha (norm_nonneg r) hr), hx⟩, end end module end semi_normed_ring section normed_field variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {s t : set E} @[simp] lemma balanced_core_aux_empty : balanced_core_aux 𝕜 (∅ : set E) = ∅ := begin simp_rw [balanced_core_aux, Inter₂_eq_empty_iff, smul_set_empty], exact λ _, ⟨1, norm_one.ge, not_mem_empty _⟩, end lemma balanced_core_aux_subset (s : set E) : balanced_core_aux 𝕜 s ⊆ s := λ x hx, by simpa only [one_smul] using mem_balanced_core_aux_iff.1 hx 1 norm_one.ge lemma balanced_core_aux_balanced (h0 : (0 : E) ∈ balanced_core_aux 𝕜 s): balanced 𝕜 (balanced_core_aux 𝕜 s) := begin rintro a ha x ⟨y, hy, rfl⟩, obtain rfl | h := eq_or_ne a 0, { rwa zero_smul }, rw mem_balanced_core_aux_iff at ⊢ hy, intros r hr, have h'' : 1 ≤ ∥a⁻¹ • r∥, { rw [norm_smul, norm_inv], exact one_le_mul_of_one_le_of_one_le (one_le_inv (norm_pos_iff.mpr h) ha) hr }, have h' := hy (a⁻¹ • r) h'', rwa [smul_assoc, mem_inv_smul_set_iff₀ h] at h', end lemma balanced_core_aux_maximal (h : t ⊆ s) (ht : balanced 𝕜 t) : t ⊆ balanced_core_aux 𝕜 s := begin refine λ x hx, mem_balanced_core_aux_iff.2 (λ r hr, _), rw mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp $ zero_lt_one.trans_le hr), refine h (ht.smul_mem _ hx), rw norm_inv, exact inv_le_one hr, end lemma balanced_core_subset_balanced_core_aux : balanced_core 𝕜 s ⊆ balanced_core_aux 𝕜 s := balanced_core_aux_maximal (balanced_core_subset s) (balanced_core_balanced s) lemma balanced_core_eq_Inter (hs : (0 : E) ∈ s) : balanced_core 𝕜 s = ⋂ (r : 𝕜) (hr : 1 ≤ ∥r∥), r • s := begin refine balanced_core_subset_balanced_core_aux.antisymm _, refine (balanced_core_aux_balanced _).subset_core_of_subset (balanced_core_aux_subset s), exact balanced_core_subset_balanced_core_aux (balanced_core_zero_mem hs), end lemma subset_balanced_core (ht : (0 : E) ∈ t) (hst : ∀ (a : 𝕜) (ha : ∥a∥ ≤ 1), a • s ⊆ t) : s ⊆ balanced_core 𝕜 t := begin rw balanced_core_eq_Inter ht, refine subset_Inter₂ (λ a ha, _), rw ←smul_inv_smul₀ (norm_pos_iff.mp $ zero_lt_one.trans_le ha) s, refine smul_set_mono (hst _ _), rw [norm_inv], exact inv_le_one ha, end end normed_field end balanced_hull /-! ### Topological properties -/ section topology variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [has_continuous_smul 𝕜 E] {U : set E} protected lemma is_closed.balanced_core (hU : is_closed U) : is_closed (balanced_core 𝕜 U) := begin by_cases h : (0 : E) ∈ U, { rw balanced_core_eq_Inter h, refine is_closed_Inter (λ a, _), refine is_closed_Inter (λ ha, _), have ha' := lt_of_lt_of_le zero_lt_one ha, rw norm_pos_iff at ha', refine is_closed_map_smul_of_ne_zero ha' U hU }, convert is_closed_empty, contrapose! h, exact balanced_core_nonempty_iff.mp (set.ne_empty_iff_nonempty.mp h), end lemma balanced_core_mem_nhds_zero (hU : U ∈ 𝓝 (0 : E)) : balanced_core 𝕜 U ∈ 𝓝 (0 : E) := begin -- Getting neighborhoods of the origin for `0 : 𝕜` and `0 : E` obtain ⟨r, V, hr, hV, hrVU⟩ : ∃ (r : ℝ) (V : set E), 0 < r ∧ V ∈ 𝓝 (0 : E) ∧ ∀ (c : 𝕜) (y : E), ∥c∥ < r → y ∈ V → c • y ∈ U, { have h : filter.tendsto (λ (x : 𝕜 × E), x.fst • x.snd) (𝓝 (0,0)) (𝓝 0), from continuous_smul.tendsto' (0, 0) _ (smul_zero _), simpa only [← prod.exists', ← prod.forall', ← and_imp, ← and.assoc, exists_prop] using h.basis_left (normed_add_comm_group.nhds_zero_basis_norm_lt.prod_nhds ((𝓝 _).basis_sets)) U hU }, rcases normed_field.exists_norm_lt 𝕜 hr with ⟨y, hy₀, hyr⟩, rw [norm_pos_iff] at hy₀, have : y • V ∈ 𝓝 (0 : E) := (set_smul_mem_nhds_zero_iff hy₀).mpr hV, -- It remains to show that `y • V ⊆ balanced_core 𝕜 U` refine filter.mem_of_superset this (subset_balanced_core (mem_of_mem_nhds hU) $ λ a ha, _), rw [smul_smul], rintro _ ⟨z, hz, rfl⟩, refine hrVU _ _ _ hz, rw [norm_mul, ← one_mul r], exact mul_lt_mul' ha hyr (norm_nonneg y) one_pos end variables (𝕜 E) lemma nhds_basis_balanced : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ 𝓝 (0 : E) ∧ balanced 𝕜 s) id := filter.has_basis_self.mpr (λ s hs, ⟨balanced_core 𝕜 s, balanced_core_mem_nhds_zero hs, balanced_core_balanced s, balanced_core_subset s⟩) lemma nhds_basis_closed_balanced [t3_space E] : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ 𝓝 (0 : E) ∧ is_closed s ∧ balanced 𝕜 s) id := begin refine (closed_nhds_basis 0).to_has_basis (λ s hs, _) (λ s hs, ⟨s, ⟨hs.1, hs.2.1⟩, rfl.subset⟩), refine ⟨balanced_core 𝕜 s, ⟨balanced_core_mem_nhds_zero hs.1, _⟩, balanced_core_subset s⟩, exact ⟨hs.2.balanced_core, balanced_core_balanced s⟩ end end topology
c8ac4ccf317136d415359e31c465a5f3d54a39b6
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/multiset/functor.lean
f0b5990c445791e8bf8230ed54f25ecc68a1549c
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,259
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Simon Hudon, Kenny Lau -/ import data.multiset.basic import control.traversable.lemmas import control.traversable.instances /-! # Functoriality of `multiset`. -/ universes u namespace multiset open list instance : functor multiset := { map := @map } @[simp] lemma fmap_def {α' β'} {s : multiset α'} (f : α' → β') : f <$> s = s.map f := rfl instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u → Type u} [applicative F] [is_comm_applicative F] variables {α' β' : Type u} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.cons { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, {x}, bind := @bind, .. multiset.functor } @[simp] lemma pure_def {α} : (pure : α → multiset α) = singleton := rfl @[simp] lemma bind_def {α β} : (>>=) = @bind α β := rfl instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by simp, pure_bind := λ α β x f, by simp [pure], bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_coe {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_mk _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x begin intro, simp [traverse], refl end lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [is_lawful_functor.comp_map, map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) end multiset
300605b5407b2041af327f791222ab9fc0ab75e1
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/partial_explicit1.lean
81f676f9065dcece18c8efb63114c48c3bbb8416
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
130
lean
lemma eq_rect (A : Type) (x : A) (P : A → Type) (f : P x) (y : A) (e : x = y) : P y := @eq.rec_on _ _ (λ (y : A), P y) _ e f
a2ebe822b09c9192a19f9698733b2de621036b22
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/convex/basic.lean
825aa0709af1ee6b4682c21f312b325e397e9727
[]
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
50,401
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.intervals.ord_connected import Mathlib.data.set.intervals.image_preimage import Mathlib.data.complex.module import Mathlib.linear_algebra.affine_space.affine_map import Mathlib.algebra.module.ordered import Mathlib.PostPort universes u u_1 v v' w x u' namespace Mathlib /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_semimodule ℝ β`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ /-! ### Segment -/ /-- Segments in a vector space. -/ def segment {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : set E := set_of fun (z : E) => ∃ (a : ℝ), ∃ (b : ℝ), ∃ (ha : 0 ≤ a), ∃ (hb : 0 ≤ b), ∃ (hab : a + b = 1), a • x + b • y = z theorem segment_symm {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : segment x y = segment y x := sorry theorem left_mem_segment {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : x ∈ segment x y := sorry theorem right_mem_segment {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : y ∈ segment x y := segment_symm y x ▸ left_mem_segment y x theorem segment_same {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) : segment x x = singleton x := sorry theorem segment_eq_image {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : segment x y = (fun (θ : ℝ) => (1 - θ) • x + θ • y) '' set.Icc 0 1 := sorry theorem segment_eq_image' {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : segment x y = (fun (θ : ℝ) => x + θ • (y - x)) '' set.Icc 0 1 := sorry theorem segment_eq_image₂ {E : Type u} [add_comm_group E] [vector_space ℝ E] (x : E) (y : E) : segment x y = (fun (p : ℝ × ℝ) => prod.fst p • x + prod.snd p • y) '' set_of fun (p : ℝ × ℝ) => 0 ≤ prod.fst p ∧ 0 ≤ prod.snd p ∧ prod.fst p + prod.snd p = 1 := sorry theorem segment_eq_Icc {a : ℝ} {b : ℝ} (h : a ≤ b) : segment a b = set.Icc a b := sorry theorem segment_eq_Icc' (a : ℝ) (b : ℝ) : segment a b = set.Icc (min a b) (max a b) := sorry theorem segment_eq_interval (a : ℝ) (b : ℝ) : segment a b = set.interval a b := segment_eq_Icc' a b theorem mem_segment_translate {E : Type u} [add_comm_group E] [vector_space ℝ E] (a : E) {x : E} {b : E} {c : E} : a + x ∈ segment (a + b) (a + c) ↔ x ∈ segment b c := sorry theorem segment_translate_preimage {E : Type u} [add_comm_group E] [vector_space ℝ E] (a : E) (b : E) (c : E) : (fun (x : E) => a + x) ⁻¹' segment (a + b) (a + c) = segment b c := set.ext fun (x : E) => mem_segment_translate a theorem segment_translate_image {E : Type u} [add_comm_group E] [vector_space ℝ E] (a : E) (b : E) (c : E) : (fun (x : E) => a + x) '' segment b c = segment (a + b) (a + c) := Eq.subst (segment_translate_preimage a b c) (set.image_preimage_eq (segment (a + b) (a + c))) (add_left_surjective a) /-! ### Convexity of sets -/ /-- Convexity of sets. -/ def convex {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : set E) := ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s theorem convex_iff_forall_pos {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} : convex s ↔ ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := sorry theorem convex_iff_segment_subset {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} : convex s ↔ ∀ {x y : E}, x ∈ s → y ∈ s → segment x y ⊆ s := sorry theorem convex.segment_subset {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (h : convex s) {x : E} {y : E} (hx : x ∈ s) (hy : y ∈ s) : segment x y ⊆ s := iff.mp convex_iff_segment_subset h x y hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ theorem convex_iff_pointwise_add_subset {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} : convex s ↔ ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := sorry /-- Alternative definition of set convexity, using division. -/ theorem convex_iff_div {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} : convex s ↔ ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → 0 < a + b → (a / (a + b)) • x + (b / (a + b)) • y ∈ s := sorry /-! ### Examples of convex sets -/ theorem convex_empty {E : Type u} [add_comm_group E] [vector_space ℝ E] : convex ∅ := sorry theorem convex_singleton {E : Type u} [add_comm_group E] [vector_space ℝ E] (c : E) : convex (singleton c) := sorry theorem convex_univ {E : Type u} [add_comm_group E] [vector_space ℝ E] : convex set.univ := fun (_x _x_1 : E) (_x : _x ∈ set.univ) (_x : _x_1 ∈ set.univ) (_x _x_2 : ℝ) (_x_3 : 0 ≤ _x) (_x_4 : 0 ≤ _x_2) (_x : _x + _x_2 = 1) => trivial theorem convex.inter {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : set E} (hs : convex s) (ht : convex t) : convex (s ∩ t) := fun (x y : E) (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) => { left := hs (and.left hx) (and.left hy) ha hb hab, right := ht (and.right hx) (and.right hy) ha hb hab } theorem convex_sInter {E : Type u} [add_comm_group E] [vector_space ℝ E] {S : set (set E)} (h : ∀ (s : set E), s ∈ S → convex s) : convex (⋂₀S) := fun (x y : E) (hx : x ∈ ⋂₀S) (hy : y ∈ ⋂₀S) (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) (s : set E) (hs : s ∈ S) => h s hs (hx s hs) (hy s hs) ha hb hab theorem convex_Inter {E : Type u} [add_comm_group E] [vector_space ℝ E] {ι : Sort u_1} {s : ι → set E} (h : ∀ (i : ι), convex (s i)) : convex (set.Inter fun (i : ι) => s i) := Eq.subst (set.sInter_range s) convex_sInter (iff.mpr set.forall_range_iff h) theorem convex.prod {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (set.prod s t) := sorry theorem convex.combo_to_vadd {E : Type u} [add_comm_group E] [vector_space ℝ E] {a : ℝ} {b : ℝ} {x : E} {y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := sorry /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ theorem convex.combo_affine_apply {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {a : ℝ} {b : ℝ} {x : E} {y : E} {f : affine_map ℝ E F} (h : a + b = 1) : coe_fn f (a • x + b • y) = a • coe_fn f x + b • coe_fn f y := sorry /-- The preimage of a convex set under an affine map is convex. -/ theorem convex.affine_preimage {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] (f : affine_map ℝ E F) {s : set F} (hs : convex s) : convex (⇑f ⁻¹' s) := sorry /-- The image of a convex set under an affine map is convex. -/ theorem convex.affine_image {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] (f : affine_map ℝ E F) {s : set E} (hs : convex s) : convex (⇑f '' s) := sorry theorem convex.linear_image {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} (hs : convex s) (f : linear_map ℝ E F) : convex (⇑f '' s) := convex.affine_image (linear_map.to_affine_map f) hs theorem convex.is_linear_image {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := convex.linear_image hs (is_linear_map.mk' f hf) theorem convex.linear_preimage {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set F} (hs : convex s) (f : linear_map ℝ E F) : convex (⇑f ⁻¹' s) := convex.affine_preimage (linear_map.to_affine_map f) hs theorem convex.is_linear_preimage {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f ⁻¹' s) := convex.linear_preimage hs (is_linear_map.mk' f hf) theorem convex.neg {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) : convex ((fun (z : E) => -z) '' s) := convex.is_linear_image hs is_linear_map.is_linear_map_neg theorem convex.neg_preimage {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) : convex ((fun (z : E) => -z) ⁻¹' s) := convex.is_linear_preimage hs is_linear_map.is_linear_map_neg theorem convex.smul {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (c : ℝ) (hs : convex s) : convex (c • s) := convex.linear_image hs (coe_fn (linear_map.lsmul ℝ E) c) theorem convex.smul_preimage {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (c : ℝ) (hs : convex s) : convex ((fun (z : E) => c • z) ⁻¹' s) := convex.linear_preimage hs (coe_fn (linear_map.lsmul ℝ E) c) theorem convex.add {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := eq.mpr (id (Eq._oldrec (Eq.refl (convex (s + t))) (Eq.symm set.add_image_prod))) (convex.is_linear_image (convex.prod hs ht) is_linear_map.is_linear_map_add) theorem convex.sub {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : set E} (hs : convex s) (ht : convex t) : convex ((fun (x : E × E) => prod.fst x - prod.snd x) '' set.prod s t) := convex.is_linear_image (convex.prod hs ht) is_linear_map.is_linear_map_sub theorem convex.translate {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) (z : E) : convex ((fun (x : E) => z + x) '' s) := convex.affine_image (affine_map.const ℝ E z +ᵥ affine_map.id ℝ E) hs /-- The translation of a convex set is also convex. -/ theorem convex.translate_preimage_right {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) (a : E) : convex ((fun (z : E) => a + z) ⁻¹' s) := convex.affine_preimage (affine_map.const ℝ E a +ᵥ affine_map.id ℝ E) hs /-- The translation of a convex set is also convex. -/ theorem convex.translate_preimage_left {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) (a : E) : convex ((fun (z : E) => z + a) ⁻¹' s) := sorry theorem convex.affinity {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) (z : E) (c : ℝ) : convex ((fun (x : E) => z + c • x) '' s) := convex.affine_image (affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E) hs theorem real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ set.ord_connected s := sorry theorem convex.ord_connected {s : set ℝ} : convex s → set.ord_connected s := iff.mp real.convex_iff_ord_connected theorem convex_Iio (r : ℝ) : convex (set.Iio r) := set.ord_connected.convex set.ord_connected_Iio theorem convex_Ioi (r : ℝ) : convex (set.Ioi r) := set.ord_connected.convex set.ord_connected_Ioi theorem convex_Iic (r : ℝ) : convex (set.Iic r) := set.ord_connected.convex set.ord_connected_Iic theorem convex_Ici (r : ℝ) : convex (set.Ici r) := set.ord_connected.convex set.ord_connected_Ici theorem convex_Ioo (r : ℝ) (s : ℝ) : convex (set.Ioo r s) := set.ord_connected.convex set.ord_connected_Ioo theorem convex_Ico (r : ℝ) (s : ℝ) : convex (set.Ico r s) := set.ord_connected.convex set.ord_connected_Ico theorem convex_Ioc (r : ℝ) (s : ℝ) : convex (set.Ioc r s) := set.ord_connected.convex set.ord_connected_Ioc theorem convex_Icc (r : ℝ) (s : ℝ) : convex (set.Icc r s) := set.ord_connected.convex set.ord_connected_Icc theorem convex_interval (r : ℝ) (s : ℝ) : convex (set.interval r s) := set.ord_connected.convex set.ord_connected_interval theorem convex_segment {E : Type u} [add_comm_group E] [vector_space ℝ E] (a : E) (b : E) : convex (segment a b) := sorry theorem convex_halfspace_lt {E : Type u} [add_comm_group E] [vector_space ℝ E] {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex (set_of fun (w : E) => f w < r) := convex.is_linear_preimage (convex_Iio r) h theorem convex_halfspace_le {E : Type u} [add_comm_group E] [vector_space ℝ E] {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex (set_of fun (w : E) => f w ≤ r) := convex.is_linear_preimage (convex_Iic r) h theorem convex_halfspace_gt {E : Type u} [add_comm_group E] [vector_space ℝ E] {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex (set_of fun (w : E) => r < f w) := convex.is_linear_preimage (convex_Ioi r) h theorem convex_halfspace_ge {E : Type u} [add_comm_group E] [vector_space ℝ E] {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex (set_of fun (w : E) => r ≤ f w) := convex.is_linear_preimage (convex_Ici r) h theorem convex_hyperplane {E : Type u} [add_comm_group E] [vector_space ℝ E] {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex (set_of fun (w : E) => f w = r) := id (eq.mpr (id (Eq._oldrec (Eq.refl (convex (f ⁻¹' set_of fun (p : ℝ) => p = r))) set.set_of_eq_eq_singleton)) (convex.is_linear_preimage (convex_singleton r) h)) theorem convex_halfspace_re_lt (r : ℝ) : convex (set_of fun (c : ℂ) => complex.re c < r) := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) r theorem convex_halfspace_re_le (r : ℝ) : convex (set_of fun (c : ℂ) => complex.re c ≤ r) := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) r theorem convex_halfspace_re_gt (r : ℝ) : convex (set_of fun (c : ℂ) => r < complex.re c) := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) r theorem convex_halfspace_re_lge (r : ℝ) : convex (set_of fun (c : ℂ) => r ≤ complex.re c) := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) r theorem convex_halfspace_im_lt (r : ℝ) : convex (set_of fun (c : ℂ) => complex.im c < r) := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) r theorem convex_halfspace_im_le (r : ℝ) : convex (set_of fun (c : ℂ) => complex.im c ≤ r) := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) r theorem convex_halfspace_im_gt (r : ℝ) : convex (set_of fun (c : ℂ) => r < complex.im c) := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) r theorem convex_halfspace_im_lge (r : ℝ) : convex (set_of fun (c : ℂ) => r ≤ complex.im c) := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) r /-! ### Convex combinations in intervals -/ theorem convex.combo_self {α : Type v'} [linear_ordered_field α] (a : α) {x : α} {y : α} (h : x + y = 1) : a = x * a + y * a := sorry /-- If `x` is in an `Ioo`, it can be expressed as a convex combination of the endpoints. -/ theorem convex.mem_Ioo {α : Type v'} [linear_ordered_field α] {a : α} {b : α} {x : α} (h : a < b) : x ∈ set.Ioo a b ↔ ∃ (x_a : α), ∃ (x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := sorry /-- If `x` is in an `Ioc`, it can be expressed as a convex combination of the endpoints. -/ theorem convex.mem_Ioc {α : Type v'} [linear_ordered_field α] {a : α} {b : α} {x : α} (h : a < b) : x ∈ set.Ioc a b ↔ ∃ (x_a : α), ∃ (x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := sorry /-- If `x` is in an `Ico`, it can be expressed as a convex combination of the endpoints. -/ theorem convex.mem_Ico {α : Type v'} [linear_ordered_field α] {a : α} {b : α} {x : α} (h : a < b) : x ∈ set.Ico a b ↔ ∃ (x_a : α), ∃ (x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := sorry /-- If `x` is in an `Icc`, it can be expressed as a convex combination of the endpoints. -/ theorem convex.mem_Icc {α : Type v'} [linear_ordered_field α] {a : α} {b : α} {x : α} (h : a ≤ b) : x ∈ set.Icc a b ↔ ∃ (x_a : α), ∃ (x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := sorry theorem submodule.convex {E : Type u} [add_comm_group E] [vector_space ℝ E] (K : submodule ℝ E) : convex ↑K := id fun (x y : E) (ᾰ : x ∈ ↑K) (ᾰ_1 : y ∈ ↑K) (a b : ℝ) (ᾰ_2 : 0 ≤ a) (ᾰ_3 : 0 ≤ b) (ᾰ_4 : a + b = 1) => submodule.add_mem K (submodule.smul_mem K a ᾰ) (submodule.smul_mem K b ᾰ_1) theorem subspace.convex {E : Type u} [add_comm_group E] [vector_space ℝ E] (K : subspace ℝ E) : convex ↑K := submodule.convex K /-! ### Convex and concave functions -/ /-- Convexity of functions -/ def convex_on {E : Type u} [add_comm_group E] [vector_space ℝ E] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] (s : set E) (f : E → β) := convex s ∧ ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on {E : Type u} [add_comm_group E] [vector_space ℝ E] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] (s : set E) (f : E → β) := convex s ∧ ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) /-- A function `f` is concave iff `-f` is convex. -/ @[simp] theorem neg_convex_on_iff {E : Type u} [add_comm_group E] [vector_space ℝ E] {γ : Type u_1} [ordered_add_comm_group γ] [semimodule ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := sorry /-- A function `f` is concave iff `-f` is convex. -/ @[simp] theorem neg_concave_on_iff {E : Type u} [add_comm_group E] [vector_space ℝ E] {γ : Type u_1} [ordered_add_comm_group γ] [semimodule ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f := eq.mpr (id (Eq._oldrec (Eq.refl (concave_on s (-f) ↔ convex_on s f)) (Eq.symm (propext (neg_convex_on_iff s (-f)))))) (eq.mpr (id (Eq._oldrec (Eq.refl (convex_on s ( --f) ↔ convex_on s f)) (neg_neg f))) (iff.refl (convex_on s f))) theorem convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := sorry theorem concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := sorry theorem convex_on_const {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] (c : β) (hs : convex s) : convex_on s fun (x : E) => c := sorry theorem concave_on_const {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] (c : β) (hs : convex s) : concave_on s fun (x : E) => c := convex_on_const c hs theorem convex_on_iff_div {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} : convex_on s f ↔ convex s ∧ ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a / (a + b)) • x + (b / (a + b)) • y) ≤ (a / (a + b)) • f x + (b / (a + b)) • f y := sorry theorem concave_on_iff_div {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} : concave_on s f ↔ convex s ∧ ∀ {x y : E}, x ∈ s → y ∈ s → ∀ {a b : ℝ}, 0 ≤ a → 0 ≤ b → 0 < a + b → (a / (a + b)) • f x + (b / (a + b)) • f y ≤ f ((a / (a + b)) • x + (b / (a + b)) • y) := convex_on_iff_div /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ theorem linear_order.convex_on_of_lt {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ {x y : E}, x ∈ s → y ∈ s → x < y → ∀ {a b : ℝ}, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := sorry /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ theorem linear_order.concave_on_of_lt {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ {x y : E}, x ∈ s → y ∈ s → x < y → ∀ {a b : ℝ}, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := linear_order.convex_on_of_lt hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ theorem convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := sorry /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ theorem convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x : ℝ} {y : ℝ} {z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := sorry /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ theorem convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := { mp := convex_on.slope_mono_adjacent, mpr := convex_on_real_of_slope_mono_adjacent hs } /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ theorem concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := sorry /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ theorem concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x : ℝ} {y : ℝ} {z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := sorry /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ theorem concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := { mp := concave_on.slope_mono_adjacent, mpr := concave_on_real_of_slope_mono_adjacent hs } theorem convex_on.subset {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {t : set E} {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := { left := h_convex, right := fun (x y : E) (hx : x ∈ s) (hy : y ∈ s) => and.right h_convex_on x y (h_subset hx) (h_subset hy) } theorem concave_on.subset {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {t : set E} {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := convex_on.subset h_concave_on h_subset h_convex theorem convex_on.add {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} {g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s fun (x : E) => f x + g x := sorry theorem concave_on.add {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} {g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s fun (x : E) => f x + g x := convex_on.add hf hg theorem convex_on.smul {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] [ordered_semimodule ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s fun (x : E) => c • f x := sorry theorem concave_on.smul {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] [ordered_semimodule ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s fun (x : E) => c • f x := convex_on.smul hc hf /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ theorem convex_on.le_on_segment' {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} {x : E} {y : E} {a : ℝ} {b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := sorry /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ theorem concave_on.le_on_segment' {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} {x : E} {y : E} {a : ℝ} {b : ℝ} (hf : concave_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := convex_on.le_on_segment' hf hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ theorem convex_on.le_on_segment {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) {x : E} {y : E} {z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ segment x y) : f z ≤ max (f x) (f y) := sorry /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ theorem concave_on.le_on_segment {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) {x : E} {y : E} {z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ segment x y) : min (f x) (f y) ≤ f z := convex_on.le_on_segment hf hx hy hz theorem convex_on.convex_le {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] [ordered_semimodule ℝ β] {f : E → β} (hf : convex_on s f) (r : β) : convex (has_sep.sep (fun (x : E) => f x ≤ r) s) := sorry theorem concave_on.concave_le {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] [ordered_semimodule ℝ β] {f : E → β} (hf : concave_on s f) (r : β) : convex (has_sep.sep (fun (x : E) => r ≤ f x) s) := convex_on.convex_le hf r theorem convex_on.convex_lt {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [ordered_cancel_add_comm_monoid γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex (has_sep.sep (fun (x : E) => f x < r) s) := sorry theorem concave_on.convex_lt {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [ordered_cancel_add_comm_monoid γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex (has_sep.sep (fun (x : E) => r < f x) s) := convex_on.convex_lt hf r theorem convex_on.convex_epigraph {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) : convex (set_of fun (p : E × γ) => prod.fst p ∈ s ∧ f (prod.fst p) ≤ prod.snd p) := sorry theorem concave_on.convex_hypograph {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) : convex (set_of fun (p : E × γ) => prod.fst p ∈ s ∧ prod.snd p ≤ f (prod.fst p)) := convex_on.convex_epigraph hf theorem convex_on_iff_convex_epigraph {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} : convex_on s f ↔ convex (set_of fun (p : E × γ) => prod.fst p ∈ s ∧ f (prod.fst p) ≤ prod.snd p) := sorry theorem concave_on_iff_convex_hypograph {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {γ : Type u_1} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} : concave_on s f ↔ convex (set_of fun (p : E × γ) => prod.fst p ∈ s ∧ prod.snd p ≤ f (prod.fst p)) := convex_on_iff_convex_epigraph /-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/ theorem convex_on.comp_affine_map {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : F → β} (g : affine_map ℝ E F) {s : set F} (hf : convex_on s f) : convex_on (⇑g ⁻¹' s) (f ∘ ⇑g) := sorry /-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/ theorem concave_on.comp_affine_map {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : F → β} (g : affine_map ℝ E F) {s : set F} (hf : concave_on s f) : concave_on (⇑g ⁻¹' s) (f ∘ ⇑g) := convex_on.comp_affine_map g hf /-- If `g` is convex on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ theorem convex_on.comp_linear_map {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {g : F → β} {s : set F} (hg : convex_on s g) (f : linear_map ℝ E F) : convex_on (⇑f ⁻¹' s) (g ∘ ⇑f) := convex_on.comp_affine_map (linear_map.to_affine_map f) hg /-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ theorem concave_on.comp_linear_map {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {g : F → β} {s : set F} (hg : concave_on s g) (f : linear_map ℝ E F) : concave_on (⇑f ⁻¹' s) (g ∘ ⇑f) := concave_on.comp_affine_map (linear_map.to_affine_map f) hg /-- If a function is convex on `s`, it remains convex after a translation. -/ theorem convex_on.translate_right {E : Type u} [add_comm_group E] [vector_space ℝ E] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((fun (z : E) => a + z) ⁻¹' s) (f ∘ fun (z : E) => a + z) := convex_on.comp_affine_map (affine_map.const ℝ E a +ᵥ affine_map.id ℝ E) hf /-- If a function is concave on `s`, it remains concave after a translation. -/ theorem concave_on.translate_right {E : Type u} [add_comm_group E] [vector_space ℝ E] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((fun (z : E) => a + z) ⁻¹' s) (f ∘ fun (z : E) => a + z) := concave_on.comp_affine_map (affine_map.const ℝ E a +ᵥ affine_map.id ℝ E) hf /-- If a function is convex on `s`, it remains convex after a translation. -/ theorem convex_on.translate_left {E : Type u} [add_comm_group E] [vector_space ℝ E] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((fun (z : E) => a + z) ⁻¹' s) (f ∘ fun (z : E) => z + a) := sorry /-- If a function is concave on `s`, it remains concave after a translation. -/ theorem concave_on.translate_left {E : Type u} [add_comm_group E] [vector_space ℝ E] {β : Type u_1} [ordered_add_comm_monoid β] [semimodule ℝ β] {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((fun (z : E) => a + z) ⁻¹' s) (f ∘ fun (z : E) => z + a) := sorry /-! ### Center of mass -/ /-- Center of mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ def finset.center_mass {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (finset.sum t fun (i : ι) => w i)⁻¹ • finset.sum t fun (i : ι) => w i • z i theorem finset.center_mass_empty {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (w : ι → ℝ) (z : ι → E) : finset.center_mass ∅ w z = 0 := sorry theorem finset.center_mass_pair {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (i : ι) (j : ι) (w : ι → ℝ) (z : ι → E) (hne : i ≠ j) : finset.center_mass (insert i (singleton j)) w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := sorry theorem finset.center_mass_insert {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (i : ι) (t : finset ι) {w : ι → ℝ} (z : ι → E) (ha : ¬i ∈ t) (hw : (finset.sum t fun (j : ι) => w j) ≠ 0) : finset.center_mass (insert i t) w z = (w i / (w i + finset.sum t fun (j : ι) => w j)) • z i + ((finset.sum t fun (j : ι) => w j) / (w i + finset.sum t fun (j : ι) => w j)) • finset.center_mass t w z := sorry theorem finset.center_mass_singleton {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (i : ι) {w : ι → ℝ} (z : ι → E) (hw : w i ≠ 0) : finset.center_mass (singleton i) w z = z i := sorry theorem finset.center_mass_eq_of_sum_1 {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (t : finset ι) {w : ι → ℝ} (z : ι → E) (hw : (finset.sum t fun (i : ι) => w i) = 1) : finset.center_mass t w z = finset.sum t fun (i : ι) => w i • z i := sorry theorem finset.center_mass_smul {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (c : ℝ) (t : finset ι) {w : ι → ℝ} (z : ι → E) : (finset.center_mass t w fun (i : ι) => c • z i) = c • finset.center_mass t w z := sorry /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ theorem finset.center_mass_segment' {E : Type u} {ι : Type w} {ι' : Type x} [add_comm_group E] [vector_space ℝ E] (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : (finset.sum s fun (i : ι) => ws i) = 1) (hwt : (finset.sum t fun (i : ι') => wt i) = 1) (a : ℝ) (b : ℝ) (hab : a + b = 1) : a • finset.center_mass s ws zs + b • finset.center_mass t wt zt = finset.center_mass (finset.map function.embedding.inl s ∪ finset.map function.embedding.inr t) (sum.elim (fun (i : ι) => a * ws i) fun (j : ι') => b * wt j) (sum.elim zs zt) := sorry /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ theorem finset.center_mass_segment {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (s : finset ι) (w₁ : ι → ℝ) (w₂ : ι → ℝ) (z : ι → E) (hw₁ : (finset.sum s fun (i : ι) => w₁ i) = 1) (hw₂ : (finset.sum s fun (i : ι) => w₂ i) = 1) (a : ℝ) (b : ℝ) (hab : a + b = 1) : a • finset.center_mass s w₁ z + b • finset.center_mass s w₂ z = finset.center_mass s (fun (i : ι) => a * w₁ i + b * w₂ i) z := sorry theorem finset.center_mass_ite_eq {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] (i : ι) (t : finset ι) (z : ι → E) (hi : i ∈ t) : finset.center_mass t (fun (j : ι) => ite (i = j) 1 0) z = z i := sorry theorem finset.center_mass_subset {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {t : finset ι} {w : ι → ℝ} (z : ι → E) {t' : finset ι} (ht : t ⊆ t') (h : ∀ (i : ι), i ∈ t' → ¬i ∈ t → w i = 0) : finset.center_mass t w z = finset.center_mass t' w z := sorry theorem finset.center_mass_filter_ne_zero {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {t : finset ι} {w : ι → ℝ} (z : ι → E) : finset.center_mass (finset.filter (fun (i : ι) => w i ≠ 0) t) w z = finset.center_mass t w z := sorry /-- The center of mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ theorem convex.center_mass_mem {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : finset ι} {w : ι → ℝ} {z : ι → E} (hs : convex s) : (∀ (i : ι), i ∈ t → 0 ≤ w i) → (0 < finset.sum t fun (i : ι) => w i) → (∀ (i : ι), i ∈ t → z i ∈ s) → finset.center_mass t w z ∈ s := sorry theorem convex.sum_mem {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : finset ι} {w : ι → ℝ} {z : ι → E} (hs : convex s) (h₀ : ∀ (i : ι), i ∈ t → 0 ≤ w i) (h₁ : (finset.sum t fun (i : ι) => w i) = 1) (hz : ∀ (i : ι), i ∈ t → z i ∈ s) : (finset.sum t fun (i : ι) => w i • z i) ∈ s := sorry theorem convex_iff_sum_mem {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} : convex s ↔ ∀ (t : finset E) (w : E → ℝ), (∀ (i : E), i ∈ t → 0 ≤ w i) → (finset.sum t fun (i : E) => w i) = 1 → (∀ (x : E), x ∈ t → x ∈ s) → (finset.sum t fun (x : E) => w x • x) ∈ s := sorry /-- Jensen's inequality, `finset.center_mass` version. -/ theorem convex_on.map_center_mass_le {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : finset ι} {w : ι → ℝ} {z : ι → E} {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ (i : ι), i ∈ t → 0 ≤ w i) (hpos : 0 < finset.sum t fun (i : ι) => w i) (hmem : ∀ (i : ι), i ∈ t → z i ∈ s) : f (finset.center_mass t w z) ≤ finset.center_mass t w (f ∘ z) := sorry /-- Jensen's inequality, `finset.sum` version. -/ theorem convex_on.map_sum_le {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : finset ι} {w : ι → ℝ} {z : ι → E} {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ (i : ι), i ∈ t → 0 ≤ w i) (h₁ : (finset.sum t fun (i : ι) => w i) = 1) (hmem : ∀ (i : ι), i ∈ t → z i ∈ s) : f (finset.sum t fun (i : ι) => w i • z i) ≤ finset.sum t fun (i : ι) => w i * f (z i) := sorry /-- If a function `f` is convex on `s` takes value `y` at the center of mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ theorem convex_on.exists_ge_of_center_mass {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : finset ι} {w : ι → ℝ} {z : ι → E} {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ (i : ι), i ∈ t → 0 ≤ w i) (hws : 0 < finset.sum t fun (i : ι) => w i) (hz : ∀ (i : ι), i ∈ t → z i ∈ s) : ∃ (i : ι), ∃ (H : i ∈ t), f (finset.center_mass t w z) ≤ f (z i) := sorry /-! ### Convex hull -/ /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : set E) : set E := set.Inter fun (t : set E) => set.Inter fun (hst : s ⊆ t) => set.Inter fun (ht : convex t) => t theorem subset_convex_hull {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : set E) : s ⊆ convex_hull s := set.subset_Inter fun (t : set E) => set.subset_Inter fun (hst : s ⊆ t) => set.subset_Inter fun (ht : convex t) => hst theorem convex_convex_hull {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : set E) : convex (convex_hull s) := convex_Inter fun (t : set E) => convex_Inter fun (ht : s ⊆ t) => convex_Inter id theorem convex_hull_min {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : set E} (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := set.Inter_subset_of_subset t (set.Inter_subset_of_subset hst (set.Inter_subset (fun (ht : convex t) => t) ht)) theorem convex_hull_mono {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {t : set E} (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull_min (set.subset.trans hst (subset_convex_hull t)) (convex_convex_hull t) theorem convex.convex_hull_eq {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl s) hs) (subset_convex_hull s) @[simp] theorem convex_hull_singleton {E : Type u} [add_comm_group E] [vector_space ℝ E] {x : E} : convex_hull (singleton x) = singleton x := convex.convex_hull_eq (convex_singleton x) theorem is_linear_map.image_convex_hull {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} {f : E → F} (hf : is_linear_map ℝ f) : f '' convex_hull s = convex_hull (f '' s) := sorry theorem linear_map.image_convex_hull {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {s : set E} (f : linear_map ℝ E F) : ⇑f '' convex_hull s = convex_hull (⇑f '' s) := is_linear_map.image_convex_hull (linear_map.is_linear f) theorem finset.center_mass_mem_convex_hull {E : Type u} {ι : Type w} [add_comm_group E] [vector_space ℝ E] {s : set E} (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ (i : ι), i ∈ t → 0 ≤ w i) (hws : 0 < finset.sum t fun (i : ι) => w i) {z : ι → E} (hz : ∀ (i : ι), i ∈ t → z i ∈ s) : finset.center_mass t w z ∈ convex_hull s := convex.center_mass_mem (convex_convex_hull s) hw₀ hws fun (i : ι) (hi : i ∈ t) => subset_convex_hull s (hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ theorem convex_hull_eq {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : set E) : convex_hull s = set_of fun (x : E) => ∃ (ι : Type u'), ∃ (t : finset ι), ∃ (w : ι → ℝ), ∃ (z : ι → E), ∃ (hw₀ : ∀ (i : ι), i ∈ t → 0 ≤ w i), ∃ (hw₁ : (finset.sum t fun (i : ι) => w i) = 1), ∃ (hz : ∀ (i : ι), i ∈ t → z i ∈ s), finset.center_mass t w z = x := sorry /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ theorem convex_on.exists_ge_of_mem_convex_hull {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x : E} (hx : x ∈ convex_hull s) : ∃ (y : E), ∃ (H : y ∈ s), f x ≤ f y := sorry theorem finset.convex_hull_eq {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : finset E) : convex_hull ↑s = set_of fun (x : E) => ∃ (w : E → ℝ), ∃ (hw₀ : ∀ (y : E), y ∈ s → 0 ≤ w y), ∃ (hw₁ : (finset.sum s fun (y : E) => w y) = 1), finset.center_mass s w id = x := sorry theorem set.finite.convex_hull_eq {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : set.finite s) : convex_hull s = set_of fun (x : E) => ∃ (w : E → ℝ), ∃ (hw₀ : ∀ (y : E), y ∈ s → 0 ≤ w y), ∃ (hw₁ : (finset.sum (set.finite.to_finset hs) fun (y : E) => w y) = 1), finset.center_mass (set.finite.to_finset hs) w id = x := sorry theorem convex_hull_eq_union_convex_hull_finite_subsets {E : Type u} [add_comm_group E] [vector_space ℝ E] (s : set E) : convex_hull s = set.Union fun (t : finset E) => set.Union fun (w : ↑t ⊆ s) => convex_hull ↑t := sorry theorem is_linear_map.convex_hull_image {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := sorry theorem linear_map.convex_hull_image {E : Type u} {F : Type v} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] (f : linear_map ℝ E F) (s : set E) : convex_hull (⇑f '' s) = ⇑f '' convex_hull s := is_linear_map.convex_hull_image (linear_map.is_linear f) s /-! ### Simplex -/ /-- The standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type u_1) [fintype ι] : set (ι → ℝ) := set_of fun (f : ι → ℝ) => (∀ (x : ι), 0 ≤ f x) ∧ (finset.sum finset.univ fun (x : ι) => f x) = 1 theorem std_simplex_eq_inter (ι : Type w) [fintype ι] : std_simplex ι = (set.Inter fun (x : ι) => set_of fun (f : ι → ℝ) => 0 ≤ f x) ∩ set_of fun (f : ι → ℝ) => (finset.sum finset.univ fun (x : ι) => f x) = 1 := sorry theorem convex_std_simplex (ι : Type w) [fintype ι] : convex (std_simplex ι) := sorry theorem ite_eq_mem_std_simplex {ι : Type w} [fintype ι] (i : ι) : (fun (j : ι) => ite (i = j) 1 0) ∈ std_simplex ι := sorry /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ theorem convex_hull_basis_eq_std_simplex {ι : Type w} [fintype ι] : convex_hull (set.range fun (i j : ι) => ite (i = j) 1 0) = std_simplex ι := sorry /-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ theorem set.finite.convex_hull_eq_image {E : Type u} [add_comm_group E] [vector_space ℝ E] {s : set E} (hs : set.finite s) : convex_hull s = ⇑(finset.sum finset.univ fun (x : ↥s) => linear_map.smul_right (linear_map.proj x) (subtype.val x)) '' std_simplex ↥s := sorry /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ theorem mem_Icc_of_mem_std_simplex {ι : Type w} [fintype ι] {f : ι → ℝ} (hf : f ∈ std_simplex ι) (x : ι) : f x ∈ set.Icc 0 1 := { left := and.left hf x, right := and.right hf ▸ finset.single_le_sum (fun (y : ι) (hy : y ∈ finset.univ) => and.left hf y) (finset.mem_univ x) }
9557309cf1ff494a04b178fde4f317d8f768efea
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebraic_geometry/Spec.lean
fcc2c42962b83b541baa5848ac9cf01cff64a0c8
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,407
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.algebraic_geometry.locally_ringed_space import Mathlib.algebraic_geometry.structure_sheaf import Mathlib.data.equiv.transfer_instance import Mathlib.PostPort universes u_1 namespace Mathlib /-! # $Spec R$ as a `LocallyRingedSpace` We bundle the `structure_sheaf R` construction for `R : CommRing` as a `LocallyRingedSpace`. ## Future work Make it a functor. -/ namespace algebraic_geometry /-- Spec of a commutative ring, as a `SheafedSpace`. -/ def Spec.SheafedSpace (R : CommRing) : SheafedSpace CommRing := SheafedSpace.mk (PresheafedSpace.mk (Top.of (prime_spectrum ↥R)) (Top.sheaf.presheaf (structure_sheaf ↥R))) (Top.sheaf.sheaf_condition (structure_sheaf ↥R)) /-- Spec of a commutative ring, as a `PresheafedSpace`. -/ def Spec.PresheafedSpace (R : CommRing) : PresheafedSpace CommRing := SheafedSpace.to_PresheafedSpace (Spec.SheafedSpace R) /-- Spec of a commutative ring, as a `LocallyRingedSpace`. -/ def Spec.LocallyRingedSpace (R : CommRing) : LocallyRingedSpace := LocallyRingedSpace.mk (SheafedSpace.mk (SheafedSpace.to_PresheafedSpace (Spec.SheafedSpace R)) (SheafedSpace.sheaf_condition (Spec.SheafedSpace R))) sorry
5d52fc2bb6f919fd83c234f26b96478ad1b7f671
09b3e1beaeff2641ac75019c9f735d79d508071d
/Mathlib.lean
9188d07654fdcf9352c4a280ae8b06fcf4872c97
[ "Apache-2.0" ]
permissive
abentkamp/mathlib4
b819079cc46426b3c5c77413504b07541afacc19
f8294a67548f8f3d1f5913677b070a2ef5bcf120
refs/heads/master
1,685,309,252,764
1,623,232,534,000
1,623,232,534,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
813
lean
import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Defs import Mathlib.Algebra.GroupWithZero.Defs import Mathlib.Algebra.Ring.Basic import Mathlib.Data.Array.Basic import Mathlib.Data.ByteArray import Mathlib.Data.Char import Mathlib.Data.Equiv.Basic import Mathlib.Data.Equiv.Functor import Mathlib.Data.List.Basic import Mathlib.Data.Nat.Basic import Mathlib.Data.UInt import Mathlib.Function import Mathlib.Logic.Basic import Mathlib.Logic.Function.Basic import Mathlib.Mem import Mathlib.Set import Mathlib.Tactic.Basic import Mathlib.Tactic.Block import Mathlib.Tactic.NoMatch import Mathlib.Tactic.NormNum import Mathlib.Tactic.OpenPrivate import Mathlib.Tactic.PrintPrefix import Mathlib.Tactic.Split import Mathlib.Tactic.Spread import Mathlib.Tactic.SudoSetOption import Mathlib.Util.Export
21b21be3fd2ef6e9720cefd04fff69d2b4326c19
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/local_context.lean
80cca54badd8e84a317e4c156e970013e4bf638e
[ "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
2,096
lean
prelude import init.meta.name init.meta.expr init.data.option.basic meta structure local_decl := (unique_name : name) (pp_name : name) (type : expr) (value : option expr) (bi : binder_info) (idx : nat) meta def local_decl.to_expr : local_decl → expr | ⟨un, pn, y, _, bi, _⟩ := expr.local_const un pn bi y /-- A local context is a list of local constant declarations. Each metavariable in a metavariable context holds a local_context to declare which locals the metavariable is allowed to depend on. -/ meta constant local_context : Type namespace local_context /-- The empty local context. -/ meta constant empty : local_context /-- Add a new local constant to the lc. The new local has an unused unique_name. Fails when the type depends on local constants that are not present in the context.-/ meta constant mk_local (pretty_name : name) (type : expr) (bi : binder_info) : local_context → option (expr × local_context) meta constant get_local_decl : name → local_context → option local_decl meta constant get_local : name → local_context → option expr meta constant is_subset : local_context → local_context → bool meta constant has_decidable_eq : decidable_eq local_context attribute [instance] has_decidable_eq meta constant fold {α : Type} (f : α → expr → α): α → local_context → α meta def to_list : local_context → list expr := list.reverse ∘ fold (λ acc e, e :: acc) [] meta def to_format : local_context → format := to_fmt ∘ to_list meta instance : has_to_format local_context := ⟨to_format⟩ meta instance : has_le local_context := ⟨λ a b, local_context.is_subset a b⟩ meta instance decidable_rel : decidable_rel ((≤) : local_context → local_context → Prop) := infer_instance meta instance : has_emptyc local_context := ⟨empty⟩ meta instance : inhabited local_context := ⟨empty⟩ meta instance : has_mem expr local_context := ⟨λ e lc, option.is_some $ get_local (expr.local_uniq_name e) lc⟩ meta instance {e : expr} {lc : local_context} : decidable (e ∈ lc) := infer_instance end local_context
fe181b94823b9e4c1f641fce1d4d531041b6d59f
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Binders.lean
54d0823280f5b13ac81f082bcd837b8838df3a4b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
32,503
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.Parser.Term import Lean.Elab.Quotation.Precheck import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Elab.AuxDiscr namespace Lean.Elab.Term open Meta open Lean.Parser.Term open TSyntax.Compat /-- Given syntax of the forms a) (`:` term)? b) `:` term return `term` if it is present, or a hole if not. -/ private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax := if stx.getNumArgs == 0 then mkHole ref else stx[1] /-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/ private def expandBinderIdent (stx : Syntax) : TermElabM Syntax := match stx with | `(_) => mkFreshIdent stx | _ => pure stx /-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/ private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do if stx.isNone then let id ← withFreshMacroScope <| MonadQuotation.addMacroScope `inst return mkIdentFrom stx id else return stx[0] /-- Auxiliary datatype for elaborating binders. -/ structure BinderView where /-- Position information provider for the Info Tree. We currently do not track binder "macro expansion" steps in the info tree. For example, suppose we expand a `_` into a fresh identifier. The fresh identifier has synthetic position since it was not written by the user, and we would not get hover information for the `_` because we also don't have this macro expansion step stored in the info tree. Thus, we store the original `Syntax` in `ref`, and use it when storing the binder information in the info tree. Potential better solution: add a binder syntax category, an extensible `elabBinder` (like we have `elabTerm`), and perform all macro expansion steps at `elabBinder` and record them in the infro tree. -/ ref : Syntax id : Syntax type : Syntax bi : BinderInfo partial def quoteAutoTactic : Syntax → TermElabM Syntax | stx@(.ident ..) => throwErrorAt stx "invalid auto tactic, identifier is not allowed" | stx@(.node _ k args) => do if stx.isAntiquot then throwErrorAt stx "invalid auto tactic, antiquotation is not allowed" else let mut quotedArgs ← `(Array.empty) for arg in args do if k == nullKind && (arg.isAntiquotSuffixSplice || arg.isAntiquotSplice) then throwErrorAt arg "invalid auto tactic, antiquotation is not allowed" else let quotedArg ← quoteAutoTactic arg quotedArgs ← `(Array.push $quotedArgs $quotedArg) `(Syntax.node SourceInfo.none $(quote k) $quotedArgs) | .atom _ val => `(mkAtom $(quote val)) | .missing => throwError "invalid auto tactic, tactic is missing" def declareTacticSyntax (tactic : Syntax) : TermElabM Name := withFreshMacroScope do let name ← MonadQuotation.addMacroScope `_auto let type := Lean.mkConst `Lean.Syntax let tactic ← quoteAutoTactic tactic let value ← elabTerm tactic type let value ← instantiateMVars value trace[Elab.autoParam] value let decl := Declaration.defnDecl { name, levelParams := [], type, value, hints := .opaque, safety := DefinitionSafety.safe } addDecl decl compileDecl decl return name /-- Expand `optional (binderTactic <|> binderDefault)` ``` def binderTactic := leading_parser " := " >> " by " >> tacticParser def binderDefault := leading_parser " := " >> termParser ``` -/ private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do if optBinderModifier.isNone then return type else let modifier := optBinderModifier[0] let kind := modifier.getKind if kind == `Lean.Parser.Term.binderDefault then let defaultVal := modifier[1] `(optParam $type $defaultVal) else if kind == `Lean.Parser.Term.binderTactic then let tac := modifier[2] let name ← declareTacticSyntax tac `(autoParam $type $(mkIdentFrom tac name)) else throwUnsupportedSyntax private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) := ids.getArgs.mapM fun id => let k := id.getKind if k == identKind || k == `Lean.Parser.Term.hole then return id else throwErrorAt id "identifier or `_` expected" /-- Convert `stx` into an array of `BinderView`s. `stx` must be an indentifier, `_`, `explicitBinder`, `implicitBinder`, `strictImplicitBinder`, or `instBinder`. -/ private def toBinderViews (stx : Syntax) : TermElabM (Array BinderView) := do let k := stx.getKind if stx.isIdent || k == ``hole then -- binderIdent return #[{ ref := stx, id := (← expandBinderIdent stx), type := mkHole stx, bi := .default }] else if k == ``Lean.Parser.Term.explicitBinder then -- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)` let ids ← getBinderIds stx[1] let type := stx[2] let optModifier := stx[3] ids.mapM fun id => do pure { ref := id, id := (← expandBinderIdent id), type := (← expandBinderModifier (expandBinderType id type) optModifier), bi := .default } else if k == ``Lean.Parser.Term.implicitBinder then -- `{` binderIdent+ binderType `}` let ids ← getBinderIds stx[1] let type := stx[2] ids.mapM fun id => do pure { ref := id, id := (← expandBinderIdent id), type := expandBinderType id type, bi := .implicit } else if k == ``Lean.Parser.Term.strictImplicitBinder then -- `⦃` binderIdent+ binderType `⦄` let ids ← getBinderIds stx[1] let type := stx[2] ids.mapM fun id => do pure { ref := id, id := (← expandBinderIdent id), type := expandBinderType id type, bi := .strictImplicit } else if k == ``Lean.Parser.Term.instBinder then -- `[` optIdent type `]` let id ← expandOptIdent stx[1] let type := stx[2] return #[ { ref := id, id := id, type := type, bi := .instImplicit } ] else throwUnsupportedSyntax private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer binder type" def addLocalVarInfo (stx : Syntax) (fvar : Expr) : TermElabM Unit := addTermInfo' (isBinder := true) stx fvar private def ensureAtomicBinderName (binderView : BinderView) : TermElabM Unit := let n := binderView.id.getId.eraseMacroScopes unless n.isAtomic do throwErrorAt binderView.id "invalid binder name '{n}', it must be atomic" register_builtin_option checkBinderAnnotations : Bool := { defValue := true descr := "check whether type is a class instance whenever the binder annotation `[...]` is used" } /-- Throw an error if `type` is not a valid local instance. -/ private partial def checkLocalInstanceParameters (type : Expr) : TermElabM Unit := do let .forallE n d b bi ← whnf type | return () if !b.hasLooseBVar 0 then throwError "invalid parametric local instance, parameter with type{indentExpr d}\ndoes not have forward dependencies, type class resolution cannot use this kind of local instance because it will not be able to infer a value for this parameter." withLocalDecl n bi d fun x => checkLocalInstanceParameters (b.instantiate1 x) private partial def elabBinderViews (binderViews : Array BinderView) (fvars : Array (Syntax × Expr)) (k : Array (Syntax × Expr) → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array (Syntax × Expr)) : TermElabM α := do if h : i < binderViews.size then let binderView := binderViews[i] ensureAtomicBinderName binderView let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type if binderView.bi.isInstImplicit && checkBinderAnnotations.get (← getOptions) then unless (← isClass? type).isSome do throwErrorAt binderView.type "invalid binder annotation, type is not a class instance{indentExpr type}\nuse the command `set_option checkBinderAnnotations false` to disable the check" withRef binderView.type <| checkLocalInstanceParameters type withLocalDecl binderView.id.getId binderView.bi type fun fvar => do addLocalVarInfo binderView.ref fvar loop (i+1) (fvars.push (binderView.id, fvar)) else k fvars loop 0 fvars private partial def elabBindersAux (binders : Array Syntax) (k : Array (Syntax × Expr) → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array (Syntax × Expr)) : TermElabM α := do if h : i < binders.size then let binderViews ← toBinderViews binders[i] elabBinderViews binderViews fvars <| loop (i+1) else k fvars loop 0 #[] /-- Like `elabBinders`, but also pass syntax node per binder. `elabBinders(Ex)` automatically adds binder info nodes for the produced fvars, but storing the syntax nodes might be necessary when later adding the same binders back to the local context so that info nodes can manually be added for the new fvars; see `MutualDef` for an example. -/ def elabBindersEx (binders : Array Syntax) (k : Array (Syntax × Expr) → TermElabM α) : TermElabM α := universeConstraintsCheckpoint do if binders.isEmpty then k #[] else elabBindersAux binders k /-- Elaborate the given binders (i.e., `Syntax` objects for `bracketedBinder`), update the local context, set of local instances, reset instance chache (if needed), and then execute `k` with the updated context. The local context will only be included inside `k`. For example, suppose you have binders `[(a : α), (b : β a)]`, then the elaborator will create two new free variables `a` and `b`, push these to the context and pass to `k #[a,b]`. -/ def elabBinders (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α := elabBindersEx binders (fun fvars => k (fvars.map (·.2))) /-- Same as `elabBinder` with a single binder.-/ def elabBinder (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α := elabBinders #[binder] fun fvars => x fvars[0]! /-- If `binder` is a `_` or an identifier, return a `bracketedBinder` using `type` otherwise throw an exception. -/ def expandSimpleBinderWithType (type : Term) (binder : Syntax) : MacroM Syntax := if binder.isOfKind ``hole || binder.isIdent then `(bracketedBinder| ($binder : $type)) else Macro.throwErrorAt type "unexpected type ascription" @[builtinMacro Lean.Parser.Term.forall] def expandForall : Macro | `(forall $binders* : $ty, $term) => do let binders ← binders.mapM (expandSimpleBinderWithType ty) `(forall $binders*, $term) | _ => Macro.throwUnsupported @[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ => match stx with | `(forall $binders*, $term) => elabBinders binders fun xs => do let e ← elabType term mkForallFVars xs e | _ => throwUnsupportedSyntax open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.arrow] def precheckArrow : Precheck | `($dom:term -> $rng) => do precheck dom precheck rng | _ => throwUnsupportedSyntax @[builtinTermElab arrow] def elabArrow : TermElab := fun stx _ => match stx with | `($dom:term -> $rng) => do -- elaborate independently from each other let dom ← elabType dom let rng ← elabType rng return mkForall (← MonadQuotation.addMacroScope `a) BinderInfo.default dom rng | _ => throwUnsupportedSyntax /-- The dependent arrow. `(x : α) → β` is equivalent to `∀ x : α, β`, but we usually reserve the latter for propositions. Also written as `Π x : α, β` (the "Pi-type") in the literature. -/ @[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ => -- bracketedBinder `->` term let binder := stx[0] let term := stx[2] elabBinders #[binder] fun xs => do mkForallFVars xs (← elabType term) /-- Auxiliary functions for converting `id_1 ... id_n` application into `#[id_1, ..., id_m]` It is used at `expandFunBinders`. -/ private partial def getFunBinderIds? (stx : Syntax) : OptionT MacroM (Array Syntax) := let convertElem (stx : Term) : OptionT MacroM Syntax := match stx with | `(_) => /- We used to use `mkFreshIdent` here, but it prevented us from obtaining hover info for `_` because the fresh identifier would have a synthetic position, and synthetic positions are ignored by the LSP server. See comment at `BinderView.ref` for additional details. -/ return stx | `($_:ident) => return stx | _ => failure match stx with | `($f $args*) => do let mut acc := #[].push (← convertElem f) for arg in args do acc := acc.push (← convertElem arg) return acc | _ => return #[].push (← convertElem stx) /-- Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as ``` def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec leading_parser unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser ``` to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern. The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form ``` `(` ident `:` term `)` ``` which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax. We update the `body` syntax when expanding the pattern notation. Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`. See local function `processAsPattern` at `expandFunBindersAux`. The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/ partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : MacroM (Array Syntax × Syntax × Bool) := let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do if h : i < binders.size then let binder := binders[i] let processAsPattern : Unit → MacroM (Array Syntax × Syntax × Bool) := fun _ => do let pattern := binder let major ← mkFreshIdent binder let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder)) let newBody ← `(match $major:ident with | $pattern => $newBody) pure (binders, newBody, true) match binder.getKind with | ``Lean.Parser.Term.implicitBinder | ``Lean.Parser.Term.strictImplicitBinder | ``Lean.Parser.Term.instBinder | ``Lean.Parser.Term.explicitBinder | ``Lean.Parser.Term.hole | `ident => loop body (i+1) (newBinders.push binder) | ``Lean.Parser.Term.paren => -- `(` (termParser >> parenSpecial)? `)` -- parenSpecial := (tupleTail <|> typeAscription)? let binderBody := binder[1] if binderBody.isNone then processAsPattern () else let term := binderBody[0] let special := binderBody[1] if special.isNone then match (← getFunBinderIds? term) with | some idents => -- `fun (x ...) ...` ~> `fun (x : _) ...` -- Interpret `(x ...)` as sequence of binders instead of pattern only if none of the idents -- are defined in the global scope. Technically, it would be sufficient to only check the -- first ident to be sure that the syntax cannot possibly be a valid pattern. However, for -- consistency we apply the same check to all idents so that the possibility of shadowing -- a global decl is identical for all of them. if (← idents.allM fun ident => return List.isEmpty (← Macro.resolveGlobalName ident.getId)) then loop body (i+1) (newBinders ++ idents.map (mkExplicitBinder · (mkHole binder))) else processAsPattern () | none => processAsPattern () else if special[0].getKind != `Lean.Parser.Term.typeAscription then processAsPattern () else -- typeAscription := `:` term let type := special[0][1] match (← getFunBinderIds? term) with | some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type)) | none => processAsPattern () | _ => processAsPattern () else pure (newBinders, body, false) loop body 0 #[] namespace FunBinders structure State where fvars : Array Expr := #[] lctx : LocalContext localInsts : LocalInstances expectedType? : Option Expr := none private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do match s.expectedType? with | none => pure s | some expectedType => let expectedType ← whnfForall expectedType match expectedType with | .forallE _ d b _ => discard <| isDefEq fvarType d let b := b.instantiate1 fvar return { s with expectedType? := some b } | _ => return { s with expectedType? := none } private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State := do if h : i < binderViews.size then let binderView := binderViews[i] ensureAtomicBinderName binderView withRef binderView.type <| withLCtx s.lctx s.localInsts do let type ← elabType binderView.type registerFailedToInferBinderTypeInfo type binderView.type let fvarId ← mkFreshFVarId let fvar := mkFVar fvarId let s := { s with fvars := s.fvars.push fvar } -- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type) /- We do **not** want to support default and auto arguments in lambda abstractions. Example: `fun (x : Nat := 10) => x+1`. We do not believe this is an useful feature, and it would complicate the logic here. -/ let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi addTermInfo' (lctx? := some lctx) (isBinder := true) binderView.ref fvar let s ← withRef binderView.id <| propagateExpectedType fvar type s let s := { s with lctx } match (← isClass? type) with | none => elabFunBinderViews binderViews (i+1) s | some className => resettingSynthInstanceCache do let localInsts := s.localInsts.push { className, fvar := mkFVar fvarId } elabFunBinderViews binderViews (i+1) { s with localInsts } else pure s partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do if h : i < binders.size then let binderViews ← toBinderViews binders[i] let s ← elabFunBinderViews binderViews 0 s elabFunBindersAux binders (i+1) s else pure s end FunBinders def elabFunBinders (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α := if binders.isEmpty then x #[] expectedType? else do let lctx ← getLCtx let localInsts ← getLocalInstances let s ← FunBinders.elabFunBindersAux binders 0 { lctx, localInsts, expectedType? } resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) <| withLCtx s.lctx s.localInsts <| x s.fvars s.expectedType? def expandWhereDecls (whereDecls : Syntax) (body : Syntax) : MacroM Syntax := match whereDecls with | `(whereDecls|where $[$decls:letRecDecl];*) => `(let rec $decls:letRecDecl,*; $body) | _ => Macro.throwUnsupported def expandWhereDeclsOpt (whereDeclsOpt : Syntax) (body : Syntax) : MacroM Syntax := if whereDeclsOpt.isNone then return body else expandWhereDecls whereDeclsOpt[0] body /-- Helper function for `expandMatchAltsIntoMatch`. -/ private def expandMatchAltsIntoMatchAux (matchAlts : Syntax) (isTactic : Bool) (useExplicit : Bool) : Nat → Array Syntax → MacroM Syntax | 0, discrs => do if isTactic then `(tactic|match $[$discrs:term],* with $matchAlts:matchAlts) else `(match $[$discrs:term],* with $matchAlts:matchAlts) | n+1, discrs => withFreshMacroScope do let x ← mkAuxFunDiscr -- Recall that identifiers created with `mkAuxFunDiscr` are cleared by the `match` elaborator let d ← `(@$x:ident) -- See comment below let body ← expandMatchAltsIntoMatchAux matchAlts isTactic useExplicit n (discrs.push d) if isTactic then `(tactic| intro $x:term; $body:tactic) else if useExplicit then `(@fun $x => $body) else `(fun $x => $body) /-- Expand `matchAlts` syntax into a full `match`-expression. Example: ``` | 0, true => alt_1 | i, _ => alt_2 ``` expands into (for tactic == false) ``` fun x_1 x_2 => match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` and (for tactic == true) ``` intro x_1; intro x_2; match @x_1, @x_2 with | 0, true => alt_1 | i, _ => alt_2 ``` If `useExplicit = true`, we add a `@` before `fun` to disable implicit lambdas. We disable them when processing `let` and `let rec` declarations to make sure the behavior is consistent with top-level declarations where we can write ``` def f : {α : Type} → α → α | _, a => a ``` We use `useExplicit = false` when we are elaborating the `fun | ... => ... | ...` notation. See issue #1132. If `@fun` is used with this notation, the we set `useExplicit = true`. We also use `useExplicit = false` when processing `instance ... where` notation declarations. The motivation is to have compact declarations such as ``` instance [Alternative m] : MonadLiftT Option m where monadLift -- We don't want to provide the implicit arguments of `monadLift` here. One should use `monadLift := @fun ...` if they want to provide them. | some a => pure a | none => failure ``` Remark: we add `@` at discriminants to make sure we don't consume implicit arguments, and to make the behavior consistent with `fun`. Example: ``` inductive T : Type 1 := | mkT : (forall {a : Type}, a -> a) -> T def makeT (f : forall {a : Type}, a -> a) : T := mkT f def makeT' : (forall {a : Type}, a -> a) -> T | f => mkT f ``` The two definitions should be elaborated without errors and be equivalent. -/ def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (useExplicit := true) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts (isTactic := false) (useExplicit := useExplicit) (getMatchAltsNumPatterns matchAlts) #[] def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax := withRef ref <| expandMatchAltsIntoMatchAux matchAlts (isTactic := true) (useExplicit := false) (getMatchAltsNumPatterns matchAlts) #[] /-- Similar to `expandMatchAltsIntoMatch`, but supports an optional `where` clause. Expand `matchAltsWhereDecls` into `let rec` + `match`-expression. Example ``` | 0, true => ... f 0 ... | i, _ => ... f i + g i ... where f x := g x + 1 g : Nat → Nat | 0 => 1 | x+1 => f x ``` expands into ``` fux x_1 x_2 => let rec f x := g x + 1, g : Nat → Nat | 0 => 1 | x+1 => f x match x_1, x_2 with | 0, true => ... f 0 ... | i, _ => ... f i + g i ... ``` -/ def expandMatchAltsWhereDecls (matchAltsWhereDecls : Syntax) : MacroM Syntax := let matchAlts := matchAltsWhereDecls[0] let whereDeclsOpt := matchAltsWhereDecls[1] let rec loop (i : Nat) (discrs : Array Syntax) : MacroM Syntax := match i with | 0 => do let matchStx ← `(match $[$discrs:term],* with $matchAlts:matchAlts) if whereDeclsOpt.isNone then return matchStx else expandWhereDeclsOpt whereDeclsOpt matchStx | n+1 => withFreshMacroScope do -- See comment at `expandMatchAltsIntoMatch`, let d ← mkAuxFunDiscr let body ← loop n (discrs.push (← `(@$d:ident))) `(@fun $d:ident => $body) loop (getMatchAltsNumPatterns matchAlts) #[] @[builtinMacro Parser.Term.fun] partial def expandFun : Macro | `(fun $binders* : $ty => $body) => do let binders ← binders.mapM (expandSimpleBinderWithType ty) `(fun $binders* => $body) | `(fun $binders* => $body) => do -- if there is a type ascription, we assume all binders are already simple let (binders, body, expandedPattern) ← expandFunBinders binders body if expandedPattern then `(fun $binders* => $body) else Macro.throwUnsupported | stx@`(fun $m:matchAlts) => expandMatchAltsIntoMatch stx m (useExplicit := false) | _ => Macro.throwUnsupported @[builtinMacro Parser.Term.explicit] partial def expandExplicitFun : Macro := fun stx => match stx with | `(@fun $m:matchAlts) => expandMatchAltsIntoMatch stx[1] m (useExplicit := true) | _ => Macro.throwUnsupported open Lean.Elab.Term.Quotation in @[builtinQuotPrecheck Lean.Parser.Term.fun] def precheckFun : Precheck | `(fun $binders* $[: $ty?]? => $body) => do let (binders, body, _) ← liftMacroM <| expandFunBinders binders body let mut ids := #[] for b in binders do for v in ← toBinderViews b do Quotation.withNewLocals ids <| precheck v.type ids := ids.push v.id.getId Quotation.withNewLocals ids <| precheck body | _ => throwUnsupportedSyntax @[builtinTermElab «fun»] partial def elabFun : TermElab := fun stx expectedType? => match stx with | `(fun $binders* => $body) => do -- We can assume all `match` binders have been iteratively expanded by the above macro here, though -- we still need to call `expandFunBinders` once to obtain `binders` in a normal form -- expected by `elabFunBinder`. let (binders, body, _) ← liftMacroM <| expandFunBinders binders body elabFunBinders binders expectedType? fun xs expectedType? => do /- We ensure the expectedType here since it will force coercions to be applied if needed. If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`, and another instance for the dependent version. -/ let e ← elabTermEnsuringType body expectedType? mkLambdaFVars xs e | _ => throwUnsupportedSyntax /-- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created. Otherwise, we create a term of the form `(fun (x : type) => body) val` The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`. If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/ def elabLetDeclAux (id : Syntax) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) (usedLetOnly : Bool) : TermElabM Expr := do let (type, val, binders) ← elabBindersEx binders fun xs => do let (binders, fvars) := xs.unzip let type ← elabType typeStx registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type" if elabBodyFirst then let type ← mkForallFVars fvars type let val ← mkFreshExprMVar type pure (type, val, binders) else let val ← elabTermEnsuringType valStx type let type ← mkForallFVars fvars type /- By default `mkLambdaFVars` and `mkLetFVars` create binders only for let-declarations that are actually used in the body. This generates counterintuitive behavior in the elaborator since users will not be notified about holes such as ``` def ex : Nat := let x := _ 42 ``` -/ let val ← mkLambdaFVars fvars val (usedLetOnly := false) pure (type, val, binders) trace[Elab.let.decl] "{id.getId} : {type} := {val}" let result ← if useLetExpr then withLetDecl id.getId type val fun x => do addLocalVarInfo id x let body ← elabTermEnsuringType body expectedType? let body ← instantiateMVars body mkLetFVars #[x] body (usedLetOnly := usedLetOnly) else let f ← withLocalDecl id.getId BinderInfo.default type fun x => do addLocalVarInfo id x let body ← elabTermEnsuringType body expectedType? let body ← instantiateMVars body mkLambdaFVars #[x] body (usedLetOnly := false) pure <| mkLetFunAnnotation (mkApp f val) if elabBodyFirst then forallBoundedTelescope type binders.size fun xs type => do -- the original `fvars` from above are gone, so add back info manually for b in binders, x in xs do addLocalVarInfo b x let valResult ← elabTermEnsuringType valStx type let valResult ← mkLambdaFVars xs valResult (usedLetOnly := false) unless (← isDefEq val valResult) do throwError "unexpected error when elaborating 'let'" pure result structure LetIdDeclView where id : Syntax binders : Array Syntax type : Syntax value : Syntax def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView := -- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser let id := letIdDecl[0] let binders := letIdDecl[1].getArgs let optType := letIdDecl[2] let type := expandOptType id optType let value := letIdDecl[4] { id, binders, type, value } def expandLetEqnsDecl (letDecl : Syntax) (useExplicit := true) : MacroM Syntax := do let ref := letDecl let matchAlts := letDecl[3] let val ← expandMatchAltsIntoMatch ref matchAlts (useExplicit := useExplicit) return mkNode `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val] def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) (usedLetOnly : Bool) : TermElabM Expr := do let letDecl := stx[1][0] let body := stx[3] if letDecl.getKind == ``Lean.Parser.Term.letIdDecl then let { id, binders, type, value } := mkLetIdDeclView letDecl elabLetDeclAux id binders type value body expectedType? useLetExpr elabBodyFirst usedLetOnly else if letDecl.getKind == ``Lean.Parser.Term.letPatDecl then -- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser if elabBodyFirst then throwError "'let_delayed' with patterns is not allowed" let pat := letDecl[0] let optType := letDecl[2] let val := letDecl[4] if pat.getKind == ``Parser.Term.hole then -- `let _ := ...` should not be treated at a `letIdDecl` let id := mkIdentFrom pat `_ let type := expandOptType id optType elabLetDeclAux id #[] type val body expectedType? useLetExpr elabBodyFirst usedLetOnly else -- We are currently treating `let_fun` and `let` the same way when patterns are used. let stxNew ← if optType.isNone then `(match $val:term with | $pat => $body) else let type := optType[0][1] `(match ($val:term : $type) with | $pat => $body) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else if letDecl.getKind == ``Lean.Parser.Term.letEqnsDecl then let letDeclIdNew ← liftMacroM <| expandLetEqnsDecl letDecl let declNew := stx[1].setArg 0 letDeclIdNew let stxNew := stx.setArg 1 declNew withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? else throwUnsupportedSyntax @[builtinTermElab «let»] def elabLetDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := true) (elabBodyFirst := false) (usedLetOnly := false) @[builtinTermElab «let_fun»] def elabLetFunDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := false) (elabBodyFirst := false) (usedLetOnly := false) @[builtinTermElab «let_delayed»] def elabLetDelayedDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := true) (elabBodyFirst := true) (usedLetOnly := false) @[builtinTermElab «let_tmp»] def elabLetTmpDecl : TermElab := fun stx expectedType? => elabLetDeclCore stx expectedType? (useLetExpr := true) (elabBodyFirst := false) (usedLetOnly := true) builtin_initialize registerTraceClass `Elab.let end Lean.Elab.Term
0c279c1c3a51c7d2efca55e66bad48653c01a3be
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/dynamics/flow.lean
3235f5a1b40f2eeacdce2a5eda9e0cb6974c89e8
[ "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,146
lean
/- Copyright (c) 2020 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo -/ import topology.algebra.group.basic import logic.function.iterate /-! # Flows and invariant sets This file defines a flow on a topological space `α` by a topological monoid `τ` as a continuous monoid-act of `τ` on `α`. Anticipating the cases where `τ` is one of `ℕ`, `ℤ`, `ℝ⁺`, or `ℝ`, we use additive notation for the monoids, though the definition does not require commutativity. A subset `s` of `α` is invariant under a family of maps `ϕₜ : α → α` if `ϕₜ s ⊆ s` for all `t`. In many cases `ϕ` will be a flow on `α`. For the cases where `ϕ` is a flow by an ordered (additive, commutative) monoid, we additionally define forward invariance, where `t` ranges over those elements which are nonnegative. Additionally, we define such constructions as the restriction of a flow onto an invariant subset, and the time-reveral of a flow by a group. -/ open set function filter /-! ### Invariant sets -/ section invariant variables {τ : Type*} {α : Type*} /-- A set `s ⊆ α` is invariant under `ϕ : τ → α → α` if `ϕ t s ⊆ s` for all `t` in `τ`. -/ def is_invariant (ϕ : τ → α → α) (s : set α): Prop := ∀ t, maps_to (ϕ t) s s variables (ϕ : τ → α → α) (s : set α) lemma is_invariant_iff_image : is_invariant ϕ s ↔ ∀ t, ϕ t '' s ⊆ s := by simp_rw [is_invariant, maps_to'] /-- A set `s ⊆ α` is forward-invariant under `ϕ : τ → α → α` if `ϕ t s ⊆ s` for all `t ≥ 0`. -/ def is_fw_invariant [preorder τ] [has_zero τ] (ϕ : τ → α → α) (s : set α): Prop := ∀ ⦃t⦄, 0 ≤ t → maps_to (ϕ t) s s lemma is_invariant.is_fw_invariant [preorder τ] [has_zero τ] {ϕ : τ → α → α} {s : set α} (h : is_invariant ϕ s) : is_fw_invariant ϕ s := λ t ht, h t /-- If `τ` is a `canonically_ordered_add_monoid` (e.g., `ℕ` or `ℝ≥0`), then the notions `is_fw_invariant` and `is_invariant` are equivalent. -/ lemma is_fw_invariant.is_invariant [canonically_ordered_add_monoid τ] {ϕ : τ → α → α} {s : set α} (h : is_fw_invariant ϕ s) : is_invariant ϕ s := λ t, h (zero_le t) /-- If `τ` is a `canonically_ordered_add_monoid` (e.g., `ℕ` or `ℝ≥0`), then the notions `is_fw_invariant` and `is_invariant` are equivalent. -/ lemma is_fw_invariant_iff_is_invariant [canonically_ordered_add_monoid τ] {ϕ : τ → α → α} {s : set α} : is_fw_invariant ϕ s ↔ is_invariant ϕ s := ⟨is_fw_invariant.is_invariant, is_invariant.is_fw_invariant⟩ end invariant /-! ### Flows -/ /-- A flow on a topological space `α` by an a additive topological monoid `τ` is a continuous monoid action of `τ` on `α`.-/ structure flow (τ : Type*) [topological_space τ] [add_monoid τ] [has_continuous_add τ] (α : Type*) [topological_space α] := (to_fun : τ → α → α) (cont' : continuous (uncurry to_fun)) (map_add' : ∀ t₁ t₂ x, to_fun (t₁ + t₂) x = to_fun t₁ (to_fun t₂ x)) (map_zero' : ∀ x, to_fun 0 x = x) namespace flow variables {τ : Type*} [add_monoid τ] [topological_space τ] [has_continuous_add τ] {α : Type*} [topological_space α] (ϕ : flow τ α) instance : inhabited (flow τ α) := ⟨{ to_fun := λ _ x, x, cont' := continuous_snd, map_add' := λ _ _ _, rfl, map_zero' := λ _, rfl }⟩ instance : has_coe_to_fun (flow τ α) (λ _, τ → α → α) := ⟨flow.to_fun⟩ @[ext] lemma ext : ∀ {ϕ₁ ϕ₂ : flow τ α}, (∀ t x, ϕ₁ t x = ϕ₂ t x) → ϕ₁ = ϕ₂ | ⟨f₁, _, _, _⟩ ⟨f₂, _, _, _⟩ h := by { congr, funext, exact h _ _ } @[continuity] protected lemma continuous {β : Type*} [topological_space β] {t : β → τ} (ht : continuous t) {f : β → α} (hf : continuous f) : continuous (λ x, ϕ (t x) (f x)) := ϕ.cont'.comp (ht.prod_mk hf) alias flow.continuous ← _root_.continuous.flow lemma map_add (t₁ t₂ : τ) (x : α) : ϕ (t₁ + t₂) x = ϕ t₁ (ϕ t₂ x) := ϕ.map_add' _ _ _ @[simp] lemma map_zero : ϕ 0 = id := funext ϕ.map_zero' lemma map_zero_apply (x : α) : ϕ 0 x = x := ϕ.map_zero' x /-- Iterations of a continuous function from a topological space `α` to itself defines a semiflow by `ℕ` on `α`. -/ def from_iter {g : α → α} (h : continuous g) : flow ℕ α := { to_fun := λ n x, g^[n] x, cont' := continuous_uncurry_of_discrete_topology_left (continuous.iterate h), map_add' := iterate_add_apply _, map_zero' := λ x, rfl } /-- Restriction of a flow onto an invariant set. -/ def restrict {s : set α} (h : is_invariant ϕ s) : flow τ ↥s := { to_fun := λ t, (h t).restrict _ _ _, cont' := (ϕ.continuous continuous_fst continuous_subtype_coe.snd').subtype_mk _, map_add' := λ _ _ _, subtype.ext (map_add _ _ _ _), map_zero' := λ _, subtype.ext (map_zero_apply _ _)} end flow namespace flow variables {τ : Type*} [add_comm_group τ] [topological_space τ] [topological_add_group τ] {α : Type*} [topological_space α] (ϕ : flow τ α) lemma is_invariant_iff_image_eq (s : set α) : is_invariant ϕ s ↔ ∀ t, ϕ t '' s = s := (is_invariant_iff_image _ _).trans (iff.intro (λ h t, subset.antisymm (h t) (λ _ hx, ⟨_, h (-t) ⟨_, hx, rfl⟩, by simp [← map_add]⟩)) (λ h t, by rw h t)) /-- The time-reversal of a flow `ϕ` by a (commutative, additive) group is defined `ϕ.reverse t x = ϕ (-t) x`. -/ def reverse : flow τ α := { to_fun := λ t, ϕ (-t), cont' := ϕ.continuous continuous_fst.neg continuous_snd, map_add' := λ _ _ _, by rw [neg_add, map_add], map_zero' := λ _, by rw [neg_zero, map_zero_apply] } /-- The map `ϕ t` as a homeomorphism. -/ def to_homeomorph (t : τ) : α ≃ₜ α := { to_fun := ϕ t, inv_fun := ϕ (-t), left_inv := λ x, by rw [← map_add, neg_add_self, map_zero_apply], right_inv := λ x, by rw [← map_add, add_neg_self, map_zero_apply] } lemma image_eq_preimage (t : τ) (s : set α) : ϕ t '' s = ϕ (-t) ⁻¹' s := (ϕ.to_homeomorph t).to_equiv.image_eq_preimage s end flow
a9b941ea7cec99b075915a0d88037117f4720083
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/nat/gcd.lean
422ec7f2dbe2f8c71d94822100732bc2d0f283b9
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,582
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Definitions and properties of gcd, lcm, and coprime. -/ import .div open eq.ops well_founded decidable prod open algebra namespace nat /- gcd -/ private definition pair_nat.lt : nat × nat → nat × nat → Prop := measure pr₂ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20 -- we use intro_k to be able to execute gcd efficiently in the kernel local attribute pair_nat.lt.wf [instance] -- instance will not be saved in .olean local infixl ` ≺ `:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : nat) : (succ y₁, x % succ y₁) ≺ (x, succ y₁) := !mod_lt (succ_pos y₁) definition gcd.F : Π (p₁ : nat × nat), (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat | (x, 0) f := x | (x, succ y) f := f (succ y, x % succ y) !gcd.lt.dec definition gcd (x y : nat) := fix gcd.F (x, y) theorem gcd_zero_right (x : nat) : gcd x 0 = x := rfl theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x % succ y) := well_founded.fix_eq gcd.F (x, succ y) theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := calc gcd n 1 = gcd 1 (n % 1) : gcd_succ ... = gcd 1 0 : mod_one theorem gcd_def (x : ℕ) : Π (y : ℕ), gcd x y = if y = 0 then x else gcd y (x % y) | 0 := !gcd_zero_right | (succ y) := !gcd_succ ⬝ (if_neg !succ_ne_zero)⁻¹ theorem gcd_self : Π (n : ℕ), gcd n n = n | 0 := rfl | (succ n₁) := calc gcd (succ n₁) (succ n₁) = gcd (succ n₁) (succ n₁ % succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : mod_self theorem gcd_zero_left : Π (n : ℕ), gcd 0 n = n | 0 := rfl | (succ n₁) := calc gcd 0 (succ n₁) = gcd (succ n₁) (0 % succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : zero_mod theorem gcd_of_pos (m : ℕ) {n : ℕ} (H : n > 0) : gcd m n = gcd n (m % n) := gcd_def m n ⬝ if_neg (ne_zero_of_pos H) theorem gcd_rec (m n : ℕ) : gcd m n = gcd n (m % n) := by_cases_zero_pos n (calc m = gcd 0 m : gcd_zero_left ... = gcd 0 (m % 0) : mod_zero) (take n, assume H : 0 < n, gcd_of_pos m H) theorem gcd.induction {P : ℕ → ℕ → Prop} (m n : ℕ) (H0 : ∀m, P m 0) (H1 : ∀m n, 0 < n → P n (m % n) → P m n) : P m n := induction (m, n) (prod.rec (λm, nat.rec (λ IH, H0 m) (λ n₁ v (IH : ∀p₂, p₂ ≺ (m, succ n₁) → P (pr₁ p₂) (pr₂ p₂)), H1 m (succ n₁) !succ_pos (IH _ !gcd.lt.dec)))) theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (take m, and.intro (!one_mul ▸ !dvd_mul_left) !dvd_zero) (take m n (npos : 0 < n), and.rec (assume (IH₁ : gcd n (m % n) ∣ n) (IH₂ : gcd n (m % n) ∣ (m % n)), have H : (gcd n (m % n) ∣ (m / n * n + m % n)), from dvd_add (dvd.trans IH₁ !dvd_mul_left) IH₂, have H1 : (gcd n (m % n) ∣ m), from !eq_div_mul_add_mod⁻¹ ▸ H, show (gcd m n ∣ m) ∧ (gcd m n ∣ n), from !gcd_rec⁻¹ ▸ (and.intro H1 IH₁))) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := and.left !gcd_dvd theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := and.right !gcd_dvd theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (take m, imp.intro) (take m n (npos : n > 0) (IH : k ∣ n → k ∣ m % n → k ∣ gcd n (m % n)) (H1 : k ∣ m) (H2 : k ∣ n), have H3 : k ∣ m / n * n + m % n, from !eq_div_mul_add_mod ▸ H1, have H4 : k ∣ m % n, from nat.dvd_of_dvd_add_left H3 (dvd.trans H2 !dvd_mul_left), !gcd_rec⁻¹ ▸ IH H2 H4) theorem gcd.comm (m n : ℕ) : gcd m n = gcd n m := dvd.antisymm (dvd_gcd !gcd_dvd_right !gcd_dvd_left) (dvd_gcd !gcd_dvd_right !gcd_dvd_left) theorem gcd.assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd.antisymm (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_left) (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right)) (dvd_gcd (dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left)) (dvd.trans !gcd_dvd_right !gcd_dvd_right)) theorem gcd_one_left (m : ℕ) : gcd 1 m = 1 := !gcd.comm ⬝ !gcd_one_right theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (take n, calc gcd (m * n) (m * 0) = gcd (m * n) 0 : mul_zero) (take n k, assume H : 0 < k, assume IH : gcd (m * k) (m * (n % k)) = m * gcd k (n % k), calc gcd (m * n) (m * k) = gcd (m * k) (m * n % (m * k)) : !gcd_rec ... = gcd (m * k) (m * (n % k)) : mul_mod_mul_left ... = m * gcd k (n % k) : IH ... = m * gcd n k : !gcd_rec) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := calc gcd (m * n) (k * n) = gcd (n * m) (k * n) : mul.comm ... = gcd (n * m) (n * k) : mul.comm ... = n * gcd m k : gcd_mul_left ... = gcd m k * n : mul.comm theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : m > 0) : gcd m n > 0 := pos_of_dvd_of_pos !gcd_dvd_left mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : n > 0) : gcd m n > 0 := pos_of_dvd_of_pos !gcd_dvd_right npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) (assume H1, H1) (assume H1 : m > 0, absurd H⁻¹ (ne_of_lt (!gcd_pos_of_pos_left H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := eq_zero_of_gcd_eq_zero_left (!gcd.comm ▸ H) theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (assume H3 : k = 0, by subst k; rewrite *nat.div_zero) (assume H3 : k > 0, (nat.div_eq_of_eq_mul_left H3 (calc gcd m n = gcd m (n / k * k) : nat.div_mul_cancel H2 ... = gcd (m / k * k) (n / k * k) : nat.div_mul_cancel H1 ... = gcd (m / k) (n / k) * k : gcd_mul_right))⁻¹) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := !mul.comm ▸ !gcd_dvd_gcd_mul_left theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !dvd_mul_left) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := !mul.comm ▸ !gcd_dvd_gcd_mul_left_right /- lcm -/ definition lcm (m n : ℕ) : ℕ := m * n / (gcd m n) theorem lcm.comm (m n : ℕ) : lcm m n = lcm n m := calc lcm m n = m * n / gcd m n : rfl ... = n * m / gcd m n : mul.comm ... = n * m / gcd n m : gcd.comm ... = lcm n m : rfl theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := calc lcm 0 m = 0 * m / gcd 0 m : rfl ... = 0 / gcd 0 m : zero_mul ... = 0 : nat.zero_div theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := !lcm.comm ▸ !lcm_zero_left theorem lcm_one_left (m : ℕ) : lcm 1 m = m := calc lcm 1 m = 1 * m / gcd 1 m : rfl ... = m / gcd 1 m : one_mul ... = m / 1 : gcd_one_left ... = m : nat.div_one theorem lcm_one_right (m : ℕ) : lcm m 1 = m := !lcm.comm ▸ !lcm_one_left theorem lcm_self (m : ℕ) : lcm m m = m := have H : m * m / m = m, from by_cases_zero_pos m !nat.div_zero (take m, assume H1 : m > 0, !nat.mul_div_cancel H1), calc lcm m m = m * m / gcd m m : rfl ... = m * m / m : gcd_self ... = m : H theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := have H : lcm m n = m * (n / gcd m n), from nat.mul_div_assoc _ !gcd_dvd_right, dvd.intro H⁻¹ theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := !lcm.comm ▸ !dvd_lcm_left theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := eq.symm (nat.eq_mul_of_div_eq_right (dvd.trans !gcd_dvd_left !dvd_mul_right) rfl) theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (assume kzero : k = 0, !kzero⁻¹ ▸ !dvd_zero) (assume kpos : k > 0, have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos, have npos : n > 0, from pos_of_dvd_of_pos H2 kpos, have gcd_pos : gcd m n > 0, from !gcd_pos_of_pos_left mpos, obtain p (km : k = m * p), from exists_eq_mul_right_of_dvd H1, obtain q (kn : k = n * q), from exists_eq_mul_right_of_dvd H2, have ppos : p > 0, from pos_of_mul_pos_left (km ▸ kpos), have qpos : q > 0, from pos_of_mul_pos_left (kn ▸ kpos), have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), from calc p * q * (m * n * gcd p q) = m * p * (n * q * gcd p q) : by rewrite [*mul.assoc, *mul.left_comm q, mul.left_comm p] ... = k * (k * gcd p q) : by rewrite [-kn, -km] ... = k * gcd (k * p) (k * q) : by rewrite gcd_mul_left ... = k * gcd (n * q * p) (m * p * q) : by rewrite [-kn, -km] ... = k * (gcd n m * (p * q)) : by rewrite [*mul.assoc, mul.comm q, gcd_mul_right] ... = p * q * (gcd m n * k) : by rewrite [mul.comm, mul.comm (gcd n m), gcd.comm, *mul.assoc], have H4 : m * n * gcd p q = gcd m n * k, from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3, have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k, from !mul.assoc ▸ !gcd_mul_lcm⁻¹ ▸ H4, have H6 : lcm m n * gcd p q = k, from !eq_of_mul_eq_mul_left gcd_pos H5, dvd.intro H6) theorem lcm.assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd.antisymm (lcm_dvd (lcm_dvd !dvd_lcm_left (dvd.trans !dvd_lcm_left !dvd_lcm_right)) (dvd.trans !dvd_lcm_right !dvd_lcm_right)) (lcm_dvd (dvd.trans !dvd_lcm_left !dvd_lcm_left) (lcm_dvd (dvd.trans !dvd_lcm_right !dvd_lcm_left) !dvd_lcm_right)) /- coprime -/ definition coprime [reducible] (m n : ℕ) : Prop := gcd m n = 1 lemma gcd_eq_one_of_coprime {m n : ℕ} : coprime m n → gcd m n = 1 := λ h, h theorem coprime_swap {m n : ℕ} (H : coprime n m) : coprime m n := !gcd.comm ▸ H theorem dvd_of_coprime_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := have H3 : gcd (m * k) (m * n) = m, from calc gcd (m * k) (m * n) = m * gcd k n : gcd_mul_left ... = m * 1 : H1 ... = m : mul_one, have H4 : (k ∣ gcd (m * k) (m * n)), from dvd_gcd !dvd_mul_left H2, H3 ▸ H4 theorem dvd_of_coprime_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := dvd_of_coprime_of_dvd_mul_right H1 (!mul.comm ▸ H2) theorem gcd_mul_left_cancel_of_coprime {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, from calc gcd (gcd (k * m) n) k = gcd (k * gcd 1 m) n : by rewrite [-gcd_mul_left, mul_one, gcd.comm, gcd.assoc] ... = 1 : by rewrite [gcd_one_left, mul_one, ↑coprime at H, H], dvd.antisymm (dvd_gcd (dvd_of_coprime_of_dvd_mul_left H1 !gcd_dvd_left) !gcd_dvd_right) (dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right) theorem gcd_mul_right_cancel_of_coprime (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := !mul.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_left_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_right_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_right_cancel_of_coprime H theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : gcd m n > 0) : coprime (m / gcd m n) (n / gcd m n) := calc gcd (m / gcd m n) (n / gcd m n) = gcd m n / gcd m n : gcd_div !gcd_dvd_left !gcd_dvd_right ... = 1 : nat.div_self H theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : d > 1) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := assume co : coprime m n, assert d ∣ gcd m n, from dvd_gcd Hm Hn, have d ∣ 1, by rewrite [↑coprime at co, co at this]; apply this, have d ≤ 1, from le_of_dvd dec_trivial this, show false, from not_lt_of_ge `d ≤ 1` `d > 1` theorem exists_coprime {m n : ℕ} (H : gcd m n > 0) : exists m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := have H1 : m = (m / gcd m n) * gcd m n, from (nat.div_mul_cancel !gcd_dvd_left)⁻¹, have H2 : n = (n / gcd m n) * gcd m n, from (nat.div_mul_cancel !gcd_dvd_right)⁻¹, exists.intro _ (exists.intro _ (and.intro (coprime_div_gcd_div_gcd H) (and.intro H1 H2))) theorem coprime_mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := calc gcd (m * n) k = gcd n k : !gcd_mul_left_cancel_of_coprime H1 ... = 1 : H2 theorem coprime_mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2)) theorem coprime_of_coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := have H1 : (gcd m n ∣ gcd (k * m) n), from !gcd_dvd_gcd_mul_left, eq_one_of_dvd_one (H ▸ H1) theorem coprime_of_coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := coprime_of_coprime_mul_left (!mul.comm ▸ H) theorem coprime_of_coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := coprime_swap (coprime_of_coprime_mul_left (coprime_swap H)) theorem coprime_of_coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := coprime_of_coprime_mul_left_right (!mul.comm ▸ H) theorem comprime_one_left : ∀ n, coprime 1 n := λ n, !gcd_one_left theorem comprime_one_right : ∀ n, coprime n 1 := λ n, !gcd_one_right theorem exists_eq_prod_and_dvd_and_dvd {m n k : nat} (H : k ∣ m * n) : ∃ m' n', k = m' * n' ∧ m' ∣ m ∧ n' ∣ n := or.elim (eq_zero_or_pos (gcd k m)) (assume H1 : gcd k m = 0, have H2 : k = 0, from eq_zero_of_gcd_eq_zero_left H1, have H3 : m = 0, from eq_zero_of_gcd_eq_zero_right H1, have H4 : k = 0 * n, from H2 ⬝ !zero_mul⁻¹, have H5 : 0 ∣ m, from H3⁻¹ ▸ !dvd.refl, have H6 : n ∣ n, from !dvd.refl, exists.intro _ (exists.intro _ (and.intro H4 (and.intro H5 H6)))) (assume H1 : gcd k m > 0, have H2 : gcd k m ∣ k, from !gcd_dvd_left, have H3 : k / gcd k m ∣ (m * n) / gcd k m, from nat.div_dvd_div H2 H, have H4 : (m * n) / gcd k m = (m / gcd k m) * n, from calc m * n / gcd k m = n * m / gcd k m : mul.comm ... = n * (m / gcd k m) : !nat.mul_div_assoc !gcd_dvd_right ... = m / gcd k m * n : mul.comm, have H5 : k / gcd k m ∣ (m / gcd k m) * n, from H4 ▸ H3, have H6 : coprime (k / gcd k m) (m / gcd k m), from coprime_div_gcd_div_gcd H1, have H7 : k / gcd k m ∣ n, from dvd_of_coprime_of_dvd_mul_left H6 H5, have H8 : k = gcd k m * (k / gcd k m), from (nat.mul_div_cancel' H2)⁻¹, exists.intro _ (exists.intro _ (and.intro H8 (and.intro !gcd_dvd_right H7)))) end nat
b6ce331b7544319ac9106f9f9ce7ea99b182ce41
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/filter/at_top_bot_auto.lean
a5c5944386f0c0d6829d59f58464a6c7f079ddf2
[]
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
57,635
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.filter.bases import Mathlib.data.finset.preimage import Mathlib.PostPort universes u_3 u_1 u_4 u_5 u_2 u_6 namespace Mathlib /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top {α : Type u_3} [preorder α] : filter α := infi fun (a : α) => principal (set.Ici a) /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot {α : Type u_3} [preorder α] : filter α := infi fun (a : α) => principal (set.Iic a) theorem mem_at_top {α : Type u_3} [preorder α] (a : α) : (set_of fun (b : α) => a ≤ b) ∈ at_top := mem_infi_sets a (set.subset.refl (set.Ici a)) theorem Ioi_mem_at_top {α : Type u_3} [preorder α] [no_top_order α] (x : α) : set.Ioi x ∈ at_top := sorry theorem mem_at_bot {α : Type u_3} [preorder α] (a : α) : (set_of fun (b : α) => b ≤ a) ∈ at_bot := mem_infi_sets a (set.subset.refl (set.Iic a)) theorem Iio_mem_at_bot {α : Type u_3} [preorder α] [no_bot_order α] (x : α) : set.Iio x ∈ at_bot := sorry theorem at_top_basis {α : Type u_3} [Nonempty α] [semilattice_sup α] : has_basis at_top (fun (_x : α) => True) set.Ici := has_basis_infi_principal (directed_of_sup fun (a b : α) => iff.mpr set.Ici_subset_Ici) theorem at_top_basis' {α : Type u_3} [semilattice_sup α] (a : α) : has_basis at_top (fun (x : α) => a ≤ x) set.Ici := sorry theorem at_bot_basis {α : Type u_3} [Nonempty α] [semilattice_inf α] : has_basis at_bot (fun (_x : α) => True) set.Iic := at_top_basis theorem at_bot_basis' {α : Type u_3} [semilattice_inf α] (a : α) : has_basis at_bot (fun (x : α) => x ≤ a) set.Iic := at_top_basis' a instance at_top_ne_bot {α : Type u_3} [Nonempty α] [semilattice_sup α] : ne_bot at_top := iff.mpr (has_basis.ne_bot_iff at_top_basis) fun (a : α) (_x : True) => set.nonempty_Ici instance at_bot_ne_bot {α : Type u_3} [Nonempty α] [semilattice_inf α] : ne_bot at_bot := at_top_ne_bot @[simp] theorem mem_at_top_sets {α : Type u_3} [Nonempty α] [semilattice_sup α] {s : set α} : s ∈ at_top ↔ ∃ (a : α), ∀ (b : α), b ≥ a → b ∈ s := iff.trans (has_basis.mem_iff at_top_basis) (exists_congr fun (_x : α) => exists_const True) @[simp] theorem mem_at_bot_sets {α : Type u_3} [Nonempty α] [semilattice_inf α] {s : set α} : s ∈ at_bot ↔ ∃ (a : α), ∀ (b : α), b ≤ a → b ∈ s := mem_at_top_sets @[simp] theorem eventually_at_top {α : Type u_3} [semilattice_sup α] [Nonempty α] {p : α → Prop} : filter.eventually (fun (x : α) => p x) at_top ↔ ∃ (a : α), ∀ (b : α), b ≥ a → p b := mem_at_top_sets @[simp] theorem eventually_at_bot {α : Type u_3} [semilattice_inf α] [Nonempty α] {p : α → Prop} : filter.eventually (fun (x : α) => p x) at_bot ↔ ∃ (a : α), ∀ (b : α), b ≤ a → p b := mem_at_bot_sets theorem eventually_ge_at_top {α : Type u_3} [preorder α] (a : α) : filter.eventually (fun (x : α) => a ≤ x) at_top := mem_at_top a theorem eventually_le_at_bot {α : Type u_3} [preorder α] (a : α) : filter.eventually (fun (x : α) => x ≤ a) at_bot := mem_at_bot a theorem eventually_gt_at_top {α : Type u_3} [preorder α] [no_top_order α] (a : α) : filter.eventually (fun (x : α) => a < x) at_top := Ioi_mem_at_top a theorem eventually_lt_at_bot {α : Type u_3} [preorder α] [no_bot_order α] (a : α) : filter.eventually (fun (x : α) => x < a) at_bot := Iio_mem_at_bot a theorem at_top_basis_Ioi {α : Type u_3} [Nonempty α] [semilattice_sup α] [no_top_order α] : has_basis at_top (fun (_x : α) => True) set.Ioi := sorry theorem at_top_countable_basis {α : Type u_3} [Nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis at_top (fun (_x : α) => True) set.Ici := has_countable_basis.mk (has_basis.mk (has_basis.mem_iff' at_top_basis)) (set.countable_encodable (set_of fun (_x : α) => True)) theorem at_bot_countable_basis {α : Type u_3} [Nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis at_bot (fun (_x : α) => True) set.Iic := has_countable_basis.mk (has_basis.mk (has_basis.mem_iff' at_bot_basis)) (set.countable_encodable (set_of fun (_x : α) => True)) theorem is_countably_generated_at_top {α : Type u_3} [Nonempty α] [semilattice_sup α] [encodable α] : is_countably_generated at_top := has_countable_basis.is_countably_generated at_top_countable_basis theorem is_countably_generated_at_bot {α : Type u_3} [Nonempty α] [semilattice_inf α] [encodable α] : is_countably_generated at_bot := has_countable_basis.is_countably_generated at_bot_countable_basis theorem order_top.at_top_eq (α : Type u_1) [order_top α] : at_top = pure ⊤ := le_antisymm (iff.mpr le_pure_iff (eventually.mono (eventually_ge_at_top ⊤) fun (b : α) => top_unique)) (le_infi fun (b : α) => iff.mpr le_principal_iff le_top) theorem order_bot.at_bot_eq (α : Type u_1) [order_bot α] : at_bot = pure ⊥ := order_top.at_top_eq (order_dual α) theorem subsingleton.at_top_eq (α : Type u_1) [subsingleton α] [preorder α] : at_top = ⊤ := sorry theorem subsingleton.at_bot_eq (α : Type u_1) [subsingleton α] [preorder α] : at_bot = ⊤ := subsingleton.at_top_eq (order_dual α) theorem tendsto_at_top_pure {α : Type u_3} {β : Type u_4} [order_top α] (f : α → β) : tendsto f at_top (pure (f ⊤)) := Eq.symm (order_top.at_top_eq α) ▸ tendsto_pure_pure f ⊤ theorem tendsto_at_bot_pure {α : Type u_3} {β : Type u_4} [order_bot α] (f : α → β) : tendsto f at_bot (pure (f ⊥)) := tendsto_at_top_pure f theorem eventually.exists_forall_of_at_top {α : Type u_3} [semilattice_sup α] [Nonempty α] {p : α → Prop} (h : filter.eventually (fun (x : α) => p x) at_top) : ∃ (a : α), ∀ (b : α), b ≥ a → p b := iff.mp eventually_at_top h theorem eventually.exists_forall_of_at_bot {α : Type u_3} [semilattice_inf α] [Nonempty α] {p : α → Prop} (h : filter.eventually (fun (x : α) => p x) at_bot) : ∃ (a : α), ∀ (b : α), b ≤ a → p b := iff.mp eventually_at_bot h theorem frequently_at_top {α : Type u_3} [semilattice_sup α] [Nonempty α] {p : α → Prop} : filter.frequently (fun (x : α) => p x) at_top ↔ ∀ (a : α), ∃ (b : α), ∃ (H : b ≥ a), p b := sorry theorem frequently_at_bot {α : Type u_3} [semilattice_inf α] [Nonempty α] {p : α → Prop} : filter.frequently (fun (x : α) => p x) at_bot ↔ ∀ (a : α), ∃ (b : α), ∃ (H : b ≤ a), p b := frequently_at_top theorem frequently_at_top' {α : Type u_3} [semilattice_sup α] [Nonempty α] [no_top_order α] {p : α → Prop} : filter.frequently (fun (x : α) => p x) at_top ↔ ∀ (a : α), ∃ (b : α), ∃ (H : b > a), p b := sorry theorem frequently_at_bot' {α : Type u_3} [semilattice_inf α] [Nonempty α] [no_bot_order α] {p : α → Prop} : filter.frequently (fun (x : α) => p x) at_bot ↔ ∀ (a : α), ∃ (b : α), ∃ (H : b < a), p b := frequently_at_top' theorem frequently.forall_exists_of_at_top {α : Type u_3} [semilattice_sup α] [Nonempty α] {p : α → Prop} (h : filter.frequently (fun (x : α) => p x) at_top) (a : α) : ∃ (b : α), ∃ (H : b ≥ a), p b := iff.mp frequently_at_top h theorem frequently.forall_exists_of_at_bot {α : Type u_3} [semilattice_inf α] [Nonempty α] {p : α → Prop} (h : filter.frequently (fun (x : α) => p x) at_bot) (a : α) : ∃ (b : α), ∃ (H : b ≤ a), p b := iff.mp frequently_at_bot h theorem map_at_top_eq {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] {f : α → β} : map f at_top = infi fun (a : α) => principal (f '' set_of fun (a' : α) => a ≤ a') := has_basis.eq_infi (has_basis.map f at_top_basis) theorem map_at_bot_eq {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] {f : α → β} : map f at_bot = infi fun (a : α) => principal (f '' set_of fun (a' : α) => a' ≤ a) := map_at_top_eq theorem tendsto_at_top {α : Type u_3} {β : Type u_4} [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ ∀ (b : β), filter.eventually (fun (a : α) => b ≤ m a) f := sorry theorem tendsto_at_bot {α : Type u_3} {β : Type u_4} [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ ∀ (b : β), filter.eventually (fun (a : α) => m a ≤ b) f := tendsto_at_top theorem tendsto_at_top_mono' {α : Type u_3} {β : Type u_4} [preorder β] (l : filter α) {f₁ : α → β} {f₂ : α → β} (h : eventually_le l f₁ f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := sorry theorem tendsto_at_bot_mono' {α : Type u_3} {β : Type u_4} [preorder β] (l : filter α) {f₁ : α → β} {f₂ : α → β} (h : eventually_le l f₁ f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := tendsto_at_top_mono' l h theorem tendsto_at_top_mono {α : Type u_3} {β : Type u_4} [preorder β] {l : filter α} {f : α → β} {g : α → β} (h : ∀ (n : α), f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l (eventually_of_forall h) theorem tendsto_at_bot_mono {α : Type u_3} {β : Type u_4} [preorder β] {l : filter α} {f : α → β} {g : α → β} (h : ∀ (n : α), f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := tendsto_at_top_mono h /-! ### Sequences -/ theorem inf_map_at_top_ne_bot_iff {α : Type u_3} {β : Type u_4} [semilattice_sup α] [Nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ map u at_top) ↔ ∀ (U : set β) (H : U ∈ F) (N : α), ∃ (n : α), ∃ (H : n ≥ N), u n ∈ U := sorry theorem inf_map_at_bot_ne_bot_iff {α : Type u_3} {β : Type u_4} [semilattice_inf α] [Nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ map u at_bot) ↔ ∀ (U : set β) (H : U ∈ F) (N : α), ∃ (n : α), ∃ (H : n ≤ N), u n ∈ U := inf_map_at_top_ne_bot_iff theorem extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ (N : ℕ), ∃ (n : ℕ), ∃ (H : n > N), P n) : ∃ (φ : ℕ → ℕ), strict_mono φ ∧ ∀ (n : ℕ), P (φ n) := sorry theorem extraction_of_frequently_at_top {P : ℕ → Prop} (h : filter.frequently (fun (n : ℕ) => P n) at_top) : ∃ (φ : ℕ → ℕ), strict_mono φ ∧ ∀ (n : ℕ), P (φ n) := extraction_of_frequently_at_top' (eq.mp (Eq._oldrec (Eq.refl (filter.frequently (fun (n : ℕ) => P n) at_top)) (propext frequently_at_top')) h) theorem extraction_of_eventually_at_top {P : ℕ → Prop} (h : filter.eventually (fun (n : ℕ) => P n) at_top) : ∃ (φ : ℕ → ℕ), strict_mono φ ∧ ∀ (n : ℕ), P (φ n) := extraction_of_frequently_at_top (eventually.frequently h) theorem exists_le_of_tendsto_at_top {α : Type u_3} {β : Type u_4} [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ (a' : α), ∃ (H : a' ≥ a), b ≤ u a' := sorry theorem exists_le_of_tendsto_at_bot {α : Type u_3} {β : Type u_4} [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) (a : α) (b : β) : ∃ (a' : α), ∃ (H : a' ≥ a), u a' ≤ b := exists_le_of_tendsto_at_top h theorem exists_lt_of_tendsto_at_top {α : Type u_3} {β : Type u_4} [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ (a' : α), ∃ (H : a' ≥ a), b < u a' := sorry theorem exists_lt_of_tendsto_at_bot {α : Type u_3} {β : Type u_4} [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) (a : α) (b : β) : ∃ (a' : α), ∃ (H : a' ≥ a), u a' < b := exists_lt_of_tendsto_at_top h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ theorem high_scores {β : Type u_4} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) (N : ℕ) : ∃ (n : ℕ), ∃ (H : n ≥ N), ∀ (k : ℕ), k < n → u k < u n := sorry /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ theorem low_scores {β : Type u_4} [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) (N : ℕ) : ∃ (n : ℕ), ∃ (H : n ≥ N), ∀ (k : ℕ), k < n → u n < u k := high_scores hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ theorem frequently_high_scores {β : Type u_4} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : filter.frequently (fun (n : ℕ) => ∀ (k : ℕ), k < n → u k < u n) at_top := sorry /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ theorem frequently_low_scores {β : Type u_4} [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : filter.frequently (fun (n : ℕ) => ∀ (k : ℕ), k < n → u n < u k) at_top := frequently_high_scores hu theorem strict_mono_subseq_of_tendsto_at_top {β : Type u_1} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ (φ : ℕ → ℕ), strict_mono φ ∧ strict_mono (u ∘ φ) := sorry theorem strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ (n : ℕ), n ≤ u n) : ∃ (φ : ℕ → ℕ), strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) theorem strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono (strict_mono.id_le h) tendsto_id theorem tendsto_at_top_add_nonneg_left' {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : filter.eventually (fun (x : α) => 0 ≤ f x) l) (hg : tendsto g l at_top) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_mono' l (eventually.mono hf fun (x : α) => le_add_of_nonneg_left) hg theorem tendsto_at_bot_add_nonpos_left' {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : filter.eventually (fun (x : α) => f x ≤ 0) l) (hg : tendsto g l at_bot) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_nonneg_left' hf hg theorem tendsto_at_top_add_nonneg_left {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : ∀ (x : α), 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg theorem tendsto_at_bot_add_nonpos_left {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : ∀ (x : α), f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_nonneg_left hf hg theorem tendsto_at_top_add_nonneg_right' {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : tendsto f l at_top) (hg : filter.eventually (fun (x : α) => 0 ≤ g x) l) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (fun (x : α) => le_add_of_nonneg_right) hg) hf theorem tendsto_at_bot_add_nonpos_right' {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : tendsto f l at_bot) (hg : filter.eventually (fun (x : α) => g x ≤ 0) l) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_nonneg_right' hf hg theorem tendsto_at_top_add_nonneg_right {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : tendsto f l at_top) (hg : ∀ (x : α), 0 ≤ g x) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) theorem tendsto_at_bot_add_nonpos_right {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : tendsto f l at_bot) (hg : ∀ (x : α), g x ≤ 0) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_nonneg_right hf hg theorem tendsto_at_top_add {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (iff.mp tendsto_at_top hf 0) hg theorem tendsto_at_bot_add {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add hf hg theorem tendsto.nsmul_at_top {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) : tendsto (fun (x : α) => n •ℕ f x) l at_top := sorry theorem tendsto.nsmul_at_bot {α : Type u_3} {β : Type u_4} [ordered_add_comm_monoid β] {l : filter α} {f : α → β} (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) : tendsto (fun (x : α) => n •ℕ f x) l at_bot := tendsto.nsmul_at_top hf hn theorem tendsto_bit0_at_top {β : Type u_4} [ordered_add_comm_monoid β] : tendsto bit0 at_top at_top := tendsto_at_top_add tendsto_id tendsto_id theorem tendsto_bit0_at_bot {β : Type u_4} [ordered_add_comm_monoid β] : tendsto bit0 at_bot at_bot := tendsto_at_bot_add tendsto_id tendsto_id theorem tendsto_at_top_of_add_const_left {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} (C : β) (hf : tendsto (fun (x : α) => C + f x) l at_top) : tendsto f l at_top := iff.mpr tendsto_at_top fun (b : β) => eventually.mono (iff.mp tendsto_at_top hf (C + b)) fun (x : α) => le_of_add_le_add_left theorem tendsto_at_bot_of_add_const_left {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} (C : β) (hf : tendsto (fun (x : α) => C + f x) l at_bot) : tendsto f l at_bot := tendsto_at_top_of_add_const_left C hf theorem tendsto_at_top_of_add_const_right {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} (C : β) (hf : tendsto (fun (x : α) => f x + C) l at_top) : tendsto f l at_top := iff.mpr tendsto_at_top fun (b : β) => eventually.mono (iff.mp tendsto_at_top hf (b + C)) fun (x : α) => le_of_add_le_add_right theorem tendsto_at_bot_of_add_const_right {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} (C : β) (hf : tendsto (fun (x : α) => f x + C) l at_bot) : tendsto f l at_bot := tendsto_at_top_of_add_const_right C hf theorem tendsto_at_top_of_add_bdd_above_left' {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : filter.eventually (fun (x : α) => f x ≤ C) l) (h : tendsto (fun (x : α) => f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (eventually.mono hC fun (x : α) (hx : f x ≤ C) => add_le_add_right hx (g x)) h) theorem tendsto_at_bot_of_add_bdd_below_left' {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : filter.eventually (fun (x : α) => C ≤ f x) l) (h : tendsto (fun (x : α) => f x + g x) l at_bot) : tendsto g l at_bot := tendsto_at_top_of_add_bdd_above_left' C hC h theorem tendsto_at_top_of_add_bdd_above_left {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : ∀ (x : α), f x ≤ C) : tendsto (fun (x : α) => f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) theorem tendsto_at_bot_of_add_bdd_below_left {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : ∀ (x : α), C ≤ f x) : tendsto (fun (x : α) => f x + g x) l at_bot → tendsto g l at_bot := tendsto_at_top_of_add_bdd_above_left C hC theorem tendsto_at_top_of_add_bdd_above_right' {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : filter.eventually (fun (x : α) => g x ≤ C) l) (h : tendsto (fun (x : α) => f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (eventually.mono hC fun (x : α) (hx : g x ≤ C) => add_le_add_left hx (f x)) h) theorem tendsto_at_bot_of_add_bdd_below_right' {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : filter.eventually (fun (x : α) => C ≤ g x) l) (h : tendsto (fun (x : α) => f x + g x) l at_bot) : tendsto f l at_bot := tendsto_at_top_of_add_bdd_above_right' C hC h theorem tendsto_at_top_of_add_bdd_above_right {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : ∀ (x : α), g x ≤ C) : tendsto (fun (x : α) => f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) theorem tendsto_at_bot_of_add_bdd_below_right {α : Type u_3} {β : Type u_4} [ordered_cancel_add_comm_monoid β] {l : filter α} {f : α → β} {g : α → β} (C : β) (hC : ∀ (x : α), C ≤ g x) : tendsto (fun (x : α) => f x + g x) l at_bot → tendsto f l at_bot := tendsto_at_top_of_add_bdd_above_right C hC theorem tendsto_at_top_add_left_of_le' {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : filter.eventually (fun (x : α) => C ≤ f x) l) (hg : tendsto g l at_top) : tendsto (fun (x : α) => f x + g x) l at_top := sorry theorem tendsto_at_bot_add_left_of_ge' {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : filter.eventually (fun (x : α) => f x ≤ C) l) (hg : tendsto g l at_bot) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_left_of_le' l C hf hg theorem tendsto_at_top_add_left_of_le {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : ∀ (x : α), C ≤ f x) (hg : tendsto g l at_top) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg theorem tendsto_at_bot_add_left_of_ge {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : ∀ (x : α), f x ≤ C) (hg : tendsto g l at_bot) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_left_of_le l C hf hg theorem tendsto_at_top_add_right_of_le' {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : tendsto f l at_top) (hg : filter.eventually (fun (x : α) => C ≤ g x) l) : tendsto (fun (x : α) => f x + g x) l at_top := sorry theorem tendsto_at_bot_add_right_of_ge' {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : tendsto f l at_bot) (hg : filter.eventually (fun (x : α) => g x ≤ C) l) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_right_of_le' l C hf hg theorem tendsto_at_top_add_right_of_le {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : tendsto f l at_top) (hg : ∀ (x : α), C ≤ g x) : tendsto (fun (x : α) => f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) theorem tendsto_at_bot_add_right_of_ge {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} {g : α → β} (C : β) (hf : tendsto f l at_bot) (hg : ∀ (x : α), g x ≤ C) : tendsto (fun (x : α) => f x + g x) l at_bot := tendsto_at_top_add_right_of_le l C hf hg theorem tendsto_at_top_add_const_left {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} (C : β) (hf : tendsto f l at_top) : tendsto (fun (x : α) => C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' fun (_x : α) => le_refl C) hf theorem tendsto_at_bot_add_const_left {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} (C : β) (hf : tendsto f l at_bot) : tendsto (fun (x : α) => C + f x) l at_bot := tendsto_at_top_add_const_left l C hf theorem tendsto_at_top_add_const_right {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} (C : β) (hf : tendsto f l at_top) : tendsto (fun (x : α) => f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' fun (_x : α) => le_refl C) theorem tendsto_at_bot_add_const_right {α : Type u_3} {β : Type u_4} [ordered_add_comm_group β] (l : filter α) {f : α → β} (C : β) (hf : tendsto f l at_bot) : tendsto (fun (x : α) => f x + C) l at_bot := tendsto_at_top_add_const_right l C hf theorem tendsto_neg_at_top_at_bot {β : Type u_4} [ordered_add_comm_group β] : tendsto Neg.neg at_top at_bot := sorry theorem tendsto_neg_at_bot_at_top {β : Type u_4} [ordered_add_comm_group β] : tendsto Neg.neg at_bot at_top := tendsto_neg_at_top_at_bot theorem tendsto_bit1_at_top {α : Type u_3} [ordered_semiring α] : tendsto bit1 at_top at_top := tendsto_at_top_add_nonneg_right tendsto_bit0_at_top fun (_x : α) => zero_le_one theorem tendsto.at_top_mul_at_top {α : Type u_3} {β : Type u_4} [ordered_semiring α] {l : filter β} {f : β → α} {g : β → α} (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (fun (x : β) => f x * g x) l at_top := sorry theorem tendsto_mul_self_at_top {α : Type u_3} [ordered_semiring α] : tendsto (fun (x : α) => x * x) at_top at_top := tendsto.at_top_mul_at_top tendsto_id tendsto_id /-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_at_top`. -/ theorem tendsto_pow_at_top {α : Type u_3} [ordered_semiring α] {n : ℕ} (hn : 1 ≤ n) : tendsto (fun (x : α) => x ^ n) at_top at_top := sorry theorem zero_pow_eventually_eq {α : Type u_3} [monoid_with_zero α] : eventually_eq at_top (fun (n : ℕ) => 0 ^ n) fun (n : ℕ) => 0 := iff.mpr eventually_at_top (Exists.intro 1 fun (n : ℕ) (hn : n ≥ 1) => zero_pow (has_lt.lt.trans_le zero_lt_one hn)) theorem tendsto.at_top_mul_at_bot {α : Type u_3} {β : Type u_4} [ordered_ring α] {l : filter β} {f : β → α} {g : β → α} (hf : tendsto f l at_top) (hg : tendsto g l at_bot) : tendsto (fun (x : β) => f x * g x) l at_bot := sorry theorem tendsto.at_bot_mul_at_top {α : Type u_3} {β : Type u_4} [ordered_ring α] {l : filter β} {f : β → α} {g : β → α} (hf : tendsto f l at_bot) (hg : tendsto g l at_top) : tendsto (fun (x : β) => f x * g x) l at_bot := sorry theorem tendsto.at_bot_mul_at_bot {α : Type u_3} {β : Type u_4} [ordered_ring α] {l : filter β} {f : β → α} {g : β → α} (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (fun (x : β) => f x * g x) l at_top := sorry /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ theorem tendsto_abs_at_top_at_top {α : Type u_3} [linear_ordered_add_comm_group α] : tendsto abs at_top at_top := tendsto_at_top_mono le_abs_self tendsto_id /-- $\lim_{x\to-\infty}|x|=+\infty$ -/ theorem tendsto_abs_at_bot_at_top {α : Type u_3} [linear_ordered_add_comm_group α] : tendsto abs at_bot at_top := tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top theorem tendsto.at_top_of_const_mul {α : Type u_3} {β : Type u_4} [linear_ordered_semiring α] {l : filter β} {f : β → α} {c : α} (hc : 0 < c) (hf : tendsto (fun (x : β) => c * f x) l at_top) : tendsto f l at_top := iff.mpr tendsto_at_top fun (b : α) => eventually.mono (iff.mp tendsto_at_top hf (c * b)) fun (x : β) (hx : c * b ≤ c * f x) => le_of_mul_le_mul_left hx hc theorem tendsto.at_top_of_mul_const {α : Type u_3} {β : Type u_4} [linear_ordered_semiring α] {l : filter β} {f : β → α} {c : α} (hc : 0 < c) (hf : tendsto (fun (x : β) => f x * c) l at_top) : tendsto f l at_top := sorry theorem nonneg_of_eventually_pow_nonneg {α : Type u_3} [linear_ordered_ring α] {a : α} (h : filter.eventually (fun (n : ℕ) => 0 ≤ a ^ n) at_top) : 0 ≤ a := (fun (_a : ∃ (x : ℕ), (fun (x : ℕ) => 0 ≤ a ^ bit1 x) x) => Exists.dcases_on _a fun (w : ℕ) (h_1 : 0 ≤ a ^ bit1 w) => idRhs (0 ≤ a) (iff.mp pow_bit1_nonneg_iff h_1)) (eventually.exists (tendsto.eventually tendsto_bit1_at_top h)) /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.const_mul_at_top'` instead. -/ theorem tendsto.const_mul_at_top {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (fun (x : β) => r * f x) l at_top := sorry /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.at_top_mul_const'` instead. -/ theorem tendsto.at_top_mul_const {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (fun (x : β) => f x * r) l at_top := sorry /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ theorem tendsto.at_top_div_const {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (fun (x : β) => f x / r) l at_top := tendsto.at_top_mul_const (iff.mpr inv_pos hr) hf /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the left) tends to negative infinity. -/ theorem tendsto.neg_const_mul_at_top {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : r < 0) (hf : tendsto f l at_top) : tendsto (fun (x : β) => r * f x) l at_bot := sorry /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the right) tends to negative infinity. -/ theorem tendsto.at_top_mul_neg_const {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : r < 0) (hf : tendsto f l at_top) : tendsto (fun (x : β) => f x * r) l at_bot := sorry /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to negative infinity. -/ theorem tendsto.const_mul_at_bot {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (fun (x : β) => r * f x) l at_bot := sorry /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to negative infinity. -/ theorem tendsto.at_bot_mul_const {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (fun (x : β) => f x * r) l at_bot := sorry /-- If a function tends to negative infinity along a filter, then this function divided by a positive constant also tends to negative infinity. -/ theorem tendsto.at_bot_div_const {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (fun (x : β) => f x / r) l at_bot := tendsto.at_bot_mul_const (iff.mpr inv_pos hr) hf /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the left) tends to positive infinity. -/ theorem tendsto.neg_const_mul_at_bot {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (fun (x : β) => r * f x) l at_top := sorry /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the right) tends to positive infinity. -/ theorem tendsto.at_bot_mul_neg_const {α : Type u_3} {β : Type u_4} [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (fun (x : β) => f x * r) l at_top := sorry theorem tendsto_at_top' {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ ∀ (s : set β), s ∈ l → ∃ (a : α), ∀ (b : α), b ≥ a → f b ∈ s := sorry theorem tendsto_at_bot' {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ ∀ (s : set β), s ∈ l → ∃ (a : α), ∀ (b : α), b ≤ a → f b ∈ s := tendsto_at_top' theorem tendsto_at_top_principal {α : Type u_3} {β : Type u_4} [Nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (principal s) ↔ ∃ (N : β), ∀ (n : β), n ≥ N → f n ∈ s := sorry theorem tendsto_at_bot_principal {α : Type u_3} {β : Type u_4} [Nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (principal s) ↔ ∃ (N : β), ∀ (n : β), n ≤ N → f n ∈ s := tendsto_at_top_principal /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ theorem tendsto_at_top_at_top {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → b ≤ f a := iff.trans tendsto_infi (forall_congr fun (b : β) => tendsto_at_top_principal) theorem tendsto_at_top_at_bot {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := tendsto_at_top_at_top theorem tendsto_at_bot_at_top {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := tendsto_at_top_at_top theorem tendsto_at_bot_at_bot {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := tendsto_at_top_at_top theorem tendsto_at_top_at_top_of_monotone {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ (b : β), ∃ (a : α), b ≤ f a) : tendsto f at_top at_top := sorry theorem tendsto_at_bot_at_bot_of_monotone {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ (b : β), ∃ (a : α), f a ≤ b) : tendsto f at_bot at_bot := sorry theorem tendsto_at_top_at_top_iff_of_monotone {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ (b : β), ∃ (a : α), b ≤ f a := sorry theorem tendsto_at_bot_at_bot_iff_of_monotone {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (a : α), f a ≤ b := sorry theorem Mathlib.monotone.tendsto_at_top_at_top {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ (b : β), ∃ (a : α), b ≤ f a) : tendsto f at_top at_top := tendsto_at_top_at_top_of_monotone theorem Mathlib.monotone.tendsto_at_bot_at_bot {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ (b : β), ∃ (a : α), f a ≤ b) : tendsto f at_bot at_bot := tendsto_at_bot_at_bot_of_monotone theorem Mathlib.monotone.tendsto_at_top_at_top_iff {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ (b : β), ∃ (a : α), b ≤ f a := tendsto_at_top_at_top_iff_of_monotone theorem Mathlib.monotone.tendsto_at_bot_at_bot_iff {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (a : α), f a ≤ b := tendsto_at_bot_at_bot_iff_of_monotone theorem tendsto_at_top_embedding {α : Type u_3} {β : Type u_4} {γ : Type u_5} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀ (b₁ b₂ : β), e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀ (c : γ), ∃ (b : β), c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := sorry /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ theorem tendsto_at_bot_embedding {α : Type u_3} {β : Type u_4} {γ : Type u_5} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀ (b₁ b₂ : β), e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀ (c : γ), ∃ (b : β), e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := tendsto_at_top_embedding (function.swap hm) hu theorem tendsto_finset_range : tendsto finset.range at_top at_top := monotone.tendsto_at_top_at_top finset.range_mono finset.exists_nat_subset_range theorem at_top_finset_eq_infi {α : Type u_3} : at_top = infi fun (x : α) => principal (set.Ici (singleton x)) := sorry /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ theorem tendsto_at_top_finset_of_monotone {α : Type u_3} {β : Type u_4} [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ (x : α), ∃ (n : β), x ∈ f n) : tendsto f at_top at_top := sorry theorem Mathlib.monotone.tendsto_at_top_finset {α : Type u_3} {β : Type u_4} [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ (x : α), ∃ (n : β), x ∈ f n) : tendsto f at_top at_top := tendsto_at_top_finset_of_monotone theorem tendsto_finset_image_at_top_at_top {β : Type u_4} {γ : Type u_5} {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := sorry theorem tendsto_finset_preimage_at_top_at_top {α : Type u_3} {β : Type u_4} {f : α → β} (hf : function.injective f) : tendsto (fun (s : finset β) => finset.preimage s f (function.injective.inj_on hf (f ⁻¹' ↑s))) at_top at_top := monotone.tendsto_at_top_finset (finset.monotone_preimage hf) fun (x : α) => Exists.intro (singleton (f x)) (iff.mpr finset.mem_preimage (finset.mem_singleton_self (f x))) theorem prod_at_top_at_top_eq {β₁ : Type u_1} {β₂ : Type u_2} [semilattice_sup β₁] [semilattice_sup β₂] : filter.prod at_top at_top = at_top := sorry theorem prod_at_bot_at_bot_eq {β₁ : Type u_1} {β₂ : Type u_2} [semilattice_inf β₁] [semilattice_inf β₂] : filter.prod at_bot at_bot = at_bot := prod_at_top_at_top_eq theorem prod_map_at_top_eq {α₁ : Type u_1} {α₂ : Type u_2} {β₁ : Type u_3} {β₂ : Type u_4} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : filter.prod (map u₁ at_top) (map u₂ at_top) = map (prod.map u₁ u₂) at_top := sorry theorem prod_map_at_bot_eq {α₁ : Type u_1} {α₂ : Type u_2} {β₁ : Type u_3} {β₂ : Type u_4} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : filter.prod (map u₁ at_bot) (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := prod_map_at_top_eq u₁ u₂ /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ theorem map_at_top_eq_of_gc {α : Type u_3} {β : Type u_4} [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀ (a : α) (b : β), b ≥ b' → (f a ≤ b ↔ a ≤ g b)) (hgi : ∀ (b : β), b ≥ b' → b ≤ f (g b)) : map f at_top = at_top := sorry theorem map_at_bot_eq_of_gc {α : Type u_3} {β : Type u_4} [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀ (a : α) (b : β), b ≤ b' → (b ≤ f a ↔ g b ≤ a)) (hgi : ∀ (b : β), b ≤ b' → f (g b) ≤ b) : map f at_bot = at_bot := map_at_top_eq_of_gc (fun (b : β) => g b) b' (monotone.order_dual hf) gc hgi theorem map_coe_at_top_of_Ici_subset {α : Type u_3} [semilattice_sup α] {a : α} {s : set α} (h : set.Ici a ⊆ s) : map coe at_top = at_top := sorry /-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/ @[simp] theorem map_coe_Ici_at_top {α : Type u_3} [semilattice_sup α] (a : α) : map coe at_top = at_top := map_coe_at_top_of_Ici_subset (set.subset.refl (set.Ici a)) /-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/ @[simp] theorem map_coe_Ioi_at_top {α : Type u_3} [semilattice_sup α] [no_top_order α] (a : α) : map coe at_top = at_top := Exists.dcases_on (no_top a) fun (b : α) (hb : a < b) => map_coe_at_top_of_Ici_subset (iff.mpr set.Ici_subset_Ioi hb) /-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient order. -/ theorem at_top_Ioi_eq {α : Type u_3} [semilattice_sup α] (a : α) : at_top = comap coe at_top := sorry /-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient order. -/ theorem at_top_Ici_eq {α : Type u_3} [semilattice_sup α] (a : α) : at_top = comap coe at_top := eq.mpr (id (Eq._oldrec (Eq.refl (at_top = comap coe at_top)) (Eq.symm (map_coe_Ici_at_top a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (at_top = comap coe (map coe at_top))) (comap_map subtype.coe_injective))) (Eq.refl at_top)) /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ @[simp] theorem map_coe_Iio_at_bot {α : Type u_3} [semilattice_inf α] [no_bot_order α] (a : α) : map coe at_bot = at_bot := map_coe_Ioi_at_top a /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ theorem at_bot_Iio_eq {α : Type u_3} [semilattice_inf α] (a : α) : at_bot = comap coe at_bot := at_top_Ioi_eq a /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ @[simp] theorem map_coe_Iic_at_bot {α : Type u_3} [semilattice_inf α] (a : α) : map coe at_bot = at_bot := map_coe_Ici_at_top a /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ theorem at_bot_Iic_eq {α : Type u_3} [semilattice_inf α] (a : α) : at_bot = comap coe at_bot := at_top_Ici_eq a theorem tendsto_Ioi_at_top {α : Type u_3} {β : Type u_4} [semilattice_sup α] {a : α} {f : β → ↥(set.Ioi a)} {l : filter β} : tendsto f l at_top ↔ tendsto (fun (x : β) => ↑(f x)) l at_top := sorry theorem tendsto_Iio_at_bot {α : Type u_3} {β : Type u_4} [semilattice_inf α] {a : α} {f : β → ↥(set.Iio a)} {l : filter β} : tendsto f l at_bot ↔ tendsto (fun (x : β) => ↑(f x)) l at_bot := sorry theorem tendsto_Ici_at_top {α : Type u_3} {β : Type u_4} [semilattice_sup α] {a : α} {f : β → ↥(set.Ici a)} {l : filter β} : tendsto f l at_top ↔ tendsto (fun (x : β) => ↑(f x)) l at_top := sorry theorem tendsto_Iic_at_bot {α : Type u_3} {β : Type u_4} [semilattice_inf α] {a : α} {f : β → ↥(set.Iic a)} {l : filter β} : tendsto f l at_bot ↔ tendsto (fun (x : β) => ↑(f x)) l at_bot := sorry @[simp] theorem tendsto_comp_coe_Ioi_at_top {α : Type u_3} {β : Type u_4} [semilattice_sup α] [no_top_order α] {a : α} {f : α → β} {l : filter β} : tendsto (fun (x : ↥(set.Ioi a)) => f ↑x) at_top l ↔ tendsto f at_top l := sorry @[simp] theorem tendsto_comp_coe_Ici_at_top {α : Type u_3} {β : Type u_4} [semilattice_sup α] {a : α} {f : α → β} {l : filter β} : tendsto (fun (x : ↥(set.Ici a)) => f ↑x) at_top l ↔ tendsto f at_top l := sorry @[simp] theorem tendsto_comp_coe_Iio_at_bot {α : Type u_3} {β : Type u_4} [semilattice_inf α] [no_bot_order α] {a : α} {f : α → β} {l : filter β} : tendsto (fun (x : ↥(set.Iio a)) => f ↑x) at_bot l ↔ tendsto f at_bot l := sorry @[simp] theorem tendsto_comp_coe_Iic_at_bot {α : Type u_3} {β : Type u_4} [semilattice_inf α] {a : α} {f : α → β} {l : filter β} : tendsto (fun (x : ↥(set.Iic a)) => f ↑x) at_bot l ↔ tendsto f at_bot l := sorry theorem map_add_at_top_eq_nat (k : ℕ) : map (fun (a : ℕ) => a + k) at_top = at_top := map_at_top_eq_of_gc (fun (a : ℕ) => a - k) k (fun (a b : ℕ) (h : a ≤ b) => add_le_add_right h k) (fun (a b : ℕ) (h : b ≥ k) => iff.symm (nat.le_sub_right_iff_add_le h)) fun (a : ℕ) (h : a ≥ k) => eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ a - k + k)) (nat.sub_add_cancel h))) (le_refl a) theorem map_sub_at_top_eq_nat (k : ℕ) : map (fun (a : ℕ) => a - k) at_top = at_top := map_at_top_eq_of_gc (fun (a : ℕ) => a + k) 0 (fun (a b : ℕ) (h : a ≤ b) => nat.sub_le_sub_right h k) (fun (a b : ℕ) (_x : b ≥ 0) => nat.sub_le_right_iff_le_add) fun (b : ℕ) (_x : b ≥ 0) => eq.mpr (id (Eq._oldrec (Eq.refl (b ≤ b + k - k)) (nat.add_sub_cancel b k))) (le_refl b) theorem tendsto_add_at_top_nat (k : ℕ) : tendsto (fun (a : ℕ) => a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) theorem tendsto_sub_at_top_nat (k : ℕ) : tendsto (fun (a : ℕ) => a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) theorem tendsto_add_at_top_iff_nat {α : Type u_3} {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (fun (n : ℕ) => f (n + k)) at_top l ↔ tendsto f at_top l := sorry theorem map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (fun (a : ℕ) => a / k) at_top = at_top := sorry /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ theorem tendsto_at_top_at_top_of_monotone' {ι : Type u_1} {α : Type u_3} [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (set.range u)) : tendsto u at_top at_top := sorry /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ theorem tendsto_at_bot_at_bot_of_monotone' {ι : Type u_1} {α : Type u_3} [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (set.range u)) : tendsto u at_bot at_bot := tendsto_at_top_at_top_of_monotone' (monotone.order_dual h) H theorem unbounded_of_tendsto_at_top {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬bdd_above (set.range f) := sorry theorem unbounded_of_tendsto_at_bot {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬bdd_below (set.range f) := unbounded_of_tendsto_at_top h theorem unbounded_of_tendsto_at_top' {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬bdd_above (set.range f) := unbounded_of_tendsto_at_top h theorem unbounded_of_tendsto_at_bot' {α : Type u_3} {β : Type u_4} [Nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬bdd_below (set.range f) := unbounded_of_tendsto_at_top h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ theorem tendsto_at_top_of_monotone_of_filter {ι : Type u_1} {α : Type u_3} [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := monotone.tendsto_at_top_at_top h fun (b : α) => eventually.exists (tendsto.eventually hu (mem_at_top b)) /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ theorem tendsto_at_bot_of_monotone_of_filter {ι : Type u_1} {α : Type u_3} [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := tendsto_at_top_of_monotone_of_filter (monotone.order_dual h) hu theorem tendsto_at_top_of_monotone_of_subseq {ι : Type u_1} {ι' : Type u_2} {α : Type u_3} [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) theorem tendsto_at_bot_of_monotone_of_subseq {ι : Type u_1} {ι' : Type u_2} {α : Type u_3} [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ theorem map_at_top_finset_prod_le_of_prod_eq {α : Type u_3} {β : Type u_4} {γ : Type u_5} [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀ (u : finset γ), ∃ (v : finset β), ∀ (v' : finset β), v ⊆ v' → ∃ (u' : finset γ), u ⊆ u' ∧ (finset.prod u' fun (x : γ) => g x) = finset.prod v' fun (b : β) => f b) : map (fun (s : finset β) => finset.prod s fun (b : β) => f b) at_top ≤ map (fun (s : finset γ) => finset.prod s fun (x : γ) => g x) at_top := sorry theorem has_antimono_basis.tendsto {ι : Type u_1} {α : Type u_3} [semilattice_sup ι] [Nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : has_antimono_basis l p s) {φ : ι → α} (h : ∀ (i : ι), φ i ∈ s i) : tendsto φ at_top l := sorry namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ theorem tendsto_iff_seq_tendsto {α : Type u_3} {β : Type u_4} {f : α → β} {k : filter α} {l : filter β} (hcb : is_countably_generated k) : tendsto f k l ↔ ∀ (x : ℕ → α), tendsto x at_top k → tendsto (f ∘ x) at_top l := sorry theorem tendsto_of_seq_tendsto {α : Type u_3} {β : Type u_4} {f : α → β} {k : filter α} {l : filter β} (hcb : is_countably_generated k) : (∀ (x : ℕ → α), tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := iff.mpr (tendsto_iff_seq_tendsto hcb) theorem subseq_tendsto {α : Type u_3} {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), strict_mono θ ∧ tendsto (u ∘ θ) at_top f := sorry end is_countably_generated end filter theorem exists_lt_mul_self {R : Type u_6} [linear_ordered_semiring R] (a : R) : ∃ (x : R), ∃ (H : x ≥ 0), a < x * x := sorry theorem exists_le_mul_self {R : Type u_6} [linear_ordered_semiring R] (a : R) : ∃ (x : R), ∃ (H : x ≥ 0), a ≤ x * x := sorry namespace order_iso @[simp] theorem comap_at_top {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] (e : α ≃o β) : filter.comap (⇑e) filter.at_top = filter.at_top := sorry @[simp] theorem comap_at_bot {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] (e : α ≃o β) : filter.comap (⇑e) filter.at_bot = filter.at_bot := comap_at_top (order_iso.dual e) @[simp] theorem map_at_top {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] (e : α ≃o β) : filter.map (⇑e) filter.at_top = filter.at_top := sorry @[simp] theorem map_at_bot {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] (e : α ≃o β) : filter.map (⇑e) filter.at_bot = filter.at_bot := map_at_top (order_iso.dual e) theorem tendsto_at_top {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] (e : α ≃o β) : filter.tendsto (⇑e) filter.at_top filter.at_top := eq.le (map_at_top e) theorem tendsto_at_bot {α : Type u_3} {β : Type u_4} [preorder α] [preorder β] (e : α ≃o β) : filter.tendsto (⇑e) filter.at_bot filter.at_bot := eq.le (map_at_bot e) @[simp] theorem tendsto_at_top_iff {α : Type u_3} {β : Type u_4} {γ : Type u_5} [preorder α] [preorder β] {l : filter γ} {f : γ → α} (e : α ≃o β) : filter.tendsto (fun (x : γ) => coe_fn e (f x)) l filter.at_top ↔ filter.tendsto f l filter.at_top := sorry @[simp] theorem tendsto_at_bot_iff {α : Type u_3} {β : Type u_4} {γ : Type u_5} [preorder α] [preorder β] {l : filter γ} {f : γ → α} (e : α ≃o β) : filter.tendsto (fun (x : γ) => coe_fn e (f x)) l filter.at_bot ↔ filter.tendsto f l filter.at_bot := tendsto_at_top_iff (order_iso.dual e) end order_iso /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ theorem function.injective.map_at_top_finset_sum_eq {α : Type u_3} {β : Type u_4} {γ : Type u_5} [add_comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ (x : β), ¬x ∈ set.range g → f x = 0) : filter.map (fun (s : finset γ) => finset.sum s fun (i : γ) => f (g i)) filter.at_top = filter.map (fun (s : finset β) => finset.sum s fun (i : β) => f i) filter.at_top := sorry end Mathlib
4dd31fd0861624d541fba60e8ed2f9fedd7bb273
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/data/ordering/default.lean
729647f40cba42a68b0b61d13bed464ccb50ea96
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
194
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import .basic .lemmas
9b5154f263e2ecf81042bd841b8c3beee493d4c3
c3de33d4701e6113627153fe1103b255e752ed7d
/data/list/sort.lean
e3c3aed2f5cbd86b57590f8f52af3422c5a6b68e
[]
no_license
jroesch/library_dev
77d2b246ff47ab05d55cb9706a37d3de97038388
4faa0a45c6aa7eee6e661113c2072b8840bff79b
refs/heads/master
1,611,281,606,352
1,495,661,644,000
1,495,661,644,000
92,340,430
0
0
null
1,495,663,344,000
1,495,663,344,000
null
UTF-8
Lean
false
false
15,877
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Insertion sort and merge sort. -/ import .perm -- TODO(Jeremy): move this namespace nat theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma succ_le_succ_iff (m n : ℕ) : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ lemma lt_succ_iff_le (m n : ℕ) : m < succ n ↔ m ≤ n := succ_le_succ_iff m n end nat namespace list section sorted universe variable uu variables {α : Type uu} (r : α → α → Prop) def sorted : list α → Prop | [] := true | (a :: l) := sorted l ∧ ∀ b ∈ l, r a b theorem sorted_nil : sorted r nil := trivial theorem sorted_singleton (a : α) : sorted r [a] := ⟨sorted_nil r, λ b h, absurd h (not_mem_nil b)⟩ theorem sorted_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : sorted r l := h^.left theorem forall_mem_rel_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : ∀ b ∈ l, r a b := h^.right theorem sorted_cons {a : α} {l : list α} (h₁ : sorted r l) (h₂ : ∀ b ∈ l, r a b) : sorted r (a :: l) := ⟨h₁, h₂⟩ end sorted /- sorting procedures -/ section sort universe variable uu parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r] local infix `≼` : 50 := r /- insertion sort -/ section insertion_sort def ordered_insert (a : α) : list α → list α | [] := [a] | (b :: l) := if a ≼ b then a :: (b :: l) else b :: ordered_insert l --@[simp] --theorem ordered_insert_nil (a : α) : ordered_insert a [] = [a] := rfl --@[simp] --theorem ordered_insert_cons (a b : α) (l : list α) : -- ordered_insert a (b :: l) = if a ≼ b then a :: (b :: l) else b :: ordered_insert a l := --rfl def insertion_sort : list α → list α | [] := [] | (b :: l) := ordered_insert b (insertion_sort l) --attribute [simp] insertion_sort.equations.eqn_1 insertion_sort.equations.eqn_2 section correctness parameter [deceqα : decidable_eq α] include deceqα open perm -- TODO(Jeremy): anonymous type class parameters don't work well theorem count_ordered_insert_eq (b a : α) : ∀ l, count b (ordered_insert a l) = count b (a :: l) | [] := by simp [ordered_insert] | (c :: l) := if h : a ≼ c then begin unfold ordered_insert, simp [if_pos, h] end else by simp [ordered_insert, if_neg, h, count_cons', count_ordered_insert_eq] theorem mem_ordered_insert_iff (b a : α) (l : list α) : b ∈ ordered_insert a l ↔ b ∈ a :: l := begin repeat {rw mem_iff_count_pos}, simp [count_ordered_insert_eq] end theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l | [] := perm.nil | (b :: l) := perm_of_forall_count_eq (take a, by simp [insertion_sort, count_ordered_insert_eq, count_cons', count_eq_count_of_perm (perm_insertion_sort l) a]) section total_and_transitive variables (totr : total r) (transr : transitive r) include totr transr theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l) | [] := assume h, sorted_singleton r a | (b :: l) := assume h, have sorted r l, from sorted_of_sorted_cons r h, have h₀ : ∀ c ∈ l, b ≼ c, from forall_mem_rel_of_sorted_cons r h, if h' : a ≼ b then begin simp [ordered_insert, if_pos, h'], have ∀ c ∈ b :: l, a ≼ c, from take c, suppose c ∈ b :: l, or.elim (eq_or_mem_of_mem_cons this) (suppose c = b, this^.symm ▸ ‹a ≼ b›) (suppose c ∈ l, transr ‹a ≼ b› (h₀ _ this)), show sorted r (a :: b :: l), from sorted_cons r h this end else have b ≼ a, from or.resolve_left (totr a b) h', begin simp [ordered_insert, if_neg, ‹¬ a ≼ b›], have h₁ : sorted r (ordered_insert r a l), from sorted_ordered_insert l ‹sorted r l›, have h₂ : ∀ c ∈ ordered_insert r a l, b ≼ c, from take c, suppose c ∈ ordered_insert r a l, have c ∈ a :: l, from (mem_ordered_insert_iff r c a l)^.mp this, or.elim (eq_or_mem_of_mem_cons this) (suppose c = a, begin rw this, exact ‹b ≼ a› end) (suppose c ∈ l, h₀ c this), show sorted r (b :: ordered_insert r a l), from sorted_cons r h₁ h₂ end theorem sorted_insert_sort : ∀ l, sorted r (insertion_sort l) | [] := sorted_nil r | (a :: l) := sorted_ordered_insert totr transr a _ (sorted_insert_sort l) end total_and_transitive end correctness end insertion_sort /- merge sort -/ section merge_sort -- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the -- equation compiler can't prove the third equation def split : list α → list α × list α | [] := ([], []) | [a] := ([a], []) | (a :: b :: l) := match split l with | (l₁, l₂) := (a :: l₁, b :: l₂) end -- TODO(Jeremy): the cases is needed because the internal split_match gets a pair private theorem split_cons_cons_aux (a b : α) (l : list α) : split (a :: b :: l) = match split l with | (l₁, l₂) := (a :: l₁, b :: l₂) end := rfl @[simp] theorem split_cons_cons (a b : α) (l : list α) : split (a :: b :: l) = (a :: (split l).1, b :: (split l).2) := begin rw [split_cons_cons_aux], cases split l, reflexivity end theorem length_split_fst_le : ∀ l : list α, length ((split l).1) ≤ length l | [] := nat.le_refl 0 | [a] := nat.le_refl 1 | (a :: b :: l) := begin simp [split_cons_cons] without add_comm, exact nat.succ_le_succ (nat.le_succ_of_le (length_split_fst_le l)) end theorem length_split_snd_le : ∀ l : list α, length ((split l).2) ≤ length l | [] := nat.le_refl 0 | [a] := nat.zero_le 1 | (a :: b :: l) := begin simp without add_comm, transitivity, { apply add_le_add_right (length_split_snd_le l) }, simp [nat.one_add, nat.le_succ] end theorem length_split_cons_cons_fst_lt (a b : α) (l : list α) : length (split (a :: b :: l)).1 < length (a :: b :: l) := begin simp without add_comm, exact add_lt_add_of_le_of_lt (length_split_fst_le l) (nat.le_refl _) end theorem length_split_cons_cons_snd_lt (a b : α) (l : list α) : length (split (a :: b :: l)).2 < length (a :: b :: l) := begin simp without add_comm, exact add_lt_add_of_le_of_lt (length_split_snd_le l) (nat.le_refl _) end -- Do the well-founded recursion by hand, until the function definition system supports it. private def merge.F : Π p : list α × list α, (Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → list α) → list α | ([], l) f := l | (a :: l, []) f := a :: l | (a :: l, b :: l') f := if a ≼ b then a :: f (l, b :: l') begin simp without add_comm, apply nat.le_refl end else b :: f (a :: l, l') begin apply nat.le_refl end def merge := well_founded.fix (inv_image.wf _ nat.lt_wf) merge.F theorem merge.def (p : list α × list α) : merge p = merge.F p (λ p h, merge p) := well_founded.fix_eq (inv_image.wf _ nat.lt_wf) merge.F p @[simp] theorem merge.equations.eq_1 (l : list α) : merge ([], l) = l := begin rw merge.def, reflexivity end @[simp] theorem merge.equations.eq_2 (a : α) (l : list α) : merge (a :: l, []) = a :: l := begin rw merge.def, reflexivity end @[simp] theorem merge.equations.eq_3 (a b : α) (l l' : list α) : merge (a :: l, b :: l') = if a ≼ b then a :: merge (l, b :: l') else b :: merge (a :: l, l') := begin rw merge.def, reflexivity end private def merge_sort.F : Π l : list α, (Π l₁ : list α, length l₁ < length l → list α) → list α | [] f := [] | [a] f := [a] | (a :: b :: l) f := let p := split (a :: b :: l), l₁ := f p.1 (length_split_cons_cons_fst_lt a b l), l₂ := f p.2 (length_split_cons_cons_snd_lt a b l) in merge (l₁, l₂) def merge_sort := well_founded.fix (inv_image.wf _ nat.lt_wf) merge_sort.F theorem merge_sort.def (l : list α) : merge_sort l = merge_sort.F l (λ l h, merge_sort l) := well_founded.fix_eq (inv_image.wf _ nat.lt_wf) merge_sort.F l @[simp] theorem merge_sort.equations.eq_1 : merge_sort [] = [] := begin rw merge_sort.def, reflexivity end @[simp] theorem merge_sort.equations.eq_2 (a : α) : merge_sort [a] = [a] := begin rw merge_sort.def, reflexivity end @[simp] theorem merge_sort.equations.eq_3 (a b : α) (l : list α) : merge_sort (a :: b :: l) = let p := split (a :: b :: l) in merge (merge_sort p.1, merge_sort p.2) := begin rw merge_sort.def, reflexivity end section correctness parameter [deceqα : decidable_eq α] include deceqα theorem count_split (a : α) : ∀ l : list α, count a (split l).1 + count a (split l).2 = count a l | [] := rfl | [a] := rfl | (a :: b :: l) := begin simp [count_cons'], rw [-count_split l], simp end private def count_merge.F (c : α) : Π p : list α × list α, (Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → count c (merge p₁) = count c p₁.1 + count c p₁.2) → count c (merge p) = count c p.1 + count c p.2 | ([], l) f := by simp | (a :: l, []) f := by simp | (a :: l, b :: l') f := if h : a ≼ b then begin note hrec := f (l, b :: l') begin simp without add_comm, apply nat.le_refl end, simp [if_pos, h, count_cons', hrec] end else begin note hrec := f (a :: l, l') begin apply nat.le_refl end, simp [if_neg, h, count_cons', hrec] end theorem count_merge (c : α) : ∀ p : list α × list α, count c (merge p) = count c p.1 + count c p.2 := well_founded.fix (inv_image.wf _ nat.lt_wf) (count_merge.F c) theorem mem_merge_iff (a : α) (p : list α × list α) : a ∈ merge p ↔ a ∈ p.1 ∨ a ∈ p.2 := begin repeat { rw mem_iff_count_pos }, simp [count_merge, nat.add_pos_iff_pos_or_pos] end private def perm_merge_sort.F : Π l : list α, (Π l₁ : list α, length l₁ < length l → merge_sort l₁ ~ l₁) → merge_sort l ~ l | [] f := by simp; exact perm.refl _ | [a] f := by simp; exact perm.refl _ | (a :: b :: l) f := perm.perm_of_forall_count_eq begin intro c, pose hrec₁ := perm.count_eq_count_of_perm (f _ (length_split_cons_cons_fst_lt a b l)) c, pose hrec₂ := perm.count_eq_count_of_perm (f _ (length_split_cons_cons_snd_lt a b l)) c, simp at hrec₁, simp at hrec₂, simp [hrec₁, hrec₂, count_merge, count_split, count_cons'] end theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l := well_founded.fix (inv_image.wf _ nat.lt_wf) perm_merge_sort.F section total_and_transitive variables (totr : total r) (transr : transitive r) include totr transr private def sorted_merge.F : Π p : list α × list α, (Π p₁ : list α × list α, length p₁.1 + length p₁.2 < length p.1 + length p.2 → (sorted r p₁.1 → sorted r p₁.2 → sorted r (merge p₁))) → sorted r p.1 → sorted r p.2 → sorted r (merge p) | ([], l) f h₁ h₂ := begin simp, exact h₂ end | (a :: l, []) f h₁ h₂ := begin simp, exact h₁ end | (a :: l, b :: l') f h₁ h₂ := have sorted r l, from sorted_of_sorted_cons r h₁, have sorted r l', from sorted_of_sorted_cons r h₂, have h₁₀ : ∀ c ∈ l, a ≼ c, from forall_mem_rel_of_sorted_cons r h₁, have h₂₀ : ∀ c ∈ l', b ≼ c, from forall_mem_rel_of_sorted_cons r h₂, if h : a ≼ b then begin note hrec := f (l, b :: l') begin simp without add_comm, apply nat.le_refl end, simp [if_pos, h], have h₃ : sorted r (merge r (l, b :: l')), from hrec ‹sorted r l› h₂, have h₄ : ∀ c ∈ merge r (l, b :: l'), a ≼ c, begin intros c hc, rw mem_merge_iff at hc, exact or.elim hc (suppose c ∈ l, show a ≼ c, from h₁₀ c this) (suppose c ∈ b :: l', or.elim (eq_or_mem_of_mem_cons this) (suppose c = b, show a ≼ c, from this^.symm ▸ ‹a ≼ b›) (suppose c ∈ l', show a ≼ c, from transr ‹a ≼ b› (h₂₀ c this))) end, show sorted r (a :: merge r (l, b :: l')), from sorted_cons r h₃ h₄ end else have h' : b ≼ a, from or.resolve_left (totr a b) h, begin note hrec := f (a :: l, l') begin apply nat.le_refl end, simp [if_neg, h], have h₃ : sorted r (merge r (a :: l, l')), from hrec h₁ ‹sorted r l'›, have h₄ : ∀ c ∈ merge r (a :: l, l'), b ≼ c, begin intros c hc, rw mem_merge_iff at hc, exact or.elim hc (suppose c ∈ a :: l, or.elim (eq_or_mem_of_mem_cons this) (suppose c = a, show b ≼ c, from this^.symm ▸ ‹b ≼ a›) (suppose c ∈ l, show b ≼ c, from transr ‹b ≼ a› (h₁₀ c this))) (suppose c ∈ l', show b ≼ c, from h₂₀ c this) end, show sorted r (b :: merge r (a :: l, l')), from sorted_cons r h₃ h₄ end theorem sorted_merge : Π {p : list α × list α}, sorted r p.1 → sorted r p.2 → sorted r (merge p) := well_founded.fix (inv_image.wf _ nat.lt_wf) (sorted_merge.F totr transr) private def sorted_merge_sort.F : Π l : list α, (Π l₁ : list α, length l₁ < length l → sorted r (merge_sort l₁)) → sorted r (merge_sort l) | [] f := by simp; exact sorted_nil r | [a] f := by simp; exact sorted_singleton r a | (a :: b :: l) f := begin simp, apply sorted_merge r totr transr, -- this should be handled by the simplifier, i.e. cancel out +1 and rewrite _ < _ + 1 to _ <= _ { apply f, show length (split l)^.fst + (1 + 0) < length l + (1 + 1), from add_lt_add_of_le_of_lt (length_split_fst_le l) (add_lt_add_of_le_of_lt (le_refl 1) zero_lt_one) }, { apply f, show length (split l)^.snd + (1 + 0) < length l + (1 + 1), from add_lt_add_of_le_of_lt (length_split_snd_le l) (add_lt_add_of_le_of_lt (le_refl 1) zero_lt_one) } end theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l) := well_founded.fix (inv_image.wf _ nat.lt_wf) (sorted_merge_sort.F totr transr) end total_and_transitive end correctness end merge_sort end sort /- try them out! -/ --vm_eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] --vm_eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] end list
d0cf8f1d3145eecc35e0d126ad073fe9d7ff2cba
690889011852559ee5ac4dfea77092de8c832e7e
/src/algebra/floor.lean
478f9c7bab1e7103d55f73a9ccd4cf3dedd5afd3
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
9,680
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Kappelmann -/ import data.int.basic import tactic.linarith tactic.abel /-! # Floor and Ceil ## Summary We define `floor`, `ceil`, and `nat_ceil` functions on linear ordered rings. ## Main Definitions - `floor_ring` is a linear ordered ring with floor function. - `floor x` is the greatest integer `z` such that `z ≤ x`. - `fract x` is the fractional part of x, that is `x - floor x`. - `ceil x` is the smallest integer `z` such that `x ≤ z`. - `nat_ceil x` is the smallest nonnegative integer `n` with `x ≤ n`. ## Notations - `⌊x⌋` is `floor x`. - `⌈x⌉` is `ceil x`. ## Tags rounding -/ variables {α : Type*} /- A `floor_ring` is a linear ordered ring over `α` with a function `floor : α → ℤ` satisfying `∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x)`. -/ class floor_ring (α) [linear_ordered_ring α] := (floor : α → ℤ) (le_floor : ∀ (z : ℤ) (x : α), z ≤ floor x ↔ (z : α) ≤ x) instance : floor_ring ℤ := { floor := id, le_floor := λ _ _, by rw int.cast_id; refl } variables [linear_ordered_ring α] [floor_ring α] /-- `floor x` is the greatest integer `z` such that `z ≤ x` -/ def floor : α → ℤ := floor_ring.floor notation `⌊` x `⌋` := floor x theorem le_floor : ∀ {z : ℤ} {x : α}, z ≤ ⌊x⌋ ↔ (z : α) ≤ x := floor_ring.le_floor theorem floor_lt {x : α} {z : ℤ} : ⌊x⌋ < z ↔ x < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (x : α) : (⌊x⌋ : α) ≤ x := le_floor.1 (le_refl _) theorem floor_nonneg {x : α} : 0 ≤ ⌊x⌋ ↔ 0 ≤ x := by rw [le_floor]; refl theorem lt_succ_floor (x : α) : x < ⌊x⌋.succ := floor_lt.1 $ int.lt_succ_self _ theorem lt_floor_add_one (x : α) : x < ⌊x⌋ + 1 := by simpa only [int.succ, int.cast_add, int.cast_one] using lt_succ_floor x theorem sub_one_lt_floor (x : α) : x - 1 < ⌊x⌋ := sub_lt_iff_lt_add.2 (lt_floor_add_one x) @[simp] theorem floor_coe (z : ℤ) : ⌊(z:α)⌋ = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] @[simp] theorem floor_zero : ⌊(0:α)⌋ = 0 := floor_coe 0 @[simp] theorem floor_one : ⌊(1:α)⌋ = 1 := by rw [← int.cast_one, floor_coe] theorem floor_mono {a b : α} (h : a ≤ b) : ⌊a⌋ ≤ ⌊b⌋ := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (x : α) (z : ℤ) : ⌊x + z⌋ = ⌊x⌋ + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (x : α) (z : ℤ) : ⌊x - z⌋ = ⌊x⌋ - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) lemma abs_sub_lt_one_of_floor_eq_floor {α : Type*} [decidable_linear_ordered_comm_ring α] [floor_ring α] {x y : α} (h : ⌊x⌋ = ⌊y⌋) : abs (x - y) < 1 := begin have : x < ⌊x⌋ + 1 := lt_floor_add_one x, have : y < ⌊y⌋ + 1 := lt_floor_add_one y, have : (⌊x⌋ : α) = ⌊y⌋ := int.cast_inj.2 h, have : (⌊x⌋: α) ≤ x := floor_le x, have : (⌊y⌋ : α) ≤ y := floor_le y, exact abs_sub_lt_iff.2 ⟨by linarith, by linarith⟩ end lemma floor_eq_iff {r : α} {z : ℤ} : ⌊r⌋ = z ↔ ↑z ≤ r ∧ r < (z + 1) := by rw [←le_floor, ←int.cast_one, ←int.cast_add, ←floor_lt, int.lt_add_one_iff, le_antisymm_iff, and.comm] lemma floor_ring_unique {α} [linear_ordered_ring α] (inst1 inst2 : floor_ring α) : @floor _ _ inst1 = @floor _ _ inst2 := begin ext v, suffices : (⌊v⌋ : α) ≤ v ∧ v < ⌊v⌋ + 1, by rwa [floor_eq_iff], exact ⟨floor_le v, lt_floor_add_one v⟩ end /-- The fractional part fract r of r is just r - ⌊r⌋ -/ def fract (r : α) : α := r - ⌊r⌋ -- Mathematical notation is usually {r}. Let's not even go there. @[simp] lemma floor_add_fract (r : α) : (⌊r⌋ : α) + fract r = r := by unfold fract; simp @[simp] lemma fract_add_floor (r : α) : fract r + ⌊r⌋ = r := sub_add_cancel _ _ theorem fract_nonneg (r : α) : 0 ≤ fract r := sub_nonneg.2 $ floor_le _ theorem fract_lt_one (r : α) : fract r < 1 := sub_lt.1 $ sub_one_lt_floor _ @[simp] lemma fract_zero : fract (0 : α) = 0 := by unfold fract; simp @[simp] lemma fract_coe (z : ℤ) : fract (z : α) = 0 := by unfold fract; rw floor_coe; exact sub_self _ @[simp] lemma fract_floor (r : α) : fract (⌊r⌋ : α) = 0 := fract_coe _ @[simp] lemma floor_fract (r : α) : ⌊fract r⌋ = 0 := by rw floor_eq_iff; exact ⟨fract_nonneg _, by rw [int.cast_zero, zero_add]; exact fract_lt_one r⟩ theorem fract_eq_iff {r s : α} : fract r = s ↔ 0 ≤ s ∧ s < 1 ∧ ∃ z : ℤ, r - s = z := ⟨λ h, by rw ←h; exact ⟨fract_nonneg _, fract_lt_one _, ⟨⌊r⌋, sub_sub_cancel _ _⟩⟩, begin intro h, show r - ⌊r⌋ = s, apply eq.symm, rw [eq_sub_iff_add_eq, add_comm, ←eq_sub_iff_add_eq], rcases h with ⟨hge, hlt, ⟨z, hz⟩⟩, rw [hz, int.cast_inj, floor_eq_iff, ←hz], clear hz, split; linarith {discharger := `[simp]} end⟩ theorem fract_eq_fract {r s : α} : fract r = fract s ↔ ∃ z : ℤ, r - s = z := ⟨λ h, ⟨⌊r⌋ - ⌊s⌋, begin unfold fract at h, rw [int.cast_sub, sub_eq_sub_iff_sub_eq_sub.1 h], end⟩, λ h, begin rcases h with ⟨z, hz⟩, rw fract_eq_iff, split, exact fract_nonneg _, split, exact fract_lt_one _, use z + ⌊s⌋, rw [eq_add_of_sub_eq hz, int.cast_add], unfold fract, simp end⟩ @[simp] lemma fract_fract (r : α) : fract (fract r) = fract r := by rw fract_eq_fract; exact ⟨-⌊r⌋, by unfold fract;simp⟩ theorem fract_add (r s : α) : ∃ z : ℤ, fract (r + s) - fract r - fract s = z := ⟨⌊r⌋ + ⌊s⌋ - ⌊r + s⌋, by unfold fract; simp⟩ theorem fract_mul_nat (r : α) (b : ℕ) : ∃ z : ℤ, fract r * b - fract (r * b) = z := begin induction b with c hc, use 0, simp, rcases hc with ⟨z, hz⟩, rw [nat.succ_eq_add_one, nat.cast_add, mul_add, mul_add, nat.cast_one, mul_one, mul_one], rcases fract_add (r * c) r with ⟨y, hy⟩, use z - y, rw [int.cast_sub, ←hz, ←hy], abel end /-- `ceil x` is the smallest integer `z` such that `x ≤ z` -/ def ceil (x : α) : ℤ := -⌊-x⌋ notation `⌈` x `⌉` := ceil x theorem ceil_le {z : ℤ} {x : α} : ⌈x⌉ ≤ z ↔ x ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem lt_ceil {x : α} {z : ℤ} : z < ⌈x⌉ ↔ (z:α) < x := lt_iff_lt_of_le_iff_le ceil_le theorem ceil_le_floor_add_one (x : α) : ⌈x⌉ ≤ ⌊x⌋ + 1 := by rw [ceil_le, int.cast_add, int.cast_one]; exact le_of_lt (lt_floor_add_one x) theorem le_ceil (x : α) : x ≤ ⌈x⌉ := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ⌈(z:α)⌉ = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : α} (h : a ≤ b) : ⌈a⌉ ≤ ⌈b⌉ := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (x : α) (z : ℤ) : ⌈x + z⌉ = ⌈x⌉ + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (x : α) (z : ℤ) : ⌈x - z⌉ = ⌈x⌉ - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) theorem ceil_lt_add_one (x : α) : (⌈x⌉ : α) < x + 1 := by rw [← lt_ceil, ← int.cast_one, ceil_add_int]; apply lt_add_one lemma ceil_pos {a : α} : 0 < ⌈a⌉ ↔ 0 < a := ⟨ λ h, have ⌊-a⌋ < 0, from neg_of_neg_pos h, pos_of_neg_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).1 $ not_le_of_gt this, λ h, have -a < 0, from neg_neg_of_pos h, neg_pos_of_neg $ lt_of_not_ge $ (not_iff_not_of_iff floor_nonneg).2 $ not_le_of_gt this ⟩ @[simp] theorem ceil_zero : ⌈(0 : α)⌉ = 0 := by simp [ceil] lemma ceil_nonneg [decidable_rel ((<) : α → α → Prop)] {q : α} (hq : 0 ≤ q) : 0 ≤ ⌈q⌉ := if h : q > 0 then le_of_lt $ ceil_pos.2 h else by rw [le_antisymm (le_of_not_lt h) hq, ceil_zero]; trivial /-- `nat_ceil x` is the smallest nonnegative integer `n` with `x ≤ n`. It is the same as `⌈q⌉` when `q ≥ 0`, otherwise it is `0`. -/ def nat_ceil (a : α) : ℕ := int.to_nat (⌈a⌉) theorem nat_ceil_le {a : α} {n : ℕ} : nat_ceil a ≤ n ↔ a ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil {a : α} {n : ℕ} [decidable ((n : α) < a)] : n < nat_ceil a ↔ (n : α) < a := not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le] theorem le_nat_ceil (a : α) : a ≤ nat_ceil a := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {a₁ a₂ : α} (h : a₁ ≤ a₂) : nat_ceil a₁ ≤ nat_ceil a₂ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil (n : α) = n := show (⌈((n : ℤ) : α)⌉).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : nat_ceil (0 : α) = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {a : α} (a_nonneg : 0 ≤ a) (n : ℕ) : nat_ceil (a + n) = nat_ceil a + n := begin change int.to_nat (⌈a + (n:ℤ)⌉) = int.to_nat ⌈a⌉ + n, rw [ceil_add_int], have : 0 ≤ ⌈a⌉, by simpa using (ceil_mono a_nonneg), obtain ⟨_, ceil_a_eq⟩ : ∃ (n : ℕ), ⌈a⌉ = n, from int.eq_coe_of_zero_le this, rw ceil_a_eq, refl end theorem nat_ceil_lt_add_one {a : α} (a_nonneg : 0 ≤ a) [decidable ((nat_ceil a : α) < a + 1)] : (nat_ceil a : α) < a + 1 := lt_nat_ceil.1 $ by rw ( show nat_ceil (a + 1) = nat_ceil a + 1, by exact_mod_cast (nat_ceil_add_nat a_nonneg 1)); apply nat.lt_succ_self lemma lt_of_nat_ceil_lt {x : α} {n : ℕ} (h : nat_ceil x < n) : x < n := lt_of_le_of_lt (le_nat_ceil x) (by exact_mod_cast h)
b1d5ddff4f8816079809da582726e2c2da7ee881
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/sup_indep.lean
a91dab0d8ad134996960c4b7a3284dd29a1a9112
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
14,481
lean
/- Copyright (c) 2021 Aaron Anderson, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Kevin Buzzard, Yaël Dillies, Eric Wieser -/ import data.finset.pairwise import data.finset.powerset import data.fintype.basic /-! # Supremum independence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define supremum independence of indexed sets. An indexed family `f : ι → α` is sup-independent if, for all `a`, `f a` and the supremum of the rest are disjoint. ## Main definitions * `finset.sup_indep s f`: a family of elements `f` are supremum independent on the finite set `s`. * `complete_lattice.set_independent s`: a set of elements are supremum independent. * `complete_lattice.independent f`: a family of elements are supremum independent. ## Main statements * In a distributive lattice, supremum independence is equivalent to pairwise disjointness: * `finset.sup_indep_iff_pairwise_disjoint` * `complete_lattice.set_independent_iff_pairwise_disjoint` * `complete_lattice.independent_iff_pairwise_disjoint` * Otherwise, supremum independence is stronger than pairwise disjointness: * `finset.sup_indep.pairwise_disjoint` * `complete_lattice.set_independent.pairwise_disjoint` * `complete_lattice.independent.pairwise_disjoint` ## Implementation notes For the finite version, we avoid the "obvious" definition `∀ i ∈ s, disjoint (f i) ((s.erase i).sup f)` because `erase` would require decidable equality on `ι`. -/ variables {α β ι ι' : Type*} /-! ### On lattices with a bottom element, via `finset.sup` -/ namespace finset section lattice variables [lattice α] [order_bot α] /-- Supremum independence of finite sets. We avoid the "obvious" definition using `s.erase i` because `erase` would require decidable equality on `ι`. -/ def sup_indep (s : finset ι) (f : ι → α) : Prop := ∀ ⦃t⦄, t ⊆ s → ∀ ⦃i⦄, i ∈ s → i ∉ t → disjoint (f i) (t.sup f) variables {s t : finset ι} {f : ι → α} {i : ι} instance [decidable_eq ι] [decidable_eq α] : decidable (sup_indep s f) := begin apply @finset.decidable_forall_of_decidable_subsets _ _ _ _, intros t ht, apply @finset.decidable_dforall_finset _ _ _ _, exact λ i hi, @implies.decidable _ _ _ (decidable_of_iff' (_ = ⊥) disjoint_iff), end lemma sup_indep.subset (ht : t.sup_indep f) (h : s ⊆ t) : s.sup_indep f := λ u hu i hi, ht (hu.trans h) (h hi) lemma sup_indep_empty (f : ι → α) : (∅ : finset ι).sup_indep f := λ _ _ a ha, ha.elim lemma sup_indep_singleton (i : ι) (f : ι → α) : ({i} : finset ι).sup_indep f := λ s hs j hji hj, begin rw [eq_empty_of_ssubset_singleton ⟨hs, λ h, hj (h hji)⟩, sup_empty], exact disjoint_bot_right, end lemma sup_indep.pairwise_disjoint (hs : s.sup_indep f) : (s : set ι).pairwise_disjoint f := λ a ha b hb hab, sup_singleton.subst $ hs (singleton_subset_iff.2 hb) ha $ not_mem_singleton.2 hab /-- The RHS looks like the definition of `complete_lattice.independent`. -/ lemma sup_indep_iff_disjoint_erase [decidable_eq ι] : s.sup_indep f ↔ ∀ i ∈ s, disjoint (f i) ((s.erase i).sup f) := ⟨λ hs i hi, hs (erase_subset _ _) hi (not_mem_erase _ _), λ hs t ht i hi hit, (hs i hi).mono_right (sup_mono $ λ j hj, mem_erase.2 ⟨ne_of_mem_of_not_mem hj hit, ht hj⟩)⟩ @[simp] lemma sup_indep_pair [decidable_eq ι] {i j : ι} (hij : i ≠ j) : ({i, j} : finset ι).sup_indep f ↔ disjoint (f i) (f j) := ⟨λ h, h.pairwise_disjoint (by simp) (by simp) hij, λ h, begin rw sup_indep_iff_disjoint_erase, intros k hk, rw [finset.mem_insert, finset.mem_singleton] at hk, obtain rfl | rfl := hk, { convert h using 1, rw [finset.erase_insert, finset.sup_singleton], simpa using hij }, { convert h.symm using 1, have : ({i, k} : finset ι).erase k = {i}, { ext, rw [mem_erase, mem_insert, mem_singleton, mem_singleton, and_or_distrib_left, ne.def, not_and_self, or_false, and_iff_right_of_imp], rintro rfl, exact hij }, rw [this, finset.sup_singleton] } end⟩ lemma sup_indep_univ_bool (f : bool → α) : (finset.univ : finset bool).sup_indep f ↔ disjoint (f ff) (f tt) := begin have : tt ≠ ff := by simp only [ne.def, not_false_iff], exact (sup_indep_pair this).trans disjoint.comm, end @[simp] lemma sup_indep_univ_fin_two (f : fin 2 → α) : (finset.univ : finset (fin 2)).sup_indep f ↔ disjoint (f 0) (f 1) := begin have : (0 : fin 2) ≠ 1 := by simp, exact sup_indep_pair this, end lemma sup_indep.attach (hs : s.sup_indep f) : s.attach.sup_indep (f ∘ subtype.val) := begin intros t ht i _ hi, classical, rw ←finset.sup_image, refine hs (image_subset_iff.2 $ λ (j : {x // x ∈ s}) _, j.2) i.2 (λ hi', hi _), rw mem_image at hi', obtain ⟨j, hj, hji⟩ := hi', rwa subtype.ext hji at hj, end end lattice section distrib_lattice variables [distrib_lattice α] [order_bot α] {s : finset ι} {f : ι → α} lemma sup_indep_iff_pairwise_disjoint : s.sup_indep f ↔ (s : set ι).pairwise_disjoint f := ⟨sup_indep.pairwise_disjoint, λ hs t ht i hi hit, finset.disjoint_sup_right.2 $ λ j hj, hs hi (ht hj) (ne_of_mem_of_not_mem hj hit).symm⟩ alias sup_indep_iff_pairwise_disjoint ↔ sup_indep.pairwise_disjoint _root_.set.pairwise_disjoint.sup_indep /-- Bind operation for `sup_indep`. -/ lemma sup_indep.sup [decidable_eq ι] {s : finset ι'} {g : ι' → finset ι} {f : ι → α} (hs : s.sup_indep (λ i, (g i).sup f)) (hg : ∀ i' ∈ s, (g i').sup_indep f) : (s.sup g).sup_indep f := begin simp_rw sup_indep_iff_pairwise_disjoint at ⊢ hs hg, rw [sup_eq_bUnion, coe_bUnion], exact hs.bUnion_finset hg, end /-- Bind operation for `sup_indep`. -/ lemma sup_indep.bUnion [decidable_eq ι] {s : finset ι'} {g : ι' → finset ι} {f : ι → α} (hs : s.sup_indep (λ i, (g i).sup f)) (hg : ∀ i' ∈ s, (g i').sup_indep f) : (s.bUnion g).sup_indep f := by { rw ←sup_eq_bUnion, exact hs.sup hg } end distrib_lattice end finset /-! ### On complete lattices via `has_Sup.Sup` -/ namespace complete_lattice variables [complete_lattice α] open set function /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : set_independent s) @[simp] lemma set_independent_empty : set_independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem set_independent.mono {t : set α} (hst : t ⊆ s) : set_independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma set_independent.pairwise_disjoint : s.pairwise_disjoint id := λ x hx y hy h, disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, h.symm⟩) lemma set_independent_pair {a b : α} (hab : a ≠ b) : set_independent ({a, b} : set α) ↔ disjoint a b := begin split, { intro h, exact h.pairwise_disjoint (mem_insert _ _) (mem_insert_of_mem _ (mem_singleton _)) hab, }, { rintros h c ((rfl : c = a) | (rfl : c = b)), { convert h using 1, simp [hab, Sup_singleton] }, { convert h.symm using 1, simp [hab, Sup_singleton] }, }, end include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end omit hs /-- An independent indexed family of elements in a complete lattice is one in which every element is disjoint from the `supr` of the rest. Example: an indexed family of non-zero elements in a vector space is linearly independent iff the indexed family of subspaces they generate is independent in this sense. Example: an indexed family of submodules of a module is independent in this sense if and only the natural map from the direct sum of the submodules to the module is injective. -/ def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop := ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) : set_independent s ↔ independent (coe : s → α) := begin simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr], refine forall₂_congr (λ a ha, _), congr' 2, convert supr_subtype.symm, simp [supr_and], end variables {t : ι → α} (ht : independent t) theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) := iff.rfl theorem independent_def' : independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) := by {simp_rw Sup_image, refl} theorem independent_def'' : independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) := by {rw independent_def', tidy} @[simp] lemma independent_empty (t : empty → α) : independent t. @[simp] lemma independent_pempty (t : pempty → α) : independent t. /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.pairwise_disjoint : pairwise (disjoint on t) := λ x y h, disjoint_Sup_right (ht x) ⟨y, supr_pos h.symm⟩ lemma independent.mono {s t : ι → α} (hs : independent s) (hst : t ≤ s) : independent t := λ i, (hs i).mono (hst i) $ supr₂_mono $ λ j _, hst j /-- Composing an independent indexed family with an injective function on the index results in another indepedendent indexed family. -/ lemma independent.comp {ι ι' : Sort*} {t : ι → α} {f : ι' → ι} (ht : independent t) (hf : injective f) : independent (t ∘ f) := λ i, (ht (f i)).mono_right $ begin refine (supr_mono $ λ i, _).trans (supr_comp_le _ f), exact supr_const_mono hf.ne, end lemma independent.comp' {ι ι' : Sort*} {t : ι → α} {f : ι' → ι} (ht : independent $ t ∘ f) (hf : surjective f) : independent t := begin intros i, obtain ⟨i', rfl⟩ := hf i, rw ← hf.supr_comp, exact (ht i').mono_right (bsupr_mono $ λ j' hij, mt (congr_arg f) hij), end lemma independent.set_independent_range (ht : independent t) : set_independent $ range t := begin rw set_independent_iff, rw ← coe_comp_range_factorization t at ht, exact ht.comp' surjective_onto_range, end lemma independent.injective (ht : independent t) (h_ne_bot : ∀ i, t i ≠ ⊥) : injective t := begin intros i j h, by_contra' contra, apply h_ne_bot j, suffices : t j ≤ ⨆ k (hk : k ≠ i), t k, { replace ht := (ht i).mono_right this, rwa [h, disjoint_self] at ht, }, replace contra : j ≠ i, { exact ne.symm contra, }, exact le_supr₂ j contra, end lemma independent_pair {i j : ι} (hij : i ≠ j) (huniv : ∀ k, k = i ∨ k = j): independent t ↔ disjoint (t i) (t j) := begin split, { exact λ h, h.pairwise_disjoint hij }, { rintros h k, obtain rfl | rfl := huniv k, { refine h.mono_right (supr_le $ λ i, supr_le $ λ hi, eq.le _), rw (huniv i).resolve_left hi }, { refine h.symm.mono_right (supr_le $ λ j, supr_le $ λ hj, eq.le _), rw (huniv j).resolve_right hj } }, end /-- Composing an indepedent indexed family with an order isomorphism on the elements results in another indepedendent indexed family. -/ lemma independent.map_order_iso {ι : Sort*} {α β : Type*} [complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} (ha : independent a) : independent (f ∘ a) := λ i, ((ha i).map_order_iso f).mono_right (f.monotone.le_map_supr₂ _) @[simp] lemma independent_map_order_iso_iff {ι : Sort*} {α β : Type*} [complete_lattice α] [complete_lattice β] (f : α ≃o β) {a : ι → α} : independent (f ∘ a) ↔ independent a := ⟨ λ h, have hf : f.symm ∘ f ∘ a = a := congr_arg (∘ a) f.left_inv.comp_eq_id, hf ▸ h.map_order_iso f.symm, λ h, h.map_order_iso f⟩ /-- If the elements of a set are independent, then any element is disjoint from the `supr` of some subset of the rest. -/ lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α] {t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) : disjoint (t x) (⨆ i ∈ y, t i) := disjoint.mono_right (bsupr_mono $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x) end complete_lattice lemma complete_lattice.independent_iff_sup_indep [complete_lattice α] {s : finset ι} {f : ι → α} : complete_lattice.independent (f ∘ (coe : s → ι)) ↔ s.sup_indep f := begin classical, rw finset.sup_indep_iff_disjoint_erase, refine subtype.forall.trans (forall₂_congr $ λ a b, _), rw finset.sup_eq_supr, congr' 2, refine supr_subtype.trans _, congr' 1 with x, simp [supr_and, @supr_comm _ (x ∈ s)], end alias complete_lattice.independent_iff_sup_indep ↔ complete_lattice.independent.sup_indep finset.sup_indep.independent /-- A variant of `complete_lattice.independent_iff_sup_indep` for `fintype`s. -/ lemma complete_lattice.independent_iff_sup_indep_univ [complete_lattice α] [fintype ι] {f : ι → α} : complete_lattice.independent f ↔ finset.univ.sup_indep f := begin classical, simp [finset.sup_indep_iff_disjoint_erase, complete_lattice.independent, finset.sup_eq_supr], end alias complete_lattice.independent_iff_sup_indep_univ ↔ complete_lattice.independent.sup_indep_univ finset.sup_indep.independent_of_univ section frame namespace complete_lattice variables [order.frame α] lemma set_independent_iff_pairwise_disjoint {s : set α} : set_independent s ↔ s.pairwise_disjoint id := ⟨set_independent.pairwise_disjoint, λ hs i hi, disjoint_Sup_iff.2 $ λ j hj, hs hi hj.1 $ ne.symm hj.2⟩ alias set_independent_iff_pairwise_disjoint ↔ _ _root_.set.pairwise_disjoint.set_independent lemma independent_iff_pairwise_disjoint {f : ι → α} : independent f ↔ pairwise (disjoint on f) := ⟨independent.pairwise_disjoint, λ hs i, disjoint_supr_iff.2 $ λ j, disjoint_supr_iff.2 $ λ hij, hs hij.symm⟩ end complete_lattice end frame
bf7d00b6a22983689cf28165e56176fc3457b713
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/locally_constant/algebra.lean
158d2fc65bc0d6566b60f3c76aaa7c85c7190bc5
[ "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
9,488
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.algebra.basic import topology.locally_constant.basic /-! # Algebraic structure on locally constant functions This file puts algebraic structure (`add_group`, etc) on the type of locally constant functions. -/ namespace locally_constant variables {X Y : Type*} [topological_space X] @[to_additive] instance [has_one Y] : has_one (locally_constant X Y) := { one := const X 1 } @[simp, to_additive] lemma coe_one [has_one Y] : ⇑(1 : locally_constant X Y) = (1 : X → Y) := rfl @[to_additive] lemma one_apply [has_one Y] (x : X) : (1 : locally_constant X Y) x = 1 := rfl @[to_additive] instance [has_inv Y] : has_inv (locally_constant X Y) := { inv := λ f, ⟨f⁻¹ , f.is_locally_constant.inv⟩ } @[simp, to_additive] lemma coe_inv [has_inv Y] (f : locally_constant X Y) : ⇑(f⁻¹) = f⁻¹ := rfl @[to_additive] lemma inv_apply [has_inv Y] (f : locally_constant X Y) (x : X) : f⁻¹ x = (f x)⁻¹ := rfl @[to_additive] instance [has_mul Y] : has_mul (locally_constant X Y) := { mul := λ f g, ⟨f * g, f.is_locally_constant.mul g.is_locally_constant⟩ } @[simp, to_additive] lemma coe_mul [has_mul Y] (f g : locally_constant X Y) : ⇑(f * g) = f * g := rfl @[to_additive] lemma mul_apply [has_mul Y] (f g : locally_constant X Y) (x : X) : (f * g) x = f x * g x := rfl @[to_additive] instance [mul_one_class Y] : mul_one_class (locally_constant X Y) := { one_mul := by { intros, ext, simp only [mul_apply, one_apply, one_mul] }, mul_one := by { intros, ext, simp only [mul_apply, one_apply, mul_one] }, .. locally_constant.has_one, .. locally_constant.has_mul } /-- `coe_fn` is a `monoid_hom`. -/ @[to_additive "`coe_fn` is an `add_monoid_hom`.", simps] def coe_fn_monoid_hom [mul_one_class Y] : locally_constant X Y →* (X → Y) := { to_fun := coe_fn, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The constant-function embedding, as a multiplicative monoid hom. -/ @[to_additive "The constant-function embedding, as an additive monoid hom.", simps] def const_monoid_hom [mul_one_class Y] : Y →* locally_constant X Y := { to_fun := const X, map_one' := rfl, map_mul' := λ _ _, rfl, } instance [mul_zero_class Y] : mul_zero_class (locally_constant X Y) := { zero_mul := by { intros, ext, simp only [mul_apply, zero_apply, zero_mul] }, mul_zero := by { intros, ext, simp only [mul_apply, zero_apply, mul_zero] }, .. locally_constant.has_zero, .. locally_constant.has_mul } instance [mul_zero_one_class Y] : mul_zero_one_class (locally_constant X Y) := { .. locally_constant.mul_zero_class, .. locally_constant.mul_one_class } section char_fn variables (Y) [mul_zero_one_class Y] {U V : set X} /-- Characteristic functions are locally constant functions taking `x : X` to `1` if `x ∈ U`, where `U` is a clopen set, and `0` otherwise. -/ noncomputable def char_fn (hU : is_clopen U) : locally_constant X Y := indicator 1 hU lemma coe_char_fn (hU : is_clopen U) : (char_fn Y hU : X → Y) = set.indicator U 1 := rfl lemma char_fn_eq_one [nontrivial Y] (x : X) (hU : is_clopen U) : char_fn Y hU x = (1 : Y) ↔ x ∈ U := set.indicator_eq_one_iff_mem _ lemma char_fn_eq_zero [nontrivial Y] (x : X) (hU : is_clopen U) : char_fn Y hU x = (0 : Y) ↔ x ∉ U := set.indicator_eq_zero_iff_not_mem _ lemma char_fn_inj [nontrivial Y] (hU : is_clopen U) (hV : is_clopen V) (h : char_fn Y hU = char_fn Y hV) : U = V := set.indicator_one_inj Y $ coe_inj.mpr h end char_fn @[to_additive] instance [has_div Y] : has_div (locally_constant X Y) := { div := λ f g, ⟨f / g, f.is_locally_constant.div g.is_locally_constant⟩ } @[to_additive] lemma coe_div [has_div Y] (f g : locally_constant X Y) : ⇑(f / g) = f / g := rfl @[to_additive] lemma div_apply [has_div Y] (f g : locally_constant X Y) (x : X) : (f / g) x = f x / g x := rfl @[to_additive] instance [semigroup Y] : semigroup (locally_constant X Y) := { mul_assoc := by { intros, ext, simp only [mul_apply, mul_assoc] }, .. locally_constant.has_mul } instance [semigroup_with_zero Y] : semigroup_with_zero (locally_constant X Y) := { .. locally_constant.mul_zero_class, .. locally_constant.semigroup } @[to_additive] instance [comm_semigroup Y] : comm_semigroup (locally_constant X Y) := { mul_comm := by { intros, ext, simp only [mul_apply, mul_comm] }, .. locally_constant.semigroup } @[to_additive] instance [monoid Y] : monoid (locally_constant X Y) := { mul := (*), .. locally_constant.semigroup, .. locally_constant.mul_one_class } instance [add_monoid_with_one Y] : add_monoid_with_one (locally_constant X Y) := { nat_cast := λ n, const X n, nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ _, by ext; simp [nat.cast], .. locally_constant.add_monoid, .. locally_constant.has_one } @[to_additive] instance [comm_monoid Y] : comm_monoid (locally_constant X Y) := { .. locally_constant.comm_semigroup, .. locally_constant.monoid } @[to_additive] instance [group Y] : group (locally_constant X Y) := { mul_left_inv := by { intros, ext, simp only [mul_apply, inv_apply, one_apply, mul_left_inv] }, div_eq_mul_inv := by { intros, ext, simp only [mul_apply, inv_apply, div_apply, div_eq_mul_inv] }, .. locally_constant.monoid, .. locally_constant.has_inv, .. locally_constant.has_div } @[to_additive] instance [comm_group Y] : comm_group (locally_constant X Y) := { .. locally_constant.comm_monoid, .. locally_constant.group } instance [distrib Y] : distrib (locally_constant X Y) := { left_distrib := by { intros, ext, simp only [mul_apply, add_apply, mul_add] }, right_distrib := by { intros, ext, simp only [mul_apply, add_apply, add_mul] }, .. locally_constant.has_add, .. locally_constant.has_mul } instance [non_unital_non_assoc_semiring Y] : non_unital_non_assoc_semiring (locally_constant X Y) := { .. locally_constant.add_comm_monoid, .. locally_constant.has_mul, .. locally_constant.distrib, .. locally_constant.mul_zero_class } instance [non_unital_semiring Y] : non_unital_semiring (locally_constant X Y) := { .. locally_constant.semigroup, .. locally_constant.non_unital_non_assoc_semiring } instance [non_assoc_semiring Y] : non_assoc_semiring (locally_constant X Y) := { .. locally_constant.mul_one_class, .. locally_constant.add_monoid_with_one, .. locally_constant.non_unital_non_assoc_semiring } /-- The constant-function embedding, as a ring hom. -/ @[simps] def const_ring_hom [non_assoc_semiring Y] : Y →+* locally_constant X Y := { to_fun := const X, .. const_monoid_hom, .. const_add_monoid_hom, } instance [semiring Y] : semiring (locally_constant X Y) := { .. locally_constant.non_assoc_semiring, .. locally_constant.monoid } instance [non_unital_comm_semiring Y] : non_unital_comm_semiring (locally_constant X Y) := { .. locally_constant.non_unital_semiring, .. locally_constant.comm_semigroup } instance [comm_semiring Y] : comm_semiring (locally_constant X Y) := { .. locally_constant.semiring, .. locally_constant.comm_monoid } instance [non_unital_non_assoc_ring Y] : non_unital_non_assoc_ring (locally_constant X Y) := { .. locally_constant.add_comm_group, .. locally_constant.has_mul, .. locally_constant.distrib, .. locally_constant.mul_zero_class } instance [non_unital_ring Y] : non_unital_ring (locally_constant X Y) := { .. locally_constant.semigroup, .. locally_constant.non_unital_non_assoc_ring } instance [non_assoc_ring Y] : non_assoc_ring (locally_constant X Y) := { .. locally_constant.mul_one_class, .. locally_constant.non_unital_non_assoc_ring } instance [ring Y] : ring (locally_constant X Y) := { .. locally_constant.semiring, .. locally_constant.add_comm_group } instance [non_unital_comm_ring Y] : non_unital_comm_ring (locally_constant X Y) := { .. locally_constant.non_unital_comm_semiring, .. locally_constant.non_unital_ring } instance [comm_ring Y] : comm_ring (locally_constant X Y) := { .. locally_constant.comm_semiring, .. locally_constant.ring } variables {R : Type*} instance [has_smul R Y] : has_smul R (locally_constant X Y) := { smul := λ r f, { to_fun := r • f, is_locally_constant := ((is_locally_constant f).comp ((•) r) : _), } } @[simp] lemma coe_smul [has_smul R Y] (r : R) (f : locally_constant X Y) : ⇑(r • f) = r • f := rfl lemma smul_apply [has_smul R Y] (r : R) (f : locally_constant X Y) (x : X) : (r • f) x = r • (f x) := rfl instance [monoid R] [mul_action R Y] : mul_action R (locally_constant X Y) := function.injective.mul_action _ coe_injective (λ _ _, rfl) instance [monoid R] [add_monoid Y] [distrib_mul_action R Y] : distrib_mul_action R (locally_constant X Y) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective (λ _ _, rfl) instance [semiring R] [add_comm_monoid Y] [module R Y] : module R (locally_constant X Y) := function.injective.module R coe_fn_add_monoid_hom coe_injective (λ _ _, rfl) section algebra variables [comm_semiring R] [semiring Y] [algebra R Y] instance : algebra R (locally_constant X Y) := { to_ring_hom := const_ring_hom.comp $ algebra_map R Y, commutes' := by { intros, ext, exact algebra.commutes' _ _, }, smul_def' := by { intros, ext, exact algebra.smul_def' _ _, }, } @[simp] lemma coe_algebra_map (r : R) : ⇑(algebra_map R (locally_constant X Y) r) = algebra_map R (X → Y) r := rfl end algebra end locally_constant
0d9af81c89269f0f9a68475675039af30adeac4c
076f5040b63237c6dd928c6401329ed5adcb0e44
/assignments/hw2_a_few_easy_pieces.lean
48fafff0906a27c516da4a3a8a57397e45e6aaa7
[]
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
4,517
lean
/- UVa CS Discrete Math (Sullivan) Homework #2 -/ /- Note: We distribute homework assignments and even exams as Lean files, as we do now for this assignment. You will answer the questions in one of two ways: by writing an answer in a comment block (such as this one), or by writing mathematical logic (which is what "Lean code" is). For this assignment you will write all your answers as simple comments. -/ /- This assignment has three questions, each with several parts. Be sure to read and answer all parts of all of the questions. Make a copy of this file in your "mywork" directory the read and answer the questions by editing this fie. When you are done, *save it*, then upload it to Collab. That is how you will submit work in this class. Be sure to double check your submission to be sure you uploaded the right file. -/ /- QUESTION #1 (7 Parts, A - G) A. How many functions are there that take one argument of type Boolean (one bit, if you prefer) and that return one value, also of type Boolean? Hint: We discussed this in class. Answer here (inside this comment block): B. How many functions are there that take two arguments of type Boolean and that return one value of type Boolean? Hint: we discussed this in class, too. Answer here: C. How many functions are there that take three bits of input and that return a one bit result? Hint: We discussed this, too. Answer here: D. Give a general formula that you believe to be valid describing the number of functions that take n bits, for any natural number, n, and that return one bit. Use the ^ character to represent exponentiation. Answer: E. How many functions are there that take three bits of input and that return *two* bits as a result? Hint: think about both how many possible combinations of input bits there are. To define a function, you need to specify which two-bit return value is associated with each combination of input values. The number of functions will be the number of ways in which you can assign output values for each combination of input values. Give your answer in a form that involves 3 (inputs) and 2 (output bits). Answer here: F. How many functions are there that take 64 bits of input and return a 64 bit result? Give your answer as an algebraic expression. The number is too big to write it out explicitly. Answer here: G. How many functions are there that take n bits of input and return m bits of output, where n and m are natural numbers? Give an algebraic expression as your answer, involving the variables m and n. Answer here: -/ /- QUESTION #2 (Three parts, A - C) Suppose you are asked to write a program, P(x), taking one argument, x, a "natural number", and that it must satisfy a specification, S(x), that defines a function in a pure functional programming language. A. Using simple English to express your answer, what proposition must be true for P to be accepted as a correct implementation of S. Hint: We discussed this in class. Answer: B. Why is testing alone generally inadequate to prove the correctness of such a program, P? Answer: C. What kind of mathematical "thing" would be needed to show beyond a reasonable doubt that P satisfies S? You can give a one-word answer. Answer: -/ /- QUESTION #3 (Four parts, A - D) Consider a new data type, cool, that has three possible values: true (T), false (F), and don't know (D). And now consider the following conjecture: For any natural number, n, the number of combinations of values of n variables of type cool is 3^n. Give a proof of this conjecture by induction. A. What is the first conjecture you must prove? Hint: substitute a specific value for n into the conjecture and rewrite it with that value in place of n. Answer: B. Prove it. Hint: One approach to proving that two terms are equal is simply to reduce each term to its simplest form, and then show that the reduced terms are exactly the same. In other words, just simplify the expressions on each side of an equals to to show that the values are identical. Answer here: C. What is the second conjecture that you must prove to complete your proof by induction? Answer here: D. Prove it. Hint, to prove a proposition of the form, P → Q, or P implies Q, you start by *assuming* that P is true (whatever proposition it happens to be), and then you show that in the context of this assumption, that proposition Q must be true. In other words, you want to prove that IF P is true THEN Q must be true, too. Answer here: -/
68bb14a8f0ce46d550e0dfb63b1022fb46648003
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/char_p.lean
9b288fdf94de1b9a1f480d4911f67eda9bb3e9ab
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
12,504
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz -/ import data.fintype.basic import data.nat.choose import data.int.modeq import algebra.module.basic import algebra.iterate_hom /-! # Characteristic of semirings -/ universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end lemma char_p.int_coe_eq_int_coe_iff (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = (b : R) ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomputable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x + y)^p = x^p + y^p := begin rw [commute.add_pow h, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one, add_right_inj], convert finset.sum_eq_single 0 _ _, { simp }, swap, { intro h1, contrapose! h1, rw finset.mem_range, apply nat.prime.pos, assumption }, intros b h1 h2, suffices : (p.choose b : R) = 0, { rw this, simp }, rw char_p.cast_eq_zero_iff R p, apply nat.prime.dvd_choose_self, assumption', { omega }, rwa ← finset.mem_range end theorem add_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := begin induction n, { simp, }, rw [nat.pow_succ, pow_mul, pow_mul, pow_mul, n_ih], apply add_pow_char_of_commute, apply commute.pow_pow h, end theorem sub_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x - y)^p = x^p - y^p := begin rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)], simp, repeat {apply_instance}, end theorem sub_pow_char_pow_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := begin induction n, { simp, }, rw [nat.pow_succ, pow_mul, pow_mul, pow_mul, n_ih], apply sub_pow_char_of_commute, apply commute.pow_pow h, end theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact p.prime] [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := add_pow_char_of_commute _ _ _ (commute.all _ _) theorem add_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := add_pow_char_pow_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char (α : Type u) [comm_ring α] {p : ℕ} [fact p.prime] [char_p α p] (x y : α) : (x - y)^p = x^p - y^p := sub_pow_char_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char_pow (R : Type u) [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := sub_pow_char_pow_of_commute _ _ _ (commute.all _ _) lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] lemma char_p.neg_one_ne_one (R : Type*) [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] : (-1 : R) ≠ (1 : R) := begin suffices : (2 : R) ≠ 0, { symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this }, assume h, rw [show (2 : R) = (2 : ℕ), by norm_cast] at h, have := (char_p.cast_eq_zero_iff R p 2).mp h, have := nat.le_of_dvd dec_trivial this, rw fact at *, linarith, end section frobenius variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt), map_add' := add_pow_char R } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n := begin induction n, {simp}, rw [function.iterate_succ', nat.pow_succ, pow_mul, function.comp_apply, frobenius_def, n_ih] end theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ variable {R} theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := function.semiconj.iterate_right (f.map_frobenius p) n x theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end frobenius theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [fact p.prime] [char_p α p] : function.injective (frobenius α p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := add_group.char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p α p] (hp : 2 ≤ p) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_two_le α _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime := (char_p.char_is_prime_or_zero α _).resolve_right (nat.pos_iff_ne_zero.1 h) theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain section char_one variables {R : Type*} section prio set_option default_priority 100 -- see Note [default priority] instance [semiring R] [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul end prio lemma false_of_nonzero_of_char_one [semiring R] [nontrivial R] [char_p R 1] : false := zero_ne_one $ show (0:R) = 1, from subsingleton.elim 0 1 lemma ring_char_ne_one [semiring R] [nontrivial R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } end char_one end char_p
218fa576b637cfe3b723331f00a50dc6bbac3468
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/ring_theory/unique_factorization_domain.lean
c7c86565658bff9a30f700316d227181ad1003bd
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
19,715
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Theory of unique factorization domains. @TODO: setup the complete lattice structure on `factor_set`. -/ import algebra.gcd_domain variables {α : Type*} local infix ` ~ᵤ ` : 50 := associated /-- Unique factorization domains. In a unique factorization domain each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. This is equivalent to defining a unique factorization domain as a domain in which each element (except zero) is non-uniquely represented as a multiset of prime factors. This definition is used. To define a UFD using the traditional definition in terms of multisets of irreducible factors, use the definition `of_unique_irreducible_factorization` -/ class unique_factorization_domain (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (prime_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, prime x) namespace unique_factorization_domain variables [integral_domain α] [unique_factorization_domain α] @[elab_as_eliminator] lemma induction_on_prime {P : α → Prop} (a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x) (h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then ha0.symm ▸ h₁ else @multiset.induction_on _ (λ s : multiset α, ∀ (a : α), a ≠ 0 → s.prod ~ᵤ a → (∀ p ∈ s, prime p) → P a) (factors a) (λ _ _ h _, h₂ _ ((is_unit_iff_of_associated h.symm).2 is_unit_one)) (λ p s ih a ha0 ⟨u, hu⟩ hsp, have ha : a = (p * u) * s.prod, by simp [hu.symm, mul_comm, mul_assoc], have hs0 : s.prod ≠ 0, from λ _ : s.prod = 0, by simp * at *, ha.symm ▸ h₃ _ _ hs0 (prime_of_associated ⟨u, rfl⟩ (hsp p (multiset.mem_cons_self _ _))) (ih _ hs0 (by refl) (λ p hp, hsp p (multiset.mem_cons.2 (or.inr hp))))) _ ha0 (factors_prod ha0) (prime_factors ha0) lemma factors_irreducible {a : α} (ha : irreducible a) : ∃ p, a ~ᵤ p ∧ factors a = p :: 0 := by haveI := classical.dec_eq α; exact multiset.induction_on (factors a) (λ h, (ha.1 (associated_one_iff_is_unit.1 h.symm)).elim) (λ p s _ hp hs, let ⟨u, hu⟩ := hp in ⟨p, have hs0 : s = 0, from classical.by_contradiction (λ hs0, let ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0 in (hs q (by simp [hq])).2.1 $ (ha.2 ((p * u) * (s.erase q).prod) _ (by rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq]; simp [hu.symm, mul_comm, mul_assoc])).resolve_left $ mt is_unit_of_mul_is_unit_left $ mt is_unit_of_mul_is_unit_left (hs p (multiset.mem_cons_self _ _)).2.1), ⟨associated.symm (by clear _let_match; simp * at *), hs0 ▸ rfl⟩⟩) (factors_prod (ne_zero_of_irreducible ha)) (prime_factors (ne_zero_of_irreducible ha)) lemma irreducible_iff_prime {p : α} : irreducible p ↔ prime p := by letI := classical.dec_eq α; exact if hp0 : p = 0 then by simp [hp0] else ⟨λ h, let ⟨q, hq⟩ := factors_irreducible h in have prime q, from hq.2 ▸ prime_factors hp0 _ (by simp [hq.2]), suffices prime (factors p).prod, from prime_of_associated (factors_prod hp0) this, hq.2.symm ▸ by simp [this], irreducible_of_prime⟩ lemma irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x := by simp only [irreducible_iff_prime]; exact @prime_factors _ _ _ lemma unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g := by haveI := classical.dec_eq α; exact λ f, multiset.induction_on f (λ g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (λ x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).1 (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))))) (λ p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (λ q hq, irreducible_iff_prime.1 (hg _ hq)) $ (dvd_iff_dvd_of_rel_right hfg).1 (show p ∣ (p :: f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq])) (λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated_mul_left_cancel (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (ne_zero_of_irreducible (hf p (by simp))))) end) end unique_factorization_domain structure unique_irreducible_factorization (α : Type*) [integral_domain α] := (factors : α → multiset α) (factors_prod : ∀{a : α}, a ≠ 0 → (factors a).prod ~ᵤ a) (irreducible_factors : ∀{a : α}, a ≠ 0 → ∀x∈factors a, irreducible x) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod → multiset.rel associated f g) namespace unique_factorization_domain open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a → ∃ q ∈ factors a, p ~ᵤ q := λ ⟨b, hb⟩, have hb0 : b ≠ 0, from λ hb0, by simp * at *, have multiset.rel associated (p :: factors b) (factors a), from unique (λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_factors hb0 _)) (irreducible_factors ha0) (associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0 ... = p * b : hb ... ~ᵤ multiset.prod (p :: factors b) : by rw multiset.prod_cons; exact associated_mul_mul (associated.refl _) (associated.symm (factors_prod hb0))), multiset.exists_mem_of_rel_of_mem this (by simp) def of_unique_irreducible_factorization {α : Type*} [integral_domain α] (o : unique_irreducible_factorization α) : unique_factorization_domain α := by letI := classical.dec_eq α; exact { prime_factors := λ a h p (hpa : p ∈ o.factors a), have hpi : irreducible p, from o.irreducible_factors h _ hpa, ⟨ne_zero_of_irreducible hpi, hpi.1, λ a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (λ ha0, by simp [ha0]) (λ hb0, by simp [hb0]) else have hx0 : x ≠ 0, from λ hx0, by simp * at *, have ha0 : a ≠ 0, from ne_zero_of_mul_ne_zero_right hab0, have hb0 : b ≠ 0, from ne_zero_of_mul_ne_zero_left hab0, have multiset.rel associated (p :: o.factors x) (o.factors a + o.factors b), from o.unique (λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (o.irreducible_factors hx0 _)) (show ∀ x ∈ o.factors a + o.factors b, irreducible x, from λ x hx, (multiset.mem_add.1 hx).elim (o.irreducible_factors (ne_zero_of_mul_ne_zero_right hab0) _) (o.irreducible_factors (ne_zero_of_mul_ne_zero_left hab0) _)) $ calc multiset.prod (p :: o.factors x) ~ᵤ a * b : by rw [hx, multiset.prod_cons]; exact associated_mul_mul (by refl) (o.factors_prod hx0) ... ~ᵤ (o.factors a).prod * (o.factors b).prod : associated_mul_mul (o.factors_prod ha0).symm (o.factors_prod hb0).symm ... = _ : by rw multiset.prod_add, let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem this (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod ha0)).1 (multiset.dvd_prod hqa)) (λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $ (dvd_iff_dvd_of_rel_right (o.factors_prod hb0)).1 (multiset.dvd_prod hqb))⟩, ..o } end unique_factorization_domain namespace associates open unique_factorization_domain associated lattice variables [integral_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] /-- `factor_set α` representation elements of unique factorization domain as multisets. `multiset α` produced by `factors` are only unique up to associated elements, while the multisets in `factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (α : Type u) [integral_domain α] [unique_factorization_domain α] : Type u := with_top (multiset { a : associates α // irreducible a }) local attribute [instance] associated.setoid theorem unique' {p q : multiset (associates α)} : (∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_domain.unique _ _ _), { exact assume a ha, ((irreducible_mk_iff _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk_iff _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end private theorem forall_map_mk_factors_irreducible (x : α) (hx : x ≠ 0) : ∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a := begin assume a ha, rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩, exact (irreducible_mk_iff c).2 (irreducible_factors hx _ hc) end theorem prod_le_prod_iff_le {p q : multiset (associates α)} (hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) : p.prod ≤ q.prod ↔ p ≤ q := iff.intro begin rintros ⟨⟨c⟩, eq⟩, have : c ≠ 0, from (mt mk_eq_zero_iff_eq_zero.2 $ assume (hc : quot.mk setoid.r c = 0), have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eq ▸ hc.symm ▸ mul_zero _, not_irreducible_zero ((irreducible_mk_iff 0).1 $ hq _ this)), have : associates.mk (factors c).prod = quot.mk setoid.r c, from mk_eq_mk_iff_associated.2 (factors_prod this), refine le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩, { assume x hx, rcases multiset.mem_add.1 hx with h | h, exact hp x h, exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h }, { simp [multiset.prod_add, prod_mk, *] at * } end prod_le_prod @[simp] theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} : (↑a + ↑b : factor_set α) = ↑(a + b) := with_top.coe_add lemma factor_set.sup_add_inf_eq_add : ∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b | none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp | a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp | (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end def factors' (a : α) (ha : a ≠ 0) : multiset { a : associates α // irreducible a } := (factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk_iff _).2 ha⟩) (irreducible_factors $ ha) @[simp] theorem map_subtype_val_factors' {a : α} (ha : a ≠ 0) : (factors' a ha).map subtype.val = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) : factors' a ha = factors' b hb := have multiset.rel associated (factors a) (factors b), from unique (irreducible_factors ha) (irreducible_factors hb) ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), by simpa [(multiset.map_eq_map subtype.val_injective).symm, rel_associated_iff_map_eq_map.symm] def factors (a : associates α) : factor_set α := begin refine (if h : a = 0 then ⊤ else quotient.hrec_on a (λx h, some $ factors' x (mt mk_eq_zero_iff_eq_zero.2 h)) _ h), assume a b hab, apply function.hfunext, { have : a ~ᵤ 0 ↔ b ~ᵤ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp [quotient_mk_eq_mk, mk_eq_zero_iff_eq_zero, (associated_zero_iff_eq_zero _).symm, this] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong _ _ hab) end @[simp] theorem factors_0 : (0 : associates α).factors = ⊤ := dif_pos rfl @[simp] theorem factors_mk (a : α) (h : a ≠ 0) : (associates.mk a).factors = factors' a h := dif_neg (mt mk_eq_zero_iff_eq_zero.1 h) def factor_set.prod : factor_set α → associates α | none := 0 | (some s) := (s.map subtype.val).prod @[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} : (s : factor_set α).prod = (s.map subtype.val).prod := rfl theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s | none := by simp [factor_set.prod]; refl | (some s) := begin unfold factor_set.prod, generalize eq_a : (s.map subtype.val).prod = a, rcases a with ⟨a⟩, rw quot_mk_eq_mk at *, have : (s.map subtype.val).prod ≠ 0, from assume ha, let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in have irreducible (0 : associates α), from eq ▸ ha, not_irreducible_zero ((irreducible_mk_iff _).1 this), have ha : a ≠ 0, by simp [*] at *, suffices : (unique_factorization_domain.factors a).map associates.mk = s.map subtype.val, { rw [factors_mk a ha], apply congr_arg some _, simpa [(multiset.map_eq_map subtype.val_injective).symm] }, refine unique' (forall_map_mk_factors_irreducible _ ha) (assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx) _, rw [prod_mk, eq_a, mk_eq_mk_iff_associated], exact factors_prod ha end theorem factors_prod (a : associates α) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a ≠ 0, have a ≠ 0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b := have a.prod.factors = b.prod.factors, by rw h, by rwa [prod_factors, prod_factors] at this @[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod | none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp | a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod, by rw [factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod | none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _ | a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h @[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors := eq_of_prod_eq_prod $ eq_of_factors_eq_factors $ by rw [prod_add, factors_prod, factors_prod, factors_prod] theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right' bot_le theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b := iff.intro (assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b := iff.intro (assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩ instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩ instance : bounded_lattice (associates α) := { sup := (⊔), inf := (⊓), sup_le := assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order, .. associates.lattice.order_top, .. associates.lattice.order_bot } lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b := show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b, begin refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end end associates section open associates unique_factorization_domain lattice /-- `to_gcd_domain` constructs a GCD domain out of a unique factorization domain over a normalization domain. -/ def unique_factorization_domain.to_gcd_domain (α : Type*) [normalization_domain α] [unique_factorization_domain α] [decidable_eq (associates α)] : gcd_domain α := { gcd := λa b, (associates.mk a ⊓ associates.mk b).out, lcm := λa b, (associates.mk a ⊔ associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp, gcd_mul_lcm := assume a b, show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out = normalize (a * b), by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl, normalize_gcd := assume a b, by convert normalize_out _, .. ‹normalization_domain α› } end
573450f8b23867397ec581e0494c0456f892cc7d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/general_linear_group.lean
f4629219b1ec4c2aeacf65edb6b549f95811ce2e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,317
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 algebra.module.equiv /-! # The general linear group of linear maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The general linear group is defined to be the group of invertible linear maps from `M` to itself. See also `matrix.general_linear_group` ## Main definitions * `linear_map.general_linear_group` -/ variables (R M : Type*) namespace linear_map variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := (M →ₗ[R] M)ˣ namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) (λ _, M → M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := (f.symm : M →ₗ[R] M), val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} @[simp] lemma coe_fn_general_linear_equiv (f : general_linear_group R M) : ⇑(general_linear_equiv R M f) = (f : M → M) := rfl end general_linear_group end linear_map
9a1f74cf69a500d14c931314915d28eef5a1f9ed
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/group_theory/monoid_localization.lean
9c802740499b99e55aa7848c9f7eaf7eef23fd73
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
40,549
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import group_theory.congruence import algebra.associated import algebra.punit_instances /-! # Localizations of commutative monoids Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so we can generalize localizations to commutative monoids. We characterize the localization of a commutative monoid `M` at a submonoid `S` up to isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a monoid homomorphism `f : M →* N` satisfying 3 properties: 1. For all `y ∈ S`, `f y` is a unit; 2. For all `z : N`, there exists `(x, y) : M × S` such that `z * f y = f x`; 3. For all `x, y : M`, `f x = f y` iff there exists `c ∈ S` such that `x * c = y * c`. We also define the quotient of `M × S` by the unique congruence relation (equivalence relation preserving a binary operation) `r` such that for any other congruence relation `s` on `M × S` satisfying '`∀ y ∈ S`, `(1, 1) ∼ (y, y)` under `s`', we have that `(x₁, y₁) ∼ (x₂, y₂)` by `s` whenever `(x₁, y₁) ∼ (x₂, y₂)` by `r`. We show this relation is equivalent to the standard localization relation. This defines the localization as a quotient type, but the majority of subsequent lemmas in the file are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic predicate. Given such a localization map `f : M →* N`, we can define the surjection `monoid_localization.mk` sending `(x, y) : M × S` to `f x * (f y)⁻¹`, and `monoid_localization.lift`, the homomorphism from `N` induced by a homomorphism from `M` which maps elements of `S` to invertible elements of the codomain. Similarly, given commutative monoids `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : M →* P` such that `g(S) ⊆ T` induces a homomorphism of localizations, `monoid_localization.map`, from `N` to `Q`. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. The infimum form of the localization congruence relation is chosen as 'canonical' here, since it shortens some proofs. ## Tags localization, monoid localization, quotient monoid, congruence relation, characteristic predicate, commutative monoid -/ namespace add_submonoid variables {M : Type*} [add_comm_monoid M] (S : add_submonoid M) (N : Type*) [add_comm_monoid N] /-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M →+ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map := (to_fun : M →+ N) (map_add_units : ∀ y : S, is_add_unit (to_fun y)) (surj : ∀ z : N, ∃ x : M × S, z + to_fun x.2 = to_fun x.1) (eq_iff_exists : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x + c = y + c) end add_submonoid variables {M : Type*} [comm_monoid M] (S : submonoid M) (N : Type*) [comm_monoid N] {P : Type*} [comm_monoid P] namespace submonoid /-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M →* N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map := (to_fun : M →* N) (map_units : ∀ y : S, is_unit (to_fun y)) (surj : ∀ z : N, ∃ x : M × S, z * to_fun x.2 = to_fun x.1) (eq_iff_exists : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x * c = y * c) attribute [to_additive add_submonoid.localization_map] submonoid.localization_map namespace localization /-- The congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(1, 1) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`. -/ @[to_additive "The congruence relation on `M × S`, `M` an `add_comm_monoid` and `S` an `add_submonoid` of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(0, 0) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`."] def r (S : submonoid M) : con (M × S) := Inf {c | ∀ y : S, c 1 (y, y)} /-- An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. Its equivalence to `r` can be useful for proofs. -/ @[to_additive "An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. Its equivalence to `r` can be useful for proofs."] def r' : con (M × S) := begin refine { r := λ a b : M × S, ∃ c : S, a.1 * b.2 * c = b.1 * a.2 * c, iseqv := ⟨λ a, ⟨1, rfl⟩, λ a b ⟨c, hc⟩, ⟨c, hc.symm⟩, _⟩, .. }, { rintros a b c ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use b.2 * t₁ * t₂, simp only [submonoid.coe_mul], calc a.1 * c.2 * (b.2 * t₁ * t₂) = a.1 * b.2 * t₁ * c.2 * t₂ : by ac_refl ... = b.1 * c.2 * t₂ * a.2 * t₁ : by { rw ht₁, ac_refl } ... = c.1 * a.2 * (b.2 * t₁ * t₂) : by { rw ht₂, ac_refl } }, { rintros a b c d ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use t₁ * t₂, calc (a.1 * c.1) * (b.2 * d.2) * (t₁ * t₂) = (a.1 * b.2 * t₁) * (c.1 * d.2 * t₂) : by ac_refl ... = (b.1 * d.1) * (a.2 * c.2) * (t₁ * t₂) : by { rw [ht₁, ht₂], ac_refl } } end /-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`). -/ @[to_additive "The additive congruence relation used to localize an `add_comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`)."] theorem r_eq_r' : r S = r' S := le_antisymm (Inf_le $ λ _, ⟨1, by simp⟩) $ le_Inf $ λ b H ⟨p, q⟩ y ⟨t, ht⟩, begin rw [← mul_one (p, q), ← mul_one y], refine b.trans (b.mul (b.refl _) (H (y.2 * t))) _, convert b.symm (b.mul (b.refl y) (H (q * t))) using 1, rw [prod.mk_mul_mk, submonoid.coe_mul, ← mul_assoc, ht, mul_left_comm, mul_assoc], refl end variables {S} @[to_additive] lemma r_iff_exists {x y : M × S} : r S x y ↔ ∃ c : S, x.1 * y.2 * c = y.1 * x.2 * c := by rw r_eq_r' S; refl end localization /-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/ @[to_additive "The localization of an `add_comm_monoid` at one of its submonoids (as a quotient type)."] def localization := (localization.r S).quotient @[to_additive] instance localization.inhabited : inhabited (localization S) := con.quotient.inhabited namespace localization_map variables {S N} @[to_additive, ext] lemma ext {f g : localization_map S N} (h : ∀ x, f.1 x = g.1 x) : f = g := by cases f; cases g; simp only []; exact monoid_hom.ext h attribute [ext] add_submonoid.localization_map.ext @[to_additive] lemma ext_iff {f g : localization_map S N} : f = g ↔ ∀ x, f.1 x = g.1 x := ⟨λ h x, h ▸ rfl, ext⟩ @[to_additive] lemma to_fun_inj {f g : localization_map S N} (h : f.1 = g.1) : f = g := ext $ monoid_hom.ext_iff.1 h variables (S) /-- Given a map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z` if there always exists such an element. -/ @[to_additive "Given a map `f : M →+ N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x - f y = z` if there always exists such an element."] noncomputable def sec (f : M →* N) := @classical.epsilon (N → M × S) ⟨λ z, 1⟩ (λ g, ∀ z, z * f (g z).2 = f (g z).1) variables {S} @[to_additive] lemma sec_spec {f : M →* N} (h : ∀ z : N, ∃ x : M × S, z * f x.2 = f x.1) (z : N) : z * f (sec S f z).2 = f (sec S f z).1 := @classical.epsilon_spec (N → M × S) (λ g, ∀ z, z * f (g z).2 = f (g z).1) ⟨λ y, classical.some $ h y, λ y, classical.some_spec $ h y⟩ z @[to_additive] lemma sec_spec' {f : M →* N} (h : ∀ z : N, ∃ x : M × S, z * f x.2 = f x.1) (z : N) : f (sec S f z).1 = f (sec S f z).2 * z := by rw [mul_comm, sec_spec h] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `w * (f y)⁻¹ = z ↔ w = f y * z`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `w : M, z : N` and `y ∈ S`, we have `w - f y = z ↔ w = f y + z`."] lemma mul_inv_left {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : w * ↑(is_unit.lift_right (f.restrict S) h y)⁻¹ = z ↔ w = f y * z := by rw mul_comm; convert units.inv_mul_eq_iff_eq_mul _; exact (is_unit.coe_lift_right (f.restrict S) h _).symm /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w * (f y)⁻¹ ↔ z * f y = w`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w - f y ↔ z + f y = w`."] lemma mul_inv_right {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : z = w * ↑(is_unit.lift_right (f.restrict S) h y)⁻¹ ↔ z * f y = w := by rw [eq_comm, mul_inv_left h, mul_comm, eq_comm] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ * (f y₁)⁻¹ = f x₂ * (f y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁)`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ - f y₁ = f x₂ - f y₂ ↔ f (x₁ + y₂) = f (x₂ + y₁)`."] lemma mul_inv {f : M →* N} (h : ∀ y : S, is_unit (f y)) {x₁ x₂} {y₁ y₂ : S} : f x₁ * ↑(is_unit.lift_right (f.restrict S) h y₁)⁻¹ = f x₂ * ↑(is_unit.lift_right (f.restrict S) h y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁) := by rw [mul_inv_right h, mul_assoc, mul_comm _ (f y₂), ←mul_assoc, mul_inv_left h, mul_comm x₂, f.map_mul, f.map_mul] /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y, z ∈ S`, we have `(f y)⁻¹ = (f z)⁻¹ → f y = f z`. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `y, z ∈ S`, we have `- (f y) = - (f z) → f y = f z`."] lemma inv_inj {f : M →* N} (hf : ∀ y : S, is_unit (f y)) {y z} (h : (is_unit.lift_right (f.restrict S) hf y)⁻¹ = (is_unit.lift_right (f.restrict S) hf z)⁻¹) : f y = f z := by rw [←mul_one (f y), eq_comm, ←mul_inv_left hf y (f z) 1, h]; convert units.inv_mul _; exact (is_unit.coe_lift_right (f.restrict S) hf _).symm /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y ∈ S`, `(f y)⁻¹` is unique. -/ @[to_additive "Given an add_monoid hom `f : M →+ N` and submonoid `S ⊆ M` such that `f(S) ⊆ add_units N`, for all `y ∈ S`, `- (f y)` is unique."] lemma inv_unique {f : M →* N} (h : ∀ y : S, is_unit (f y)) {y : S} {z} (H : f y * z = 1) : ↑(is_unit.lift_right (f.restrict S) h y)⁻¹ = z := by rw [←one_mul ↑(_)⁻¹, mul_inv_left, ←H] variables (f : localization_map S N) /-- Given a localization map `f : M →* N`, the surjection sending `(x, y) : M × S` to `f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N`, the surjection sending `(x, y) : M × S` to `f x - f y`."] noncomputable def mk' (f : localization_map S N) (x : M) (y : S) : N := f.1 x * ↑(is_unit.lift_right (f.1.restrict S) f.2 y)⁻¹ @[to_additive] lemma mk'_mul (x₁ x₂ : M) (y₁ y₂ : S) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := (mul_inv_left f.2 _ _ _).2 $ show _ = _ * (_ * _ * (_ * _)), by rw [←mul_assoc, ←mul_assoc, mul_inv_right f.2, mul_assoc, mul_assoc, mul_comm _ (f.1 x₂), ←mul_assoc, ←mul_assoc, mul_inv_right f.2, submonoid.coe_mul, f.1.map_mul, f.1.map_mul]; ac_refl @[to_additive] lemma mk'_one (x) : f.mk' x (1 : S) = f.1 x := by rw [mk', monoid_hom.map_one]; exact mul_one (f.1 x) /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z * f y = f x`, then `f x * (f y)⁻¹ = z`. -/ @[simp, to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z + f y = f x`, then `f x - f y = z`."] lemma mk'_sec (z : N) : f.mk' (sec S f.1 z).1 (sec S f.1 z).2 = z := show _ * _ = _, by rw [←sec_spec f.3, mul_inv_left, mul_comm] @[to_additive] lemma mk'_surjective (z : N) : ∃ x (y : S), f.mk' x y = z := ⟨(sec S f.1 z).1, (sec S f.1 z).2, f.mk'_sec z⟩ @[to_additive] lemma mk'_spec (x) (y : S) : f.mk' x y * f.1 y = f.1 x := show _ * _ * _ = _, by rw [mul_assoc, mul_comm _ (f.1 y), ←mul_assoc, mul_inv_left, mul_comm] @[to_additive] lemma mk'_spec' (x) (y : S) : f.1 y * f.mk' x y = f.1 x := by rw [mul_comm, mk'_spec] @[to_additive] theorem eq_mk'_iff_mul_eq {x} {y : S} {z} : z = f.mk' x y ↔ z * f.1 y = f.1 x := ⟨λ H, by rw [H, mk'_spec], λ H, by erw [mul_inv_right, H]; refl⟩ @[to_additive] theorem mk'_eq_iff_eq_mul {x} {y : S} {z} : f.mk' x y = z ↔ f.1 x = z * f.1 y := by rw [eq_comm, eq_mk'_iff_mul_eq, eq_comm] @[to_additive] lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.1 (x₁ * y₂) = f.1 (x₂ * y₁) := ⟨λ H, by rw [f.1.map_mul, f.mk'_eq_iff_eq_mul.1 H, mul_assoc, mul_comm (f.1 _), ←mul_assoc, mk'_spec, f.1.map_mul], λ H, by rw [mk'_eq_iff_eq_mul, mk', mul_assoc, mul_comm _ (f.1 y₁), ←mul_assoc, ←f.1.map_mul, ←H, f.1.map_mul, mul_inv_right f.2]⟩ @[to_additive] protected lemma eq {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : S, a₁ * b₂ * c = b₁ * a₂ * c := f.mk'_eq_iff_eq.trans $ f.4 _ _ @[to_additive] protected lemma eq' {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ localization.r S (a₁, a₂) (b₁, b₂) := by rw [f.eq, localization.r_iff_exists] @[to_additive] lemma eq_iff_eq (g : localization_map S P) {x y} : f.1 x = f.1 y ↔ g.1 x = g.1 y := (f.4 _ _).trans (g.4 _ _).symm @[to_additive] lemma mk'_eq_iff_mk'_eq (g : localization_map S P) {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.eq'.trans g.eq'.symm /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `f x₁ * (f y₁)⁻¹ * f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ * y₂ * c = x₂ * y₁ * c`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `(f x₁ - f y₁) + f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ + y₂ + c = x₂ + y₁ + c`."] lemma exists_of_sec_mk' (x) (y : S) : ∃ c : S, x * (sec S f.1 $ f.mk' x y).2 * c = (sec S f.1 $ f.mk' x y).1 * y * c := (f.4 _ _).1 $ f.mk'_eq_iff_eq.1 $ (mk'_sec _ _).symm @[to_additive] lemma mk'_eq_of_eq {a₁ b₁ : M} {a₂ b₂ : S} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.mk'_eq_iff_eq.2 $ H ▸ rfl @[simp, to_additive] lemma mk'_self (y : S) : f.mk' (y : M) y = 1 := show _ * _ = _, by rw [mul_inv_left, mul_one] @[simp, to_additive] lemma mk'_self' (x) (H : x ∈ S) : f.mk' x ⟨x, H⟩ = 1 := by convert mk'_self _ _; refl @[to_additive] lemma mul_mk'_eq_mk'_of_mul (x₁ x₂) (y : S) : f.1 x₁ * f.mk' x₂ y = f.mk' (x₁ * x₂) y := by rw [←mk'_one, ←mk'_mul, one_mul] @[to_additive] lemma mk'_mul_eq_mk'_of_mul (x₁ x₂) (y : S) : f.mk' x₂ y * f.1 x₁ = f.mk' (x₁ * x₂) y := by rw [mul_comm, mul_mk'_eq_mk'_of_mul] @[to_additive] lemma mul_mk'_one_eq_mk' (x) (y : S) : f.1 x * f.mk' 1 y = f.mk' x y := by rw [mul_mk'_eq_mk'_of_mul, mul_one] @[to_additive] lemma mk'_mul_cancel_right (x : M) (y : S) : f.mk' (x * y) y = f.1 x := by rw [←mul_mk'_one_eq_mk', f.1.map_mul, mul_assoc, mul_mk'_one_eq_mk', mk'_self, mul_one] @[to_additive] lemma mk'_mul_cancel_left (x) (y : S) : f.mk' ((y : M) * x) y = f.1 x := by rw [mul_comm, mk'_mul_cancel_right] @[to_additive] lemma is_unit_comp (j : N →* P) (y : S) : is_unit (j.comp f.1 y) := ⟨units.map j $ is_unit.lift_right (f.1.restrict S) f.2 y, show j _ = j _, from congr_arg j $ (is_unit.coe_lift_right (f.1.restrict S) f.2 _).symm⟩ variables {g : M →* P} /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g(S) ⊆ units P`, `f x = f y → g x = g y` for all `x y : M`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g(S) ⊆ add_units P`, `f x = f y → g x = g y` for all `x y : M`."] lemma eq_of_eq (hg : ∀ y : S, is_unit (g y)) {x y} (h : f.1 x = f.1 y) : g x = g y := begin obtain ⟨c, hc⟩ := (f.4 _ _).1 h, rw [←mul_one (g x), ←is_unit.mul_lift_right_inv (g.restrict S) hg c], show _ * (g c * _) = _, rw [←mul_assoc, ←g.map_mul, hc, mul_inv_left hg, g.map_mul, mul_comm], end /-- Given `comm_monoid`s `M, P`, localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, and `g : M →* P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`. -/ @[to_additive "Given `add_comm_monoid`s `M, P`, localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, and `g : M →+ P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`."] lemma comp_eq_of_eq {T : submonoid P} {Q : Type*} [comm_monoid Q] (hg : ∀ y : S, g y ∈ T) (k : localization_map T Q) {x y} (h : f.1 x = f.1 y) : k.1 (g x) = k.1 (g y) := f.eq_of_eq (λ y : S, show is_unit (k.1.comp g y), from k.2 ⟨g y, hg y⟩) h variables (hg : ∀ y : S, is_unit (g y)) /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x * (g y)⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x - g y`, where `(x, y) : M × S` are such that `z = f x - f y`."] noncomputable def lift : N →* P := { to_fun := λ z, g (sec S f.1 z).1 * ↑(is_unit.lift_right (g.restrict S) hg (sec S f.1 z).2)⁻¹, map_one' := by rw [mul_inv_left, mul_one]; exact f.eq_of_eq hg (by rw [←sec_spec f.3, one_mul]), map_mul' := λ x y, by rw [mul_inv_left hg, ←mul_assoc, ←mul_assoc, mul_inv_right hg, mul_comm _ (g (sec S f.1 y).1), ←mul_assoc, ←mul_assoc, mul_inv_right hg]; repeat { rw ←g.map_mul }; exact f.eq_of_eq hg (by repeat { rw f.1.map_mul <|> rw sec_spec' f.3 }; ac_refl) } variables {S g} /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : M, y ∈ S`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M` and a map of `add_comm_monoid`s `g : M →+ P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x - f y` to `g x - g y` for all `x : M, y ∈ S`."] lemma lift_mk' (x y) : f.lift hg (f.mk' x y) = g x * ↑(is_unit.lift_right (g.restrict S) hg y)⁻¹ := (mul_inv hg).2 $ f.eq_of_eq hg $ by rw [f.1.map_mul, f.1.map_mul, sec_spec' f.3, mul_assoc, f.mk'_spec, mul_comm] /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y + v`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_spec (z v) : f.lift hg z = v ↔ g (sec S f.1 z).1 = g (sec S f.1 z).2 * v := mul_inv_left hg _ _ v /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v w : P`, we have `f.lift hg z * w = v ↔ g x * w = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N, v w : P`, we have `f.lift hg z + w = v ↔ g x + w = g y + v`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_spec_mul (z w v) : f.lift hg z * w = v ↔ g (sec S f.1 z).1 * w = g (sec S f.1 z).2 * v := begin rw mul_comm, show _ * (_ * _) = _ ↔ _, rw [←mul_assoc, mul_inv_left hg, mul_comm], end @[to_additive] lemma lift_mk'_spec (x v) (y : S) : f.lift hg (f.mk' x y) = v ↔ g x = g y * v := by rw f.lift_mk' hg; exact mul_inv_left hg _ _ _ /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `f.lift hg z * g y = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N`, we have `f.lift hg z + g y = g x`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_mul_right (z) : f.lift hg z * g (sec S f.1 z).2 = g (sec S f.1 z).1 := show _ * _ * _ = _, by erw [mul_assoc, is_unit.lift_right_inv_mul, mul_one] /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `g y * f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given a localization map `f : M →+ N` for a submonoid `S ⊆ M`, if an `add_comm_monoid` map `g : M →+ P` induces a map `f.lift hg : N →+ P` then for all `z : N`, we have `g y + f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma lift_mul_left (z) : g (sec S f.1 z).2 * f.lift hg z = g (sec S f.1 z).1 := by rw [mul_comm, lift_mul_right] @[simp, to_additive] lemma lift_eq (x : M) : f.lift hg (f.1 x) = g x := by rw [lift_spec, ←g.map_mul]; exact f.eq_of_eq hg (by rw [sec_spec' f.3, f.1.map_mul]) @[to_additive] lemma lift_eq_iff {x y : M × S} : f.lift hg (f.mk' x.1 x.2) = f.lift hg (f.mk' y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := by rw [lift_mk', lift_mk', mul_inv hg] @[simp, to_additive] lemma lift_comp : (f.lift hg).comp f.1 = g := by ext; exact f.lift_eq hg _ @[simp, to_additive] lemma lift_of_comp (j : N →* P) : f.lift (f.is_unit_comp j) = j := begin ext, rw lift_spec, show j _ = j _ * _, erw [←j.map_mul, sec_spec' f.3], end @[to_additive] lemma epic_of_localization_map {j k : N →* P} (h : ∀ a, j.comp f.1 a = k.comp f.1 a) : j = k := begin rw [←f.lift_of_comp j, ←f.lift_of_comp k], congr' 1, ext, exact h x, end @[to_additive] lemma lift_unique {j : N →* P} (hj : ∀ x, j (f.1 x) = g x) : f.lift hg = j := begin ext, rw [lift_spec, ←hj, ←hj, ←j.map_mul], apply congr_arg, rw ←sec_spec' f.3, end @[simp, to_additive] lemma lift_id (x) : f.lift f.2 x = x := monoid_hom.ext_iff.1 (f.lift_of_comp $ monoid_hom.id N) x /-- Given two localization maps `f : M →* N, k : M →* P` for a submonoid `S ⊆ M`, the hom from `P` to `N` induced by `f` is left inverse to the hom from `N` to `P` induced by `k`. -/ @[simp, to_additive] lemma lift_left_inverse {k : localization_map S P} (z : N) : k.lift f.2 (f.lift k.2 z) = z := begin rw lift_spec, cases f.3 z with x hx, conv_rhs {congr, skip, rw f.eq_mk'_iff_mul_eq.2 hx}, rw [mk', ←mul_assoc, mul_inv_right f.2, ←f.1.map_mul, ←f.1.map_mul], apply k.eq_of_eq f.2, rw [k.1.map_mul, k.1.map_mul, ←sec_spec k.3, mul_assoc, lift_spec_mul], repeat { rw ←k.1.map_mul }, apply f.eq_of_eq k.2, repeat { rw f.1.map_mul }, rw [sec_spec' f.3, ←hx], ac_refl, end @[to_additive] lemma lift_surjective_iff : function.surjective (f.lift hg) ↔ ∀ v : P, ∃ x : M × S, v * g x.2 = g x.1 := begin split, { intros H v, obtain ⟨z, hz⟩ := H v, obtain ⟨x, hx⟩ := f.3 z, use x, rw [←hz, f.eq_mk'_iff_mul_eq.2 hx, lift_mk', mul_assoc, mul_comm _ (g ↑x.2)], erw [is_unit.mul_lift_right_inv (g.restrict S) hg, mul_one] }, { intros H v, obtain ⟨x, hx⟩ := H v, use f.mk' x.1 x.2, rw [lift_mk', mul_inv_left hg, mul_comm, ←hx] } end @[to_additive] lemma lift_injective_iff : function.injective (f.lift hg) ↔ ∀ x y, f.1 x = f.1 y ↔ g x = g y := begin split, { intros H x y, split, { exact f.eq_of_eq hg }, { intro h, rw [←f.lift_eq hg, ←f.lift_eq hg] at h, exact H h }}, { intros H z w h, obtain ⟨x, hx⟩ := f.3 z, obtain ⟨y, hy⟩ := f.3 w, rw [←f.mk'_sec z, ←f.mk'_sec w], exact (mul_inv f.2).2 ((H _ _).2 $ (mul_inv hg).1 h) } end variables {T : submonoid P} (hy : ∀ y : S, g y ∈ T) {Q : Type*} [comm_monoid Q] (k : localization_map T Q) /-- Given a `comm_monoid` homomorphism `g : M →* P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →* N` and `k : P →* Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ @[to_additive "Given a `add_comm_monoid` homomorphism `g : M →+ P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced add_monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →+ N` and `k : P →+ Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) - k (g y)`, where `(x, y) : M × S` are such that `z = f x - f y`."] noncomputable def map : N →* Q := @lift _ _ _ _ _ _ _ f (k.1.comp g) $ λ y, k.2 ⟨g y, hy y⟩ variables {k} @[to_additive] lemma map_eq (x) : f.map hy k (f.1 x) = k.1 (g x) := f.lift_eq (λ y, k.2 ⟨g y, hy y⟩) x @[simp, to_additive] lemma map_comp : (f.map hy k).comp f.1 = k.1.comp g := f.lift_comp $ λ y, k.2 ⟨g y, hy y⟩ @[to_additive] lemma map_mk' (x) (y : S) : f.map hy k (f.mk' x y) = k.mk' (g x) ⟨g y, hy y⟩ := begin rw [map, lift_mk', mul_inv_left], { show k.1 (g x) = k.1 (g y) * _, rw mul_mk'_eq_mk'_of_mul, exact (k.mk'_mul_cancel_left (g x) ⟨(g y), hy y⟩).symm }, end /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) * u` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) + u` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_spec (z u) : f.map hy k z = u ↔ k.1 (g (sec S f.1 z).1) = k.1 (g (sec S f.1 z).2) * u := f.lift_spec (λ y, k.2 ⟨g y, hy y⟩) _ _ /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `f.map hy k z * k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, we have `f.map hy k z + k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_mul_right (z) : f.map hy k z * (k.1 (g (sec S f.1 z).2)) = k.1 (g (sec S f.1 z).1) := f.lift_mul_right (λ y, k.2 ⟨g y, hy y⟩) _ /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `k (g y) * f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ Q` for submonoids `S, T` respectively, if an `add_comm_monoid` homomorphism `g : M →+ P` induces a `f.map hy k : N →+ Q`, then for all `z : N`, we have `k (g y) + f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z + f y = f x`."] lemma map_mul_left (z) : k.1 (g (sec S f.1 z).2) * f.map hy k z = k.1 (g (sec S f.1 z).1) := by rw [mul_comm, f.map_mul_right] @[simp, to_additive] lemma map_id (z : N) : f.map (λ y, show monoid_hom.id M y ∈ S, from y.2) f z = z := f.lift_id z /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ @[to_additive "If `add_comm_monoid` homs `g : M →+ P, l : P →+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`."] lemma map_comp_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ w : T, l w ∈ U) : (k.map hl j).comp (f.map hy k) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j := begin ext z, show j.1 _ * _ = j.1 (l _) * _, { rw [mul_inv_left, ←mul_assoc, mul_inv_right], show j.1 _ * j.1 (l (g _)) = j.1 (l _) * _, rw [←j.1.map_mul, ←j.1.map_mul, ←l.map_mul, ←l.map_mul], exact k.comp_eq_of_eq hl j (by rw [k.1.map_mul, k.1.map_mul, sec_spec' k.3, mul_assoc, map_mul_right]) }, end /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ @[to_additive "If `add_comm_monoid` homs `g : M →+ P, l : P →+ A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`."] lemma map_map {A : Type*} [comm_monoid A] {U : submonoid A} {R} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ w : T, l w ∈ U) (x) : k.map hl j (f.map hy k x) = f.map (λ x, show l.comp g x ∈ U, from hl ⟨g x, hy x⟩) j x := by rw ←f.map_comp_map hy j hl; refl variables {g} /-- If `f : M →* N` and `k : M →* R` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `R`. -/ @[to_additive "If `f : M →+ N` and `k : M →+ R` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `R`."] noncomputable def mul_equiv_of_localizations (k : localization_map S P) : N ≃* P := ⟨f.lift k.2, k.lift f.2, f.lift_left_inverse, k.lift_left_inverse, monoid_hom.map_mul _⟩ @[simp, to_additive] lemma mul_equiv_of_localizations_apply {k : localization_map S P} {x} : f.mul_equiv_of_localizations k x = f.lift k.2 x := rfl @[simp, to_additive] lemma mul_equiv_of_localizations_symm_apply {k : localization_map S P} {x} : (f.mul_equiv_of_localizations k).symm x = k.lift f.2 x := rfl /-- If `f : M →* N` is a localization map for a submonoid `S` and `k : N ≃* P` is an isomorphism of `comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`. -/ @[to_additive "If `f : M →+ N` is a localization map for a submonoid `S` and `k : N ≃+ P` is an isomorphism of `add_comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`."] def to_mul_equiv (k : N ≃* P) : localization_map S P := { to_fun := k.to_monoid_hom.comp f.1, map_units := λ y, is_unit_comp f k.to_monoid_hom y, surj := λ v, let ⟨z, hz⟩ := k.to_equiv.surjective v in let ⟨x, hx⟩ := f.3 z in ⟨x, show v * k _ = k _, by rw [←hx, k.map_mul, ←hz]; refl⟩, eq_iff_exists := λ x y, (k.to_equiv.apply_eq_iff_eq _ _).trans $ f.4 _ _ } @[simp, to_additive] lemma to_mul_equiv_eq {k : N ≃* P} : (f.to_mul_equiv k).1 = k.to_monoid_hom.comp f.1 := rfl @[to_additive] lemma symm_to_mul_equiv_apply {k : N ≃* P} (x) : k.symm ((f.to_mul_equiv k).1 x) = f.1 x := k.symm_apply_apply (f.1 x) @[to_additive] lemma comp_mul_equiv_symm_map_apply {k : P ≃* N} (x) : k ((f.to_mul_equiv k.symm).1 x) = f.1 x := k.apply_symm_apply (f.1 x) @[to_additive] lemma to_mul_equiv_eq_iff_eq {k : N ≃* P} {x y} : (f.to_mul_equiv k).1 x = y ↔ f.1 x = k.symm y := k.to_equiv.eq_symm_apply.symm @[to_additive] lemma mul_equiv_of_to_mul_equiv (k : localization_map S P) : f.to_mul_equiv (f.mul_equiv_of_localizations k) = k := to_fun_inj $ f.lift_comp k.2 @[to_additive] lemma mul_equiv_of_to_mul_equiv_apply {k : localization_map S P} {x} : (f.to_mul_equiv (f.mul_equiv_of_localizations k)).1 x = k.1 x := ext_iff.1 (f.mul_equiv_of_to_mul_equiv k) x @[simp, to_additive] lemma to_mul_equiv_of_mul_equiv (k : N ≃* P) : f.mul_equiv_of_localizations (f.to_mul_equiv k) = k := mul_equiv.ext $ monoid_hom.ext_iff.1 $ f.lift_of_comp k.to_monoid_hom @[to_additive] lemma to_mul_equiv_of_mul_equiv_apply {k : N ≃* P} (x) : f.mul_equiv_of_localizations (f.to_mul_equiv k) x = k x := by rw to_mul_equiv_of_mul_equiv @[simp, to_additive] lemma to_mul_equiv_id : f.to_mul_equiv (mul_equiv.refl N) = f := by ext; refl @[to_additive] lemma to_mul_equiv_comp {k : N ≃* P} {j : P ≃* Q} : (f.to_mul_equiv (k.trans j)).1 = j.to_monoid_hom.comp (f.to_mul_equiv k).1 := by ext; refl /-- Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`. -/ @[to_additive "Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`."] def of_mul_equiv {k : P ≃* M} (H : T.map k.to_monoid_hom = S) : localization_map T N := let H' : S.comap k.to_monoid_hom = T := H ▸ (submonoid.ext' $ T.1.preimage_image_eq k.to_equiv.injective) in { to_fun := f.1.comp k.to_monoid_hom, map_units := λ y, let ⟨z, hz⟩ := f.2 ⟨k y, H ▸ set.mem_image_of_mem k y.2⟩ in ⟨z, hz⟩, surj := λ z, let ⟨x, hx⟩ := f.3 z in let ⟨v, hv⟩ := k.to_equiv.surjective x.1 in let ⟨w, hw⟩ := k.to_equiv.surjective x.2 in ⟨(v, ⟨w, H' ▸ show k w ∈ S, from hw.symm ▸ x.2.2⟩), show z * f.1 (k.to_equiv w) = f.1 (k.to_equiv v), by erw [hv, hw, hx]; refl⟩, eq_iff_exists := λ x y, show f.1 _ = f.1 _ ↔ _, by erw f.4; exact ⟨λ ⟨c, hc⟩, let ⟨d, hd⟩ := k.to_equiv.surjective c in ⟨⟨d, H' ▸ show k d ∈ S, from hd.symm ▸ c.2⟩, by erw [←hd, ←k.map_mul, ←k.map_mul] at hc; exact k.to_equiv.injective hc⟩, λ ⟨c, hc⟩, ⟨⟨k c, H ▸ set.mem_image_of_mem k c.2⟩, by erw ←k.map_mul; rw [hc, k.map_mul]; refl⟩⟩ } @[simp, to_additive] lemma of_mul_equiv_eq {k : P ≃* M} (H : T.map k.to_monoid_hom = S) : (f.of_mul_equiv H).1 = f.1.comp k.to_monoid_hom := rfl @[to_additive] lemma symm_of_mul_equiv_apply {k : P ≃* M} (H : T.map k.to_monoid_hom = S) (x) : (f.of_mul_equiv H).1 (k.symm x) = f.1 x := congr_arg f.1 $ k.apply_symm_apply x @[to_additive] lemma comp_mul_equiv_symm_comap_apply {k : M ≃* P} (H : T.map k.symm.to_monoid_hom = S) (x) : (f.of_mul_equiv H).1 (k x) = f.1 x := congr_arg f.1 $ k.symm_apply_apply x /-- A special case of `f ∘ id = f`, `f` a localization map. -/ @[simp, to_additive "A special case of `f ∘ id = f`, `f` a localization map."] lemma of_mul_equiv_id : f.of_mul_equiv (show S.map (mul_equiv.refl M).to_monoid_hom = S, from submonoid.ext $ λ x, ⟨λ ⟨y, hy, h⟩, h ▸ hy, λ h, ⟨x, h, rfl⟩⟩) = f := by ext; refl /-- Given localization maps `f : M →* N, k : P →* U` for submonoids `S, T` respectively, an isomorphism `j : M ≃* P` such that `j(S) = T` induces an isomorphism of localizations `N ≃* U`. -/ @[to_additive "Given localization maps `f : M →+ N, k : P →+ U` for submonoids `S, T` respectively, an isomorphism `j : M ≃+ P` such that `j(S) = T` induces an isomorphism of localizations `N ≃+ U`."] noncomputable def mul_equiv_of_mul_equiv (k : localization_map T Q) {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : N ≃* Q := f.mul_equiv_of_localizations $ k.of_mul_equiv H @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq_map_apply {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : f.mul_equiv_of_mul_equiv k H x = f.map (λ y : S, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k x := rfl @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq_map {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : (f.mul_equiv_of_mul_equiv k H).to_monoid_hom = f.map (λ y : S, show j.to_monoid_hom y ∈ T, from H ▸ set.mem_image_of_mem j y.2) k := rfl @[simp, to_additive] lemma mul_equiv_of_mul_equiv_eq {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : f.mul_equiv_of_mul_equiv k H (f.1 x) = k.1 (j x) := f.map_eq (λ y : S, H ▸ set.mem_image_of_mem j y.2) _ @[to_additive] lemma mul_equiv_of_mul_equiv_mk' {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x y) : f.mul_equiv_of_mul_equiv k H (f.mk' x y) = k.mk' (j x) ⟨j y, H ▸ set.mem_image_of_mem j y.2⟩ := f.map_mk' (λ y : S, H ▸ set.mem_image_of_mem j y.2) _ _ @[to_additive] lemma to_mul_equiv_of_mul_equiv_of_mul_equiv_apply {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) (x) : (f.to_mul_equiv (f.mul_equiv_of_mul_equiv k H)).1 x = k.1 (j x) := ext_iff.1 (f.mul_equiv_of_to_mul_equiv (k.of_mul_equiv H)) x @[simp, to_additive] lemma to_mul_equiv_of_mul_equiv_of_mul_equiv {k : localization_map T Q} {j : M ≃* P} (H : S.map j.to_monoid_hom = T) : (f.to_mul_equiv (f.mul_equiv_of_mul_equiv k H)).1 = k.1.comp j.to_monoid_hom := monoid_hom.ext $ f.to_mul_equiv_of_mul_equiv_of_mul_equiv_apply H end localization_map end submonoid
533e021a3256cea926f985fa82e03348b75bb154
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/archive/imo/imo1972_b2.lean
e1ad58e24f7dfd40a1fb80a6d7a3a0d768c9d806
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
4,418
lean
/- Copyright (c) 2020 Ruben Van de Velde, Stanislas Polu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ruben Van de Velde, Stanislas Polu -/ import data.real.basic import data.set.basic import analysis.normed_space.basic /-- IMO 1972 B2 Problem: `f` and `g` are real-valued functions defined on the real line. For all `x` and `y`, `f(x + y) + f(x - y) = 2f(x)g(y)`. `f` is not identically zero and `|f(x)| ≤ 1` for all `x`. Prove that `|g(x)| ≤ 1` for all `x`. This proof begins by introducing the supremum of `f`, `k ≤ 1` as well as `k' = k / ∥g y∥`. We then suppose that the conclusion does not hold (`hneg`) and show that `k ≤ k'` (by `2 * (∥f x∥ * ∥g y∥) ≤ 2 * k` obtained from the main hypothesis `hf1`) and that `k' < k` (obtained from `hneg` directly), finally raising a contradiction with `k' < k'`. (Authored by Stanislas Polu inspired by Ruben Van de Velde). -/ example (f g : ℝ → ℝ) (hf1 : ∀ x, ∀ y, (f(x+y) + f(x-y)) = 2 * f(x) * g(y)) (hf2 : ∀ y, ∥f(y)∥ ≤ 1) (hf3 : ∃ x, f(x) ≠ 0) (y : ℝ) : ∥g(y)∥ ≤ 1 := begin classical, set S := set.range (λ x, ∥f x∥), -- Introduce `k`, the supremum of `f`. let k : ℝ := Sup (S), -- Show that `∥f x∥ ≤ k`. have hk₁ : ∀ x, ∥f x∥ ≤ k, { have h : ∃ x, ∀ y ∈ S, y ≤ x, { use 1, intros _ hy, rw set.mem_range at hy, rcases hy with ⟨z, rfl⟩, exact hf2 z, }, intro x, exact real.le_Sup S h (set.mem_range_self x), }, -- Show that `2 * (∥f x∥ * ∥g y∥) ≤ 2 * k`. have hk₂ : ∀ x, 2 * (∥f x∥ * ∥g y∥) ≤ 2 * k, { intro x, calc 2 * (∥f x∥ * ∥g y∥) = ∥2 * f x * g y∥ : by simp [real.norm_eq_abs, abs_mul, mul_assoc] ... = ∥f (x + y) + f (x - y)∥ : by rw hf1 ... ≤ ∥f (x + y)∥ + ∥f (x - y)∥ : norm_add_le _ _ ... ≤ k + k : add_le_add (hk₁ _) (hk₁ _) ... = 2 * k : (two_mul _).symm, }, -- Suppose the conclusion does not hold. by_contra hneg, push_neg at hneg, set k' := k / ∥g y∥, -- Demonstrate that `k' < k` using `hneg`. have H₁ : k' < k, { have h₁ : 0 < k, { obtain ⟨x, hx⟩ := hf3, calc 0 < ∥f x∥ : norm_pos_iff.mpr hx ... ≤ k : hk₁ x }, rw div_lt_iff, apply lt_mul_of_one_lt_right h₁ hneg, exact trans zero_lt_one hneg }, -- Demonstrate that `k ≤ k'` using `hk₂`. have H₂ : k ≤ k', { have h₁ : ∃ x : ℝ, x ∈ S, { use ∥f 0∥, exact set.mem_range_self 0, }, have h₂ : ∀ x, ∥f x∥ ≤ k', { intros x, rw le_div_iff, { apply (mul_le_mul_left zero_lt_two).mp (hk₂ x) }, { exact trans zero_lt_one hneg } }, apply real.Sup_le_ub _ h₁, rintros y' ⟨yy, rfl⟩, exact h₂ yy }, -- Conclude by obtaining a contradiction, `k' < k'`. apply lt_irrefl k', calc k' < k : H₁ ... ≤ k' : H₂, end /-- IMO 1972 B2 Problem: `f` and `g` are real-valued functions defined on the real line. For all `x` and `y`, `f(x + y) + f(x - y) = 2f(x)g(y)`. `f` is not identically zero and `|f(x)| ≤ 1` for all `x`. Prove that `|g(x)| ≤ 1` for all `x`. This is a more concise version of the proof proposed by Ruben Van de Velde. -/ example (f g : ℝ → ℝ) (hf1 : ∀ x, ∀ y, (f (x+y) + f(x-y)) = 2 * f(x) * g(y)) (hf2 : bdd_above (set.range (λ x, ∥f x∥))) (hf3 : ∃ x, f(x) ≠ 0) (y : ℝ) : ∥g(y)∥ ≤ 1 := begin obtain ⟨x, hx⟩ := hf3, set k := supr (λ x, ∥f x∥), have h : ∀ x, ∥f x∥ ≤ k := le_csupr hf2, by_contradiction H, push_neg at H, have hgy : 0 < ∥g y∥, by linarith, have k_pos : 0 < k := lt_of_lt_of_le (norm_pos_iff.mpr hx) (h x), have : k / ∥g y∥ < k := (div_lt_iff hgy).mpr (lt_mul_of_one_lt_right k_pos H), have : k ≤ k / ∥g y∥, { suffices : ∀ x, ∥f x∥ ≤ k / ∥g y∥, from csupr_le this, intro x, suffices : 2 * (∥f x∥ * ∥g y∥) ≤ 2 * k, by rwa [le_div_iff hgy, ←mul_le_mul_left zero_lt_two], calc 2 * (∥f x∥ * ∥g y∥) = ∥2 * f x * g y∥ : by simp [abs_mul, mul_assoc] ... = ∥f (x + y) + f (x - y)∥ : by rw hf1 ... ≤ ∥f (x + y)∥ + ∥f (x - y)∥ : abs_add _ _ ... ≤ 2 * k : by linarith [h (x+y), h (x -y)] }, linarith, end
eafc72e47b4052124c9c25192945ba5fb6e3914d
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/linear_algebra/basic.lean
ac1e5e52524fe13fff5baec61a2dd14aa05928d6
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
97,705
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, Kevin Buzzard, Yury Kudryashov -/ import algebra.pi_instances import data.finsupp /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module.lean`. ## Main definitions * Many constructors for linear maps, including `prod` and `coprod` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends `linear_map` and `equiv`. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `quotient_inf_equiv_sup_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`prod`, `coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators reserve infix ` ≃ₗ `:25 universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [semiring R] [add_comm_monoid M] [semimodule R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := begin ext k, rw pi.finset_sum_apply, have : ∑ i, x i * ite (k = i) 1 0 = x k, by { have := finset.sum_mul_boole finset.univ x k, rwa if_pos (finset.mem_univ _) at this }, rw ← this, apply finset.sum_congr rfl (λl hl, _), simp only [smul_eq_mul, mul_ite, pi.smul_apply], conv_lhs { rw eq_comm } end end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_monoid_hom (a : M) : is_add_monoid_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a, map_zero := rfl } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..}; { intros, apply linear_map.ext, simp {proj := ff} } section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩ end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem prod_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : prod f g x = (f x, g x) := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl] /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr] end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := { to_fun := λ x, f x.1 + g x.2, map_add' := λ x y, by simp only [map_add, prod.snd_add, prod.fst_add]; cc, map_smul' := λ x y, by simp only [smul_add, prod.smul_snd, prod.smul_fst, map_smul] } @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : coprod f g (x, y) = f x + g y := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext ⟨x, y⟩; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext ⟨x, y⟩; simp theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (f g : M →ₗ[R] M₂) include R /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl end add_comm_group section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (f g : M →ₗ[R] M₂) include R instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl instance : semimodule R (M →ₗ[R] M₂) := by refine { smul := (•), .. }; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl end comm_semiring section ring instance endomorphism_ring [ring R] [add_comm_group M] [semimodule R M] : ring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp {proj := ff} } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := { le := λ p p', ∀ ⦃x⦄, x ∈ p → x ∈ p', ..partial_order.lift (coe : submodule R M → set M) coe_injective } variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) := ⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx, λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩ protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) := by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, (s : set M), zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot } instance add_comm_monoid_submodule : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hdir end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [submodule.exists, coe_mk] end lemma mem_span_singleton_self (x : M) : x ∈ span R ({x} : set M) := subset_span (mem_def.mpr rfl) lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (span K {x}) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem _ i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : span R {m} ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : semimodule R (quotient p) := semimodule.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule @[simp] lemma finsupp_sum {γ} [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := set.ext_iff.1 (range_coe f) theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := begin refine eq_top_iff'.2 (λ x, mem_sup.2 _), rcases x with ⟨x₁, x₂⟩ , have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range, by simp, have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range, by simp, use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂], simp end /-- Restrict the codomain of a linear map `f` to `f.range`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : span R {x} = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0), from ⟨λ h m, h m mem_top, λ h m _, h m⟩, by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R open submodule theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [le_def', prod_apply, mem_range, mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end ring section field variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end field end linear_map lemma submodule.sup_eq_range [semiring R] [add_comm_monoid M] [semimodule R M] (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, submodule.exists] namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [semimodule R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [semimodule R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : p'.comap p.subtype = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : p.comap p.subtype = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [semimodule R M] [semimodule R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.order_iso : ((≤) : submodule R p → submodule R p → Prop) ≃o ((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], ord' := λ p₁ p₂, (map_le_map_iff' (ker_subtype p)).symm } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.le_order_embedding : ((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.le_order_embedding p p' = map p.subtype p' := rfl /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.lt_order_embedding : ((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (map_subtype.le_order_embedding p).lt_embedding_of_le_embedding /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.order_iso : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o ((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], ord' := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.le_order_embedding : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.lt_order_embedding : ((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding end ring end submodule @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (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₂] extends M →ₗ[R] M₂, M ≃ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma mk_apply {to_fun inv_fun map_add map_smul left_inv right_inv a} : (⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) a = to_fun a := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) @[simp, norm_cast] theorem coe_coe : ((e : M →ₗ[R] M₂) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma coe_to_equiv : ((e.to_equiv) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma to_fun_apply {m : M} : e.to_fun m = e m := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := to_equiv_injective (equiv.ext h) end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } @[simp] lemma inv_fun_apply {m : M₂} : e.inv_fun m = e.symm m := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } /-- A linear equivalence is an additive equivalence. -/ def to_add_equiv : M ≃+ M₂ := { .. e } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := to_equiv_injective e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := to_equiv_injective e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := submodule.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule of the domain onto the image of the submodule. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section prod variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end prod section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def uncurry : (V → V₂ → R) ≃ₗ[R] (V × V₂ → R) := { map_add' := λ _ _, by { ext ⟨⟩, refl }, map_smul' := λ _ _, by { ext ⟨⟩, refl }, .. equiv.arrow_arrow_equiv_prod_arrow _ _ _} @[simp] lemma coe_uncurry : ⇑(linear_equiv.uncurry R V V₂) = uncurry := rfl @[simp] lemma coe_uncurry_symm : ⇑(linear_equiv.uncurry R V V₂).symm = curry := rfl end uncurry section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [semimodule R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables {semimodule_M₃ : semimodule R M₃} {semimodule_M₄ : semimodule R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end add_comm_group section ring variables [ring 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₂) (e : M ≃ₗ[R] M₂) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. -/ noncomputable def of_injective (h : f.ker = ⊥) : M ≃ₗ[R] f.range := { .. (equiv.set.range f $ linear_map.ker_eq_bot.1 h).trans (equiv.set.of_eq f.range_coe.symm), .. f.cod_restrict f.range (λ x, f.mem_range_self x) } @[simp] theorem of_injective_apply {h : f.ker = ⊥} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp }, right_inv := λ f, by { ext x, simp }, map_add' := λ f g, by { ext x, simp }, map_smul' := λ c f, by { ext x, simp } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_group N] [add_comm_group N₂] [add_comm_group N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [add_comm_group N₁] [module R N₁] [add_comm_group N₂] [module R N₂] [add_comm_group N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (submodule.span K ({x} : set M)) := linear_equiv.trans ( linear_equiv.of_injective (to_span_singleton K M x) begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end ) (of_eq (to_span_singleton K M x).range (submodule.span K {x}) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span K ({x} : set M)) := begin apply submodule.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (submodule.span K ({x} : set M)) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) ( ⟨x, submodule.mem_span_singleton_self x⟩ : submodule.span K ({x} : set M)) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, map_smul' := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws section prod lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [semimodule R M] [semimodule R M₂] [semimodule R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables [semiring R] [add_comm_monoid M₂] [semimodule R M₂] [add_comm_monoid M₃] [semimodule R M₃] {φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, λ c d, funext $ λ i, (f i).map_add _ _, λ c d, funext $ λ i, (f i).map_smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.coe_prop], ext b ⟨j, hj⟩, refl }, { ext1 ⟨b, hb⟩, apply subtype.ext, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { refl }, { exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot_of_injective $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne R φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show ∑ i in I, std_basis R φ i (b i) = b, { ext i, rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $ (std_basis R φ i).mem_range_self (b i)) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [set.finite.mem_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi section fun_left variables (R M) [semiring R] [add_comm_monoid M] [semimodule R M] variables {m n p : Type*} /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := mk (∘f) (λ _ _, rfl) (λ _ _, rfl) @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end fun_left universe i variables [semiring R] [add_comm_monoid M] [semimodule R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map
6378c32a7e260c8cf9488c9216b5ced0c73f6bf4
695574baef97a204f68217f2dfede8512fd91ff8
/src/ralgebra.lean
eb9a3c1ca68cd0c489cad638289c4a1772faa979
[]
no_license
JasonKYi/stone-weierstrass
ba463bedc758c4993e922afcc8cf8895a9257bd4
390affd1415cf393da55866b82fdf68747dee7a2
refs/heads/master
1,680,089,697,789
1,617,652,603,000
1,617,652,603,000
266,203,243
1
0
null
null
null
null
UTF-8
Lean
false
false
6,637
lean
import topology.bounded_continuous_function noncomputable theory open set classical local attribute [instance] prop_decidable variables {X : Type*} [metric_space X] [compact_space X] -- We adopt the notation of bounded countinuous function from mathlib local infixr ` →ᵇ ` : 25 := bounded_continuous_function /- In this file we establish the main result - `subalgebra_of_R2` alongside some other lemmas regarding algebra and subalgebras. We shall assume some trivial propositions with arguments in text form. -/ -- We now need it to consider both ℝ² and X →ᵇ ℝ (BCF) as algebras. instance R_R2_scalar_mul : has_scalar ℝ (ℝ × ℝ) := ⟨λ β x, (β * x.1, β * x.2)⟩ -- We define the natural ring homomorphism from ℝ to ℝ² : β ↦ (β, β) def R_to_R2_hom : ℝ →+* ℝ × ℝ := ⟨λ β, (β, β), rfl, λ x y, rfl, rfl, λ x y, rfl⟩ instance : algebra ℝ (ℝ × ℝ) := { commutes' := λ r x, by simp [mul_comm], smul_def' := λ r x, rfl, .. R_R2_scalar_mul, .. R_to_R2_hom } /- While we find an algebra already constructed for BCF, it requires normed_algebra ℝ ℝ, so we will prove that here. As ℝ over ℝ is already an R-algebra, we just have to prove the isometry part which is true by definition. -/ instance : normed_algebra ℝ ℝ := ⟨λ x, rfl⟩ lemma subalgebra_nonempty (S : subalgebra ℝ (ℝ × ℝ)) : ∃ x, x ∈ S.carrier := ⟨1, S.2.2.1⟩ lemma subalgebra_closed_under_plus {S : subalgebra ℝ (ℝ × ℝ)} : ∀ (x y), x ∈ S.carrier → y ∈ S.carrier → x + y ∈ S.carrier := S.2.1.1.2 lemma subalgebra_closed_under_mul {S : subalgebra ℝ (ℝ × ℝ)} : ∀ (x y), x ∈ S.carrier → y ∈ S.carrier → x * y ∈ S.carrier := S.2.2.2 -- This should be true since a subalgebra is an algebra so it's closed under smul lemma subalgebra_closed_under_smul {S : subalgebra ℝ (ℝ × ℝ)} : ∀ (α : ℝ) {x}, x ∈ S.carrier → α • x ∈ S.carrier := sorry lemma non_zero_fst {S : subalgebra ℝ (ℝ × ℝ)} {β} (h : ((β, 0) : ℝ × ℝ) ∈ S.carrier) (hβ : β ≠ 0) : ∀ γ, ((γ, 0) : ℝ × ℝ) ∈ S.carrier := λ γ, begin convert subalgebra_closed_under_smul (γ / β) h, exact ((eq_div_iff hβ).mp rfl).symm, simp only [mul_zero] end lemma non_zero_snd {S : subalgebra ℝ (ℝ × ℝ)} {β} (h : ((0, β) : ℝ × ℝ) ∈ S.carrier) (hβ : β ≠ 0) : ∀ γ, ((0, γ) : ℝ × ℝ) ∈ S.carrier := λ γ, begin convert subalgebra_closed_under_smul (γ / β) h, simp only [mul_zero], exact ((eq_div_iff hβ).mp rfl).symm end /- The proof of this considers if β.1 ≠ β.2, β and β² are linearly independent and hence spans the entire space of ℝ² -/ lemma non_zero_fst_snd {S : subalgebra ℝ (ℝ × ℝ)} {β γ} (h₀ : (β : ℝ × ℝ) ∈ S.carrier) (hβ : β.1 ≠ 0) (h₁ : (γ : ℝ × ℝ) ∈ S.carrier) (hγ : γ.2 ≠ 0) (hβγ : β ≠ γ) : ∀ δ, δ ∈ S.carrier := sorry lemma non_zero_eq {S : subalgebra ℝ (ℝ × ℝ)} {β} (h : (β : ℝ × ℝ) ∈ S.carrier) (hβ : β.1 = β.2) (hnz : β ≠ 0): ∀ γ, ((γ, γ) : ℝ × ℝ) ∈ S.carrier := λ γ, begin have : β.1 ≠ 0 ∨ β.2 ≠ 0, by_contra hn, push_neg at hn, refine hnz (prod.ext hn.1 hn.2), cases this; convert subalgebra_closed_under_smul (γ / β.1) h; try { rw ←hβ at * }; exact (div_eq_iff this).mp rfl end /- We prove by considering all cases that a subalgebra of ℝ² must be a set of one of the indicated forms. -/ theorem subalgebra_of_R2 (S : subalgebra ℝ (ℝ × ℝ)) : S.carrier = {(0, 0)} ∨ S.carrier = {p | ∃ x : ℝ, p = (x, 0)} ∨ S.carrier = {p | ∃ y : ℝ, p = (0, y)} ∨ S.carrier = {p | ∃ z : ℝ, p = (z, z)} ∨ S.carrier = univ := begin by_cases (∀ s : ℝ × ℝ, s ∈ S.carrier → s.1 = s.2), { cases em (∀ s : ℝ × ℝ, s ∈ S.carrier → s = 0) with hz hnz, cases subalgebra_nonempty S with s hs, left, ext, split; intro hx, { exact hz _ hx }, { cases subalgebra_nonempty S with s hs, finish [hz _ hs] }, push_neg at hnz, cases hnz with s hs, iterate 3 { right }, left, ext, split; intro hx, { refine ⟨x.1, _⟩, apply prod.ext, refl, rw h x hx }, { cases hx with z hz, rw hz, exact non_zero_eq hs.1 (h s hs.1) hs.2 z} }, { push_neg at h, rcases h with ⟨s, hs₀, hs₁⟩, by_cases (s.1 = 0), rw h at hs₁, cases em (∃ (t : ℝ × ℝ) (ht : t ∈ S.carrier) (ht' : t ≠ s), t.1 ≠ 0) with ht ht, { rcases ht with ⟨t, ht₀, ht₁, ht₂⟩, iterate 4 { right }, ext, split; intro hx, exact mem_univ x, exact non_zero_fst_snd ht₀ ht₂ hs₀ hs₁.symm ht₁ x }, { push_neg at ht, iterate 2 { right }, left, ext, split; intro hx, cases em (x = s) with hxs hnxs, refine ⟨s.2, _⟩, rw [hxs, ←h], simp only [prod.mk.eta], refine ⟨x.2, _⟩, rw ←(ht x hx hnxs), simp only [prod.mk.eta], cases hx with p hp, rw hp, refine non_zero_snd _ hs₁.symm p, rw ←h, simp only [prod.mk.eta, hs₀] }, cases em (∃ (t : ℝ × ℝ) (ht : t ∈ S.carrier) (ht' : t ≠ s), t.2 ≠ 0) with ht ht, { rcases ht with ⟨t, ht₀, ht₁, ht₂⟩, iterate 4 { right }, ext, split; intro hx, exact mem_univ x, exact non_zero_fst_snd hs₀ h ht₀ ht₂ ht₁.symm x }, { push_neg at ht, right, left, ext, split; intro hx, cases em (x = s) with hxs hnxs, cases em (x.2 = 0) with hz hnz, refine ⟨x.1, _⟩, rw ←hz, simp only [prod.mk.eta, hs₀], exfalso, have hndouble : s + s ≠ s, suffices : s ≠ 0, simpa only [add_right_eq_self, ne.def], intro hs, cases hs, apply h, simp only [], have := ht (s + s) (subalgebra_closed_under_plus s s hs₀ hs₀) hndouble, have : s.2 = 0, simp at this, linarith [this], apply hnz, rwa hxs, refine ⟨x.1, _⟩, rw ←(ht x hx hnxs), simp only [prod.mk.eta, hs₀], cases hx with p hp, rw hp, cases em (s.2 = 0) with hsnd hsnd, refine non_zero_fst _ h p, rw ←hsnd, simp only [prod.mk.eta, hs₀], exfalso, have hndouble : s + s ≠ s, suffices : s ≠ 0, simpa only [add_right_eq_self, ne.def], intro hs, cases hs, apply h, simp only [], have := ht (s + s) (subalgebra_closed_under_plus s s hs₀ hs₀) hndouble, have : s.2 = 0, simp at this, linarith [this], contradiction } } end
76705835c2fe6eb0f96c7239b526a557567c07d2
2fbe653e4bc441efde5e5d250566e65538709888
/src/data/finsupp.lean
01e7045ec5de282262b6bf4d3435c730a1b27265
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
62,065
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 Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * ℕ →₀ α: Polynomials (where α is a ring) * (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names) * α →₀ ℕ: Multisets * α →₀ ℤ: Abelian groups freely generated by α * β →₀ α: Linear combinations over β where α is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use α →₀ β directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module noncomputable theory open_locale classical open finset variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*} {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (β : Type*) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[ext] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) := ⟨by rintros rfl a; refl, ext⟩ @[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h, by rw [hf, hg], by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ end basic section single variables [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) := assume b₁ b₂ eq, have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (injective_single a₂).eq_iff] at eq }, { rw [finsupp.ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end lemma single_right_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := ⟨λ H, by simpa [h, single_eq_single_iff] using H, λ H, by rw [H]⟩ lemma single_eq_zero : single a b = 0 ↔ b = 0 := ⟨λ h, by { rw ext_iff at h, simpa only [finsupp.single_eq_same, finsupp.zero_apply] using h a }, λ h, by rw [h, single_zero]⟩ lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) : (single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ := by simp [single_apply]; ac_refl lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) := by ext i; simp [unique.eq_default i] @[simp] lemma unique_single_eq_iff [unique α] {b' : β} : single a b = single a' b' ↔ b = b' := begin rw [single_eq_single_iff], split, { rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl }, { intro h, left, exact ⟨subsingleton.elim _ _, h⟩ } end end single section on_finset variables [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩) (assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ end on_finset section map_range variables [has_zero β₁] [has_zero β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 := finsupp.ext $ λ a, by simp [hf] lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} : map_range f hf (single a b) = single a (f b) := finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range section emb_domain variables [has_zero β] /-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported function whose value at `f a : α₂` is `v a`. For a `b : α₂` outside the range of `f` it is zero. -/ def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) }, { assume a₂, split_ifs, { simp [h], rw [← finsupp.not_mem_support_iff, not_not], apply finset.choose_mem }, { simp [h] } } end lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : (emb_domain f v).support = v.support.map f := rfl lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 := rfl lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α₁ → β) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (finsupp.not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := ⟨λ h, finsupp.ext $ λ a, by simpa [emb_domain_apply] using finsupp.ext_iff.1 h (f a), λ h, by rw h⟩ lemma emb_domain_map_range {β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂] (f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0) (h : l.emb_domain f = finsupp.single a b) : ∃ x, l = finsupp.single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = finset.singleton a, by rw [←finsupp.support_emb_domain, h, finsupp.support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp [h_map_support], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← finsupp.emb_domain_apply f l, h], by_cases h_cases : c = d, { simp [h_cases.symm, hc₂] }, { rw [finsupp.single_apply, finsupp.single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.inj (hc₂.trans hfd)) } }, { exact hc₂ } end end emb_domain section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with section erase def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.sum (λa, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.prod (λa, g a (f a)) @[to_additive] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[to_additive] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := rfl section nat_sub instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩ @[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl end nat_sub section add_monoid variables [add_monoid β] @[to_additive] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp only [h, h_zero, single_zero]; refl }, { simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton, prod_singleton, single_eq_same] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) := { map_add := λ _ _, add_apply, map_zero := zero_apply } lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[elab_as_eliminator] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma map_range_add [add_monoid β₁] [add_monoid β₂] {f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := finsupp.ext $ λ a, by simp [hf'] end add_monoid instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (f.support.sum_hom (λf : α →₀ β, f a₂)).symm lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this @[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := f.support.sum_hom (@has_neg.neg γ _) @[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl @[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ({a} : finset α).sum (λa', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset α) ⊆ f.support, { simpa only [finset.subset_iff, mem_singleton, forall_eq] }, refine (finset.sum_subset this (λ _ _ H, _)).symm, exact if_neg (mt mem_singleton.2 H) }, { transitivity (f.support.sum (λa, (0 : β))), { refine (finset.sum_congr rfl $ λ a' ha', if_neg _), rintro rfl, exact h ha' }, { rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } } end, ext $ assume a, by simp only [sum_apply, single_apply, this, insert_empty_eq_singleton, sum_singleton, if_pos] @[to_additive] lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, calc (f + g).support.prod (λa, h a ((f + g) a)) = (f.support ∪ g.support).prod (λa, h a ((f + g) a)) : finset.prod_subset support_add $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero] ... = (f.support ∪ g.support).prod (λa, h a (f a)) * (f.support ∪ g.support).prod (λa, h a (g a)) : by simp only [add_apply, h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa only [sub_self] using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa only [h_zero, zero_sub] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa only [h_neg, sub_neg_eq_add] using this, calc (f - g).sum h = (f + - g).sum h : rfl ... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg] ... = f.sum h - g.sum h : rfl @[to_additive] lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid β] [add_comm_monoid γ] (f : multiset (α →₀ β)) (h : α → β → γ) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (f.support.sum_hom _).symm lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (f.support.sum_hom multiset.sum).symm section map_range variables [add_comm_monoid β₁] [add_comm_monoid β₂] (f : β₁ → β₂) [hf : is_add_monoid_hom f] instance is_add_monoid_hom_map_range : is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) := { map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ } lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) : map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum := (m.sum_hom (map_range f hf.map_zero)).symm lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) : map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) := by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl end map_range section map_domain variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { simp only [(∉), (≠), not_not, mem_support_iff], assume h, rw [h, single_zero], refl } end lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive] lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) : function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end end map_domain section comap_domain noncomputable def comap_domain {α₁ α₂ γ : Type*} [has_zero γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ := { support := l.support.preimage hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) : comap_domain f l hf a = l (f a) := begin unfold_coes, unfold comap_domain, simp, refl end lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set): (comap_domain f l (set.inj_on_of_bij_on hf)).sum (g ∘ f) = l.sum g := begin unfold sum, haveI := classical.dec_eq α₂, simp only [comap_domain, comap_domain_apply, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) : comap_domain f l (set.inj_on_of_bij_on hf) = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ] (f : α₁ → α₂) (l : α₂ →₀ γ) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (set.inj_on_of_injective _ hf)) = l := begin ext a, haveI := classical.dec (a ∈ set.range f), by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl (finset.mem_coe.2 (mem_support_iff.2 (λ h, h_contr h.symm)))) } end end comap_domain /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the monoid of monomial exponents.) -/ instance [has_add α] [semiring β] : has_mul (α →₀ β) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) := ⟨single 0 1⟩ lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl section filter section has_zero variables [has_zero β] (p : α → Prop) (f : α →₀ β) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) $ λ a H, mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, if H : p a then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true] else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false] lemma filter_zero : (0 : α →₀ β).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : β} (h : p a) : (single a b).filter p = single a b := finsupp.ext $ λ x, begin by_cases h' : p x; simp [h'], rw single_eq_of_ne, rintro rfl, exact h' h end @[simp] lemma filter_single_of_neg {a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 := finsupp.ext $ λ x, begin by_cases h' : p x; simp [h'], rw single_eq_of_ne, rintro rfl, exact h h' end end has_zero lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := finsupp.ext $ assume a, if H : p a then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero] else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add] end filter section frange variables [has_zero β] def frange (f : α →₀ β) : finset β := finset.image f f.support theorem mem_frange {f : α →₀ β} {y : β} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange section subtype_domain variables {α' : Type*} [has_zero δ] {p : α → Prop} section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl instance subtype_domain.is_add_monoid_hom : is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma filter_add {v v' : α →₀ β} : (v + v').filter p = v.filter p + v'.filter p := ext $ λ a, by by_cases p a; simp [h] instance filter.is_add_monoid_hom (p : α → Prop) : is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) := { map_zero := filter_zero p, map_add := λ x y, filter_add } end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset γ) (f : γ → α →₀ β) : (s.sum f).filter p = s.sum (λa, filter p (f a)) := (s.sum_hom (filter p)).symm end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl end group end subtype_domain section multiset def to_multiset (f : α →₀ ℕ) : multiset α := f.sum (λa n, add_monoid.smul n {a}) lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _) lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} := by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) := { map_zero := to_multiset_zero, map_add := to_multiset_add } lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.card_zero, sum_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single, sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton, multiset.card_singleton, mul_one]; intros; refl } end lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, is_add_monoid_hom.map_smul (multiset.map g)], refl } end lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) : f.to_multiset.prod = f.prod (λa n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index, finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton, multiset.prod_singleton], { exact pow_zero a }, { exact pow_zero }, { exact pow_add } } end lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero hn, multiset.to_finset_smul _ _ hn, multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero], refl, refine disjoint_mono support_single_subset (subset.refl _) _, rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] } end @[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) : (f.support.sum_hom $ multiset.count a).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul] ... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl ... = f a * (a :: 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] def of_multiset (m : multiset α) : α →₀ ℕ := on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $ by_contradiction (mt multiset.count_eq_zero.2 H) @[simp] lemma of_multiset_apply (m : multiset α) (a : α) : of_multiset m a = m.count a := rfl def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) := ⟨ to_multiset, of_multiset, assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset], assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩ lemma mem_support_multiset_sum [add_comm_monoid β] {s : multiset (α →₀ β)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid β] {s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ lemma mem_support_single [has_zero β] (a a' : α) (b : β) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := ⟨λ H : (a ∈ ite _ _ _), if h : b = 0 then by rw if_pos h at H; exact H.elim else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩, λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩ end multiset section curry_uncurry protected def curry [add_comm_monoid γ] (f : (α × β) →₀ γ) : α →₀ (β →₀ γ) := f.sum $ λp c, single p.1 (single p.2 c) lemma sum_curry_index [add_comm_monoid γ] [add_comm_monoid δ] (f : (α × β) →₀ γ) (g : α → β → γ → δ) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ := f.sum $ λa g, g.sum $ λb c, single (a, b) c def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) : (f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, @filter_sum _ (α₂ →₀ β) _ p _ f.support _], rw [support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bind_singleton, refine finset.subset.trans support_sum _, refine finset.bind_mono (assume a _, support_single_subset) end end curry_uncurry section variables [add_monoid α] [semiring β] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] instance : semiring (α →₀ β) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end instance [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. finsupp.semiring } instance [add_monoid α] [ring β] : ring (α →₀ β) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.semiring } instance [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) := { mul_comm := mul_comm, .. finsupp.ring} lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}: single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [_root_.mul_zero, single_zero])) lemma prod_single [add_comm_monoid α] [comm_semiring β] {s : finset ι} {a : ι → α} {b : ι → β} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] section instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ variables (α β) @[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) := rfl instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) := { smul := (•), smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _, add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _, one_smul := λ x, finsupp.ext $ λ _, one_smul _ _, mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _, zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _, smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ } instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) := { ..finsupp.semimodule α β } instance [discrete_field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) := { ..finsupp.module α β } variables {α β} lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} : (b • g).support ⊆ g.support := λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _) section variables {α' : Type*} [has_zero δ] {p : α → Prop} @[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p := ext $ λ a, by by_cases p a; simp [h] end lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β] {f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v := begin change map_domain f (map_range _ _ _) = map_range _ _ _, apply finsupp.induction v, {simp}, intros a b v' hv₁ hv₂ IH, rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add, map_range_single, map_domain_single, map_domain_single, map_range_single]; apply smul_add end @[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β] (c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) := ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]] end @[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b • (v a) := rfl lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp only [finsupp.sum, finset.mul_sum] protected lemma eq_zero_of_zero_eq_one (zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 := by ext i; simp [eq_zero_of_zero_eq_one β zero_eq_one (l i)] end def restrict_support_equiv [add_comm_monoid β] (s : set α) : {f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):= begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) := ⟨map_domain e, map_domain e.symm, begin assume v, simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply], exact map_domain_id end, begin assume v, simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply], exact map_domain_id end⟩ section sigma variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β) noncomputable def split (i : ι) : αs i →₀ β := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin classical, rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp end noncomputable def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw mem_split_support_iff_nonzero, haveI := classical.dec, rwa not_iff_not, exact hg _ _, end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp [finset.ext, split_support, split, comap_domain]; tauto lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) : l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) := by simp [sum, sigma_support, sum_sigma,split_apply] end sigma end finsupp namespace multiset def to_finsupp (s : multiset α) : α →₀ ℕ := { support := s.to_finset, to_fun := λ a, s.count a, mem_support_to_fun := λ a, begin rw mem_to_finset, convert not_iff_not_of_iff (count_eq_zero.symm), rw not_not end } @[simp] lemma to_finsupp_support (s : multiset α) : s.to_finsupp.support = s.to_finset := rfl @[simp] lemma to_finsupp_apply (s : multiset α) (a : α) : s.to_finsupp a = s.count a := rfl @[simp] lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := finsupp.ext $ λ a, count_zero a @[simp] lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := finsupp.ext $ λ a, count_add a s t lemma to_finsupp_singleton (a : α) : to_finsupp {a} = finsupp.single a 1 := finsupp.ext $ λ b, if h : a = b then by simp [finsupp.single_apply, h] else begin rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero, singleton_eq_singleton, mem_singleton], rintro rfl, exact h rfl end namespace to_finsupp instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) := { map_zero := to_finsupp_zero, map_add := to_finsupp_add } end to_finsupp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply] end multiset namespace finsupp variables {σ : Type*} instance [preorder α] [has_zero α] : preorder (σ →₀ α) := { le := λ f g, ∀ s, f s ≤ g s, le_refl := λ f s, le_refl _, le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) } instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) := { le_antisymm := λ f g hfg hgf, finsupp.ext $ λ s, le_antisymm (hfg s) (hgf s), .. finsupp.preorder } instance [ordered_cancel_comm_monoid α] : add_left_cancel_semigroup (σ →₀ α) := { add_left_cancel := λ a b c h, finsupp.ext $ λ s, by { rw finsupp.ext_iff at h, exact add_left_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_comm_monoid α] : add_right_cancel_semigroup (σ →₀ α) := { add_right_cancel := λ a b c h, finsupp.ext $ λ s, by { rw finsupp.ext_iff at h, exact add_right_cancel (h s) }, .. finsupp.add_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (σ →₀ α) := { add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s), le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s), .. finsupp.add_comm_monoid, .. finsupp.partial_order, .. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup } lemma le_iff [canonically_ordered_monoid α] (f g : σ →₀ α) : f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s := ⟨λ h s hs, h s, λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩ @[simp] lemma add_eq_zero_iff [canonically_ordered_monoid α] (f g : σ →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := begin split, { assume h, split, all_goals { ext s, suffices H : f s + g s = 0, { rw add_eq_zero_iff at H, cases H, assumption }, show (f + g) s = 0, rw h, refl } }, { rintro ⟨rfl, rfl⟩, simp } end attribute [simp] to_multiset_zero to_multiset_add @[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) : f.to_multiset.to_finsupp = f := ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset] lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) := λ m n h, begin rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂, split, { rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s }, { intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H, simpa using H } end lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [← card_to_multiset, ← card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (σ) /-- The order on σ →₀ ℕ is well-founded.-/ lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) := λ m n, by rw le_iff; apply_instance variable {σ} def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} : p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f := begin erw [multiset.mem_to_finset, multiset.mem_map], split, { rintros ⟨⟨a, b⟩, h, rfl⟩, rw multiset.mem_antidiagonal at h, simpa using congr_arg multiset.to_finsupp h }, { intro h, refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩, { simpa using congr_arg to_multiset h }, { rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 := by rw [← multiset.to_finsupp_singleton]; refl lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) : f.swap ∈ (antidiagonal n).support := by simpa [mem_antidiagonal_support, add_comm] using hf end finsupp
714f8fca0e9cce3943fda09cc90c7c70b1aadb37
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/topology/algebra/infinite_sum.lean
f08eb1dc86a72340be96793eec522ad06c15dbb0
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,179
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.big_operators.intervals import topology.instances.real import topology.algebra.module import data.indicator_function import data.equiv.encodable.lattice import order.filter.at_top_bot /-! # Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open finset filter function classical open_locale topological_space classical big_operators variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 notation `∑'` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : (∑'b, f b) = 0 := by simp [tsum, h] lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator] @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) (g : α →+ γ) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ g.map_sum _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) (g : α →+ γ) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := ⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩ variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum.add] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum end has_sum section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : (∑'b, f b) = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ (∑'b, f b) = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_zero : (∑'b:β, 0:α) = 0 := has_sum_zero.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑'b, f b) = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma tsum_fintype [fintype β] (f : β → α) : (∑'b, f b) = ∑ b, f b := (has_sum_fintype f).tsum_eq @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : (∑'x : {x // x ∈ s}, f x) = ∑ x in s, f x := (s.has_sum f).tsum_eq lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑'b, f b) = f b := (has_sum_single b hf).tsum_eq @[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑'b', if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : (∑' b, f b) = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : (∑'b, f b) = (∑'c, g c) := (equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : (∑'c, f (j c)) = (∑'b, f b) := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg lemma tsum_subtype (s : set β) (f : β → α) : (∑' x : s, f x) = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : (∑'b, f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : (∑'b, ∑ i in s, f i b) = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : (∑'p, f p) = (∑'b c, f (b, c)) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : (∑' c b, f b c) = (∑' b c, f b c) := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq], refl, assumption end end has_continuous_add section encodable open encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode2 [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : (∑' i : ℕ, m (⨆ b ∈ decode2 γ i, s b)) = (∑' b : γ, m (s b)) := begin have H : ∀ n, m (⨆ b ∈ decode2 γ n, s b) ≠ 0 → (decode2 γ n).is_some, { intros n h, cases decode2 γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek2] at h ⊢, convert h, simp [set.ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode2 γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode2 (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : (∑' i, m (⋃ b ∈ decode2 γ i, s b)) = (∑' b, m (s b)) := tsum_supr_decode2 m m0 s /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ /-- If a function is countably sub-additive then it is sub-additive on encodable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : γ → β) : R (m (⨆ b : γ, s b)) (∑' b : γ, m (s b)) := by { rw [← supr_decode2, ← tsum_supr_decode2 _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _, rw [← finset.tsum_subtype], assumption } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end encodable end tsum section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp [has_sum, tendsto_pi] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp [summable, pi.has_sum, classical.skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : (∑'b, - f b) = - (∑'b, f b) := hf.has_sum.neg.tsum_eq lemma tsum_sub (hf : summable f) (hg : summable g) : (∑'b, f b - g b) = (∑'b, f b) - (∑'b, g b) := (hf.has_sum.sub hg.has_sum).tsum_eq lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm end tsum /-! ### Sums on subtypes If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype `univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`. -/ section subtype variables {s : finset β} lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i) := by simpa [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : (∑'b, f b) = f 0 + (∑'b, f (b + 1)) := by simpa only [range_one, sum_singleton] using (sum_add_tsum_nat_add 1 hf).symm end subtype end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) := by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id) lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const) lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) := (hf.has_sum.mul_left _).summable lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) := (hf.has_sum.mul_right _).summable section tsum variables [t2_space α] lemma tsum_mul_left (a) (hf : summable f) : (∑'b, a * f b) = a * (∑'b, f b) := (hf.has_sum.mul_left _).tsum_eq lemma tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a := (hf.has_sum.mul_right _).tsum_eq end tsum end topological_semiring section topological_semimodule variables {R : Type*} [semiring R] [topological_space R] [topological_space α] [add_comm_monoid α] [semimodule R α] [topological_semimodule R α] {f : β → α} lemma has_sum.smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) := hf.map (const_smul_hom α r) (continuous_const.smul continuous_id) lemma summable.smul {r : R} (hf : summable f) : summable (λ z, r • f z) := hf.has_sum.smul.summable lemma tsum_smul [t2_space α] {r : R} (hf : summable f) : (∑' z, r • f z) = r • (∑' z, f z) := hf.has_sum.smul.tsum_eq end topological_semimodule section division_ring variables [division_ring α] [topological_space α] [topological_semiring α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) := ⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a₂⁻¹⟩ lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) := ⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a₂⁻¹⟩ lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) := ⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a⁻¹⟩ lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) := ⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a⁻¹⟩ end division_ring section order_topology variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf, { exact assume c₁ c₂ eq, hi eq }, { intros c hc, rw [mem_support] at hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨⟨b, hc⟩, eq⟩ } }, { assume c, simp [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj i hi hs h hf.has_sum hg.has_sum lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : ∑ b in s, f b ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a := calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : ∑ b in s, f b ≤ tsum f := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b := le_has_sum (summable.has_sum hf) b hb lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑'b, f b) ≤ (∑'b, g b) := has_sum_le h hf.has_sum hg.has_sum lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ (∑'b, g b) := begin by_cases hg : summable g, { simpa using tsum_le_tsum h summable_zero hg }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : (∑'b, f b) ≤ 0 := begin by_cases hf : summable f, { simpa using tsum_le_tsum h hf summable_zero}, { simp [tsum_eq_zero_of_not_summable hf] } end end order_topology section canonically_ordered variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] variables {f : β → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a := le_has_sum hf b $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b := le_tsum hf b $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx) (le_has_sum' h x)) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : (∑' i, f i) = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] end canonically_ordered section uniform_group variables [add_comm_group α] [uniform_space α] lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [regular_space α] {f : β × γ → α} (h : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) := tsum_prod' h h.prod_factor lemma tsum_comm [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : (∑' c b, f b c) = (∑' b c, f b c) := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (singleton_disjoint.2 hx) end end topological_group lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β] [uniform_add_group β] [complete_space β] {f : α → β} : summable (λ x, abs (f x)) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, abs (f x) = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, abs (f x) = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, abs (f x)) ↔ summable (λ x : {x | 0 ≤ f x}, abs (f x)) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, abs (f x)) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, rw edist_comm, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) := let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq, refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ abs (∑ x in Ico N n, d x) : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_at_top.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact hd.comp_injective (add_right_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
04ac7a312d48db4ff22002066b2701311fdf43d2
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.28.lean
4709384abfca87e7872c8812db0b5fd5308f0b8c
[]
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
301
lean
import standard import data.nat open nat example (x : ℕ) (H : x ≠ 0) : succ (pred x) = x := begin revert H, cases x, -- first goal: ⊢ 0 ≠ 0 → succ (pred 0) = 0 { intro H1, apply (absurd rfl H1)}, -- second goal: ⊢ succ a ≠ 0 → succ (pred (succ a)) = succ a { intro H1, apply rfl} end
c0a846ae9dbc88dfd9fe5c23131750fb7f6292ce
de8d0cdc3dc15aa390280472764229d0e14e734c
/src/topological_spaces.lean
79e86102756bd9a2c337b76d60a80afaa3c250ff
[]
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,722
lean
import tactic import data.set.finite open set -- Definition d'un espace topologique : @[ext] class topological_space (X : Type) := (is_open : set X → Prop) (univ_mem : is_open univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ {A B : set X} (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) namespace topological_space -- Fermés : def is_closed {X : Type} [topological_space X] : set X → Prop := λ F, is_open (compl F) -- Preuve que l'ensemble vide est un ouvert à partir des autres axiomes : lemma empty_mem {X : Type} [topological_space X] : is_open (∅ : set X) := begin have : (∅ : set X) = ⋃₀ ∅, simp, rw this, apply union, intros b hb, exfalso, exact hb, end -- Toute intersection finie d'ouverts est un ouvert : lemma finite_inter {X : Type} [topological_space X] : ∀ (B : set (set X)) (hB : finite B) (h : ∀ b ∈ B, is_open b), is_open (⋂₀ B) := begin intros b hB, apply finite.induction_on hB, simp, exact univ_mem, intros a s ha hs h1 h2, have clef : ⋂₀insert a s = ⋂₀s ∩ a, { apply le_antisymm, { intros x hx, split, intros b hb, apply hx, right, exact hb, apply hx, left, refl, }, { intros x hx, intros b hb, cases hb with hb1 hb2, rw hb1, exact hx.2, exact hx.1 b hb2, }, }, rw clef, apply inter, { apply h1, intros b hb, apply h2 b, right, exact hb, }, { apply h2 a, left, refl, }, end -- Topologie discrete : def discrete (X : Type) : topological_space X := { is_open := λ U, true, univ_mem := trivial, union := begin intros B h, trivial, end, inter := begin intros A hA B hB, trivial, end } -- Definition d'un espace discret : class discrete_space (X : Type) [topological_space X] := (all_open : ∀ U : set X, is_open U) -- Topologie engendrée par un ensemble de parties : inductive generated_open (X : Type) (g : set (set X)) : set X → Prop | generator : ∀ A ∈ g, generated_open A | inter : ∀ A B, generated_open A → generated_open B → generated_open (A ∩ B) | union : ∀ (B : set (set X)), (∀ b ∈ B, generated_open b) → generated_open (⋃₀ B) | univ : generated_open univ def generate_from (X : Type) (g : set (set X)) : topological_space X := { is_open := generated_open X g, univ_mem := generated_open.univ, inter := generated_open.inter, union := generated_open.union } -- Topologie grossière : def indiscrete (X : Type) : topological_space X := generate_from X {∅, univ} end topological_space open topological_space -- Topologie produit : instance prod.topological_space (X Y : Type) [topological_space X] [topological_space Y] : topological_space (X × Y) := topological_space.generate_from (X × Y) {U | ∃ (Ux : set X) (Uy : set Y) (hx : is_open Ux) (hy : is_open Uy), U = set.prod Ux Uy} -- Les ouverts pour la topologie produit sont les réunions d'ouverts élémentaires : lemma is_open_prod_iff {X Y : Type} [topological_space X] [topological_space Y] {s : set (X × Y)} : 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 split, { intros hyp a b hab, induction hyp with U hU A B hA1 hB1 hA2 hB2 C hC1 hC2, { rcases hU with ⟨ Ux, Uy, hx, hy, hs ⟩, rw hs at hab, use [Ux, Uy, hx, hy, hab.1, hab.2], rw hs, }, { rcases hA2 hab.1 with ⟨u1, v1, ⟨h1a, h1b, h1c, h1d, h1e⟩⟩, rcases hB2 hab.2 with ⟨u2, v2, ⟨h2a, h2b, h2c, h2d, h2e⟩⟩, refine ⟨u1 ∩ u2, v1 ∩ v2, inter h1a h2a, inter h1b h2b, ⟨h1c, h2c⟩, ⟨h1d, h2d⟩,_⟩, intros uv huv, split, apply h1e, split, exact huv.1.1, exact huv.2.1, apply h2e, split, exact huv.1.2, exact huv.2.2, }, { rcases hab with ⟨c, hcC, habc ⟩, rcases hC2 c hcC habc with ⟨u, v, ⟨ha, hb, hc, hd, he⟩⟩, use [u, v, ha, hb, hc, hd], intros uv huv, use c, split, exact hcC, exact he huv, }, { use [univ, univ], simp, split; exact univ_mem, }, }, { intro hyp, choose f1 f2 hfa hfb hfc hfd hfe using hyp, have clef : s = ⋃₀ {(f1 a b hab).prod (f2 a b hab) | (a : X) (b : Y) (hab : (a, b) ∈ s)}, { apply le_antisymm, { rintros ⟨a, b⟩ hab, use ((f1 a b hab).prod (f2 a b hab)), use [a, b, hab, hfc a b hab, hfd a b hab], }, { rintros uv ⟨ UV, ⟨ ⟨a, b, hab, h⟩, huv ⟩⟩, rw ← h at huv, exact (hfe a b hab) huv }, }, rw clef, apply union, rintros UV ⟨a, b, hab, h⟩, rw ← h, apply generated_open.generator, use [f1 a b hab, f2 a b hab, hfa a b hab, hfb a b hab], }, end namespace topological_space -- Definition d'une topologie à partir de ses fermés : def mk_closed_sets (X : Type) (σ : set (set X)) (empty_mem : ∅ ∈ σ) (univ_mem : univ ∈ σ) (inter : ∀ B ⊆ σ, ⋂₀ B ∈ σ) (union : ∀ (A ∈ σ) (B ∈ σ), A ∪ B ∈ σ) : topological_space X := { is_open := λ U, U ∈ compl '' σ, univ_mem := begin apply (mem_compl_image _ _).2, rw compl_univ, exact empty_mem end, union := begin intros B hB, apply (mem_compl_image _ _).2, rw compl_sUnion, apply inter, intros cb hcb, rw ← compl_compl cb, exact (mem_compl_image _ _).1 (hB (compl cb) ((mem_compl_image _ _).1 hcb)), end, inter := begin intros A B hA hB, apply (mem_compl_image _ _).2, rw compl_inter, exact union (compl A) ((mem_compl_image _ _).1 hA) (compl B) ((mem_compl_image _ _).1 hB), end, } end topological_space
c0d84c20a6a675bfa1570cc51975ba4454427580
367134ba5a65885e863bdc4507601606690974c1
/src/group_theory/congruence.lean
67e9bc912e59ae79121bc8ceb231e9829b8ed4a8
[ "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
44,062
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient of a type with decidable equality by a congruence relation also has decidable equality. -/ @[to_additive "The quotient of a type with decidable equality by an additive congruence relation also has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_coe {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected noncomputable def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, 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, λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end end -- Monoids section monoids variables {M} [monoid M] [monoid N] [monoid P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid : monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {α : Type*} [comm_monoid α] (c : con α) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) 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⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨λ ⟨y, hy⟩, by revert hy; rcases y; exact λ hy, ⟨y, hy.1, by rw [hy.2.symm, ←lift_coe H]; refl⟩, λ ⟨y, hy⟩, ⟨↑y, hy.1, by rw ←hy.2; refl⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hzm, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism."] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective (ker_lift f) ⟨ker_lift_injective f, lift_surjective_of_surjective (le_refl _) hf⟩ } /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end monoids section groups variables {M} [group M] [group N] [group P] (c : con M) /-- Multiplicative congruence relations preserve inversion. -/ @[to_additive "Additive congruence relations preserve negation."] protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ := λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹)) /-- The inversion induced on the quotient by a congruence relation on a type with a inversion. -/ @[to_additive "The negation induced on the quotient by an additive congruence relation on a type with an negation."] instance has_inv : has_inv c.quotient := ⟨λ x, quotient.lift_on' x (λ w, ((w⁻¹ : M) : c.quotient)) $ λ x y h, c.eq.2 $ c.inv h⟩ /-- The quotient of a group by a congruence relation is a group. -/ @[to_additive "The quotient of an `add_group` by an additive congruence relation is an `add_group`."] instance group : group c.quotient := { inv := λ x, x⁻¹, mul_left_inv := λ x, show x⁻¹ * x = 1, from quotient.induction_on' x $ λ _, congr_arg coe $ mul_left_inv _, .. con.monoid c} end groups end con
af901981b3a93473c155624a28c2baaec2beadd9
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Elab/MutualDef.lean
7c672f8e427353069d242325c9e7ba4d69168943
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,306
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 import Lean.Meta.Closure import Lean.Meta.Check import Lean.Elab.Command import Lean.Elab.DefView import Lean.Elab.PreDefinition import Lean.Elab.DeclarationRange namespace Lean.Elab open Lean.Parser.Term /- DefView after elaborating the header. -/ structure DefViewElabHeader where ref : Syntax modifiers : Modifiers kind : DefKind shortDeclName : Name declName : Name levelNames : List Name numParams : Nat type : Expr -- including the parameters valueStx : Syntax deriving Inhabited namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | Exception.error ref msg => throw (Exception.error ref m!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" private def elabFunType {α} (ref : Syntax) (xs : Array Expr) (view : DefView) (k : Array Expr → Expr → TermElabM α) : TermElabM α := do match view.type? with | some typeStx => elabTypeWithAutoBoundImplicit typeStx fun type => do synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type registerFailedToInferDefTypeInfo type typeStx k xs (← mkForallFVars xs type) | none => let hole := mkHole ref let type ← elabType hole registerFailedToInferDefTypeInfo type ref k xs (← mkForallFVars xs type) def isAutoImplicit (fvarId : FVarId) : TermElabM Bool := return (← read).autoBoundImplicits.any fun x => x.fvarId! == fvarId private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let mut headers := #[] for view in views do let newHeader ← withRef view.ref do let ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers addDeclarationRanges declName view.ref applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration withDeclName declName <| withAutoBoundImplicitLocal <| withLevelNames levelNames <| elabBinders (catchAutoBoundImplicit := true) view.binders.getArgs fun xs => do let refForElabFunType := view.value elabFunType refForElabFunType xs view fun xs type => do let mut type ← mkForallFVars (← read).autoBoundImplicits.toArray type let xs ← addAutoBoundImplicits xs let levelNames ← getLevelNames if view.type?.isSome then Term.synthesizeSyntheticMVarsNoPostponing type ← instantiateMVars type let pendingMVarIds ← getMVars type discard <| logUnassignedUsingErrorInfos pendingMVarIds let newHeader := { ref := view.ref, modifiers := view.modifiers, kind := view.kind, shortDeclName := shortDeclName, declName := declName, levelNames := levelNames, numParams := xs.size, type := type, valueStx := view.value : DefViewElabHeader } check headers newHeader pure newHeader headers := headers.push newHeader pure headers private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def expandWhereDeclsAsStructInst : Macro | `(whereDecls|where $[$decls:letRecDecl$[;]?]*) => do let letIdDecls ← decls.mapM fun stx => match stx with | `(letRecDecl|$attrs:attributes $decl:letDecl) => Macro.throwErrorAt stx "attributes are 'where' elements are currently not supported here" | `(letRecDecl|$decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here" | `(letRecDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl | `(letRecDecl|$decl:letIdDecl) => pure decl | _ => unreachable! let structInstFields ← letIdDecls.mapM fun | stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do let mut val := val if let some ty := ty? then val ← `(($val : $ty)) val ← `(fun $[$binders]* => $val:term) `(structInstField|$id:ident := $val) | _ => unreachable! `({ $[$structInstFields,]* }) | _ => unreachable! /- Recall that ``` def declValSimple := parser! " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := parser! Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do if declVal.isOfKind `Lean.Parser.Command.declValSimple then expandWhereDeclsOpt declVal[2] declVal[1] else if declVal.isOfKind `Lean.Parser.Command.declValEqns then expandMatchAltsWhereDecls declVal[0] else if declVal.isOfKind `Lean.Parser.Term.whereDecls then expandWhereDeclsAsStructInst declVal else Macro.throwErrorAt declVal "unexpected definition value" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do let valStx ← liftMacroM $ declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State TermElabM Unit := do headers.forM fun header => collectUsedFVars header.type values.forM collectUsedFVars toLift.forM fun letRecToLift => do collectUsedFVars letRecToLift.type collectUsedFVars letRecToLift.val private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts $ k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type := type, val := val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId _) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← findLocalDecl? fvarId) with | some decl => pure decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => pure n /- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt! toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := NameMap NameSet /- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : UsedFVarsMap := do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set pure usedFVarMap /- The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State where usedFVarsMap : UsedFVarsMap := {} modified : Bool := false abbrev M := ReaderT (List FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : NameSet) : M NameSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then pure s₁ else markModified pure $ s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => pure () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => if fvarId == fvarId' then pure fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => pure fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := NameMap (Array FVarId) private def mkFreeVarMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := do let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds pure freeVarMap structure ClosureState where newLocalDecls : Array LocalDecl := #[] localDecls : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] exprArgs : Array Expr := #[] private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl arbitrary fvarId userName type bi, exprArgs := s.exprArgs.push (mkFVar fvarId) } pure $ pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => pure () | some fvarId => trace[Elab.definition.mkClosure]! "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => let toProcess ← pushLocalDecl toProcess fvarId userName type bi mkClosureForAux toProcess | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl arbitrary fvarId userName type val false, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val), localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls } pure { s with newLocalDecls := s.newLocalDecls.reverse, newLetDecls := s.newLetDecls.reverse, exprArgs := s.exprArgs.reverse } structure LetRecClosure where ref : Syntax localDecls : Array LocalDecl closed : Expr -- expression used to replace occurrences of the let-rec FVarId toLift : LetRecToLift private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId! let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs assignExprMVar toLift.mvarId c return { ref := toLift.ref localDecls := s.newLocalDecls closed := c toLift := { toLift with val := val, type := type } } private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) := letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get! /- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := NameMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert (mainFVars.get! i).fvarId! (mkAppN (Lean.mkConst (mainHeaders.get! i).declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | Expr.fvar fvarId _ => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i] let val ← mkLambdaFVars sectionVars mainVals[i] let type ← mkForallFVars sectionVars header.type return preDefs.push { ref := getDeclarationSelectionRef header.ref kind := header.kind declName := header.declName levelParams := [], -- we set it later modifiers := header.modifiers type := type value := val } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition := letRecClosures.foldl (init := preDefs) fun preDefs c => let type := Closure.mkForall c.localDecls c.toLift.type let val := Closure.mkLambda c.localDecls c.toLift.val preDefs.push { ref := c.ref kind := kind declName := c.toLift.declName levelParams := [] -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs } type := type value := val } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable, isPartial := mainHeaders.any fun h => h.modifiers.isPartial, isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mctx ← getMCtx let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val let letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM (instantiateMVars ·) let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] def elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing if isExample views then pure () else let values ← values.mapM (instantiateMVars ·) let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift let preDefs ← levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames addPreDefinitions preDefs end Term namespace Command def elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] mkDefView modifiers d[1] runTermElabM none fun vars => Term.elabMutualDef vars views end Command end Lean.Elab
e78ca0efe784337933df001f799a24fd3cf880ca
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/expressions/boolean.lean
d8bf24b5902f32946fc771d24972c7a7ec4e0a00
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
667
lean
/- We have a better version of this. To be replaced. -/ inductive bvar : Type | mk (n : ℕ) def bvar_eq : bvar → bvar → bool | (bvar.mk n1) (bvar.mk n2) := n1=n2 inductive bExpr : Type | BLit (b: bool) | BVar (v: bvar) def benv := bvar → bool def bEval : bExpr → benv → bool | (bExpr.BLit b) i := b | (bExpr.BVar v) i := i v def update_benv : benv → bvar → bool → benv | i v b := λ v2, if (bvar_eq v v2) then b else (i v2) inductive bCmd : Type | bAssm (v : bvar) (e : bExpr) | bSeq (c1 c2 : bCmd) def cEval : benv → bCmd → benv | i0 (bCmd.bAssm v e) := update_benv i0 v (bEval e i0) | i0 (bCmd.bSeq c1 c2) := (cEval (cEval i0 c1) c2)
7cad00d36083da0e05be4e57b06bb275f851ec68
761d983a78bc025071bac14a3facced881cf5e53
/new_affine/affine_with_frame.lean
ccf0aa033b819aea83eb6ea0ec48c5609920c731
[]
no_license
rohanrajnair/affine_lib
bcf22ff892cf74ccb36a95bc9b7fff8e0adb2d0d
83076864245ac547b9d615bc6a23804b1b4a8f70
refs/heads/master
1,673,320,928,343
1,603,036,653,000
1,603,036,653,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,878
lean
import tactic.ext linear_algebra.affine_space.basic import algebra.module linear_algebra.basis universes u v w variables (X : Type u) (K : Type v) (V : Type w) (ι : Type*) [ring K] [add_comm_group V] [module K V] variables (s : finset ι) (g : ι → K) (v : ι → V) [is_basis K v] [affine_space V X] open_locale big_operators def affine_combination (g_add : ∑ i in s, g i = 1) := ∑ i in s, g i • v i def barycenter (g_add : ∑ i in s, g i = 1) := g -- TODO: want to coerce g to be a list? structure affine_frame := (ref_pt : X) (vec : ι → V) (basis : is_basis K vec) namespace aff_fr @[ext] structure vec_with_frame (frame : affine_frame X K V ι) := (vec : V) structure pt_with_frame (frame : affine_frame X K V ι) := (pt : X) variables (basis : affine_frame X K V ι) (pt : X) def vecf_add : vec_with_frame X K V ι basis → vec_with_frame X K V ι basis → vec_with_frame X K V ι basis := λ x y, ⟨x.1 + y.1⟩ def vecf_neg : vec_with_frame X K V ι basis → vec_with_frame X K V ι basis := λ x, ⟨-x.1⟩ def vecf_scalar : K → vec_with_frame X K V ι basis → vec_with_frame X K V ι basis := λ c x, ⟨c • x.1⟩ instance : has_add (vec_with_frame X K V ι basis) := ⟨vecf_add X K V ι basis⟩ instance : has_neg (vec_with_frame X K V ι basis) := ⟨vecf_neg X K V ι basis⟩ instance vec_has_zero : has_zero V := by refine add_monoid.to_has_zero V def vecf_zero : vec_with_frame X K V ι basis := ⟨(aff_fr.vec_has_zero V).zero⟩ instance : has_zero (vec_with_frame X K V ι basis) := ⟨vecf_zero X K V ι basis⟩ instance : has_scalar K (vec_with_frame X K V ι basis) := ⟨vecf_scalar X K V ι basis⟩ #print add_comm_group lemma vadd_assoc : ∀ x y z : vec_with_frame X K V ι basis, x + y + z = x + (y + z) := begin intros, cases x, cases y, cases z, ext, exact add_assoc x y z, end lemma vzero_add : ∀ x : vec_with_frame X K V ι basis, 0 + x = x := begin intros, cases x, ext, exact zero_add x, end lemma vadd_zero : ∀ x : vec_with_frame X K V ι basis, x + 0 = x := begin intros, cases x, ext, exact add_zero x, end lemma vadd_left_neg : ∀ x : vec_with_frame X K V ι basis, -x + x = 0 := begin intros, cases x, ext, exact add_left_neg x, end lemma vadd_comm : ∀ x y : vec_with_frame X K V ι basis, x + y = y + x := begin intros, cases x, cases y, ext, exact add_comm x y, end instance : add_comm_group (vec_with_frame X K V ι basis) := ⟨ vecf_add X K V ι basis, vadd_assoc X K V ι basis, vecf_zero X K V ι basis, vzero_add X K V ι basis, vadd_zero X K V ι basis, vecf_neg X K V ι basis, vadd_left_neg X K V ι basis, vadd_comm X K V ι basis ⟩ #print vector_space #print semimodule instance : module K (vec_with_frame X K V ι basis) := sorry instance : affine_space (vec_with_frame X K V ι basis) (pt_with_frame X K V ι basis) := sorry end aff_fr
116c8c1e20bb1a77d573dd0dd1b072ec730a68d0
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/Meta.lean
9e6bdf7ceb58b32b058df004f603dcac8b65f13b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
45,739
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic import Init.Data.Option.BasicAux namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private opaque version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private opaque version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private opaque version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () @[extern "lean_get_githash"] opaque getGithash (u : Unit) : String def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] opaque version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] opaque version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () def versionStringCore := toString version.major ++ "." ++ toString version.minor ++ "." ++ toString version.patch def versionString := if version.specialDesc ≠ "" then versionStringCore ++ "-" ++ version.specialDesc else if version.isRelease then versionStringCore else versionStringCore ++ ", commit " ++ githash def origin := "leanprover/lean4" def toolchain := if version.specialDesc ≠ "" then if version.isRelease then origin ++ ":" ++ versionStringCore ++ "-" ++ version.specialDesc else origin ++ ":" ++ version.specialDesc else if version.isRelease then origin ++ ":" ++ versionStringCore else "" @[extern c inline "LEAN_IS_STAGE0"] opaque Internal.isStage0 (u : Unit) : Bool /-- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _) => n | n@(num anonymous _) => n | str n _ => getRoot n | num n _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s => s.contains '✝' || s == "_inaccessible" | Name.num p _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst (s.get 0) && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s => maybeEscape s | num anonymous v => toString v | str n s => toStringWithSep n ++ sep ++ maybeEscape s | num n v => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let .str _ s := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString private def hasNum : Name → Bool | anonymous => false | num .. => true | str p .. => hasNum p protected def reprPrec (n : Name) (prec : Nat) : Std.Format := match n with | anonymous => Std.Format.text "Lean.Name.anonymous" | num p i => Repr.addAppParen ("Lean.Name.mkNum " ++ Name.reprPrec p max_prec ++ " " ++ repr i) prec | str p s => if p.hasNum then Repr.addAppParen ("Lean.Name.mkStr " ++ Name.reprPrec p max_prec ++ " " ++ repr s) prec else Std.Format.text "`" ++ n.toString instance : Repr Name where reprPrec := Name.reprPrec deriving instance Repr for Syntax def capitalize : Name → Name | .str p s => .str p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- `eraseSuffix? n s` return `n'` if `n` is of the form `n == n' ++ s`. -/ def eraseSuffix? : Name → Name → Option Name | n, anonymous => some n | str p s, str p' s' => if s == s' then eraseSuffix? p p' else none | num p s, num p' s' => if s == s' then eraseSuffix? p p' else none | _, _ => none /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s => Name.mkStr p (pre ++ s) | num p n => Name.mkNum (Name.mkStr p pre) n protected theorem beq_iff_eq {m n : Name} : m == n ↔ m = n := by show m.beq n ↔ _ induction m generalizing n <;> cases n <;> simp_all [Name.beq, And.comm] instance : LawfulBEq Name where eq_of_beq := Name.beq_iff_eq.1 rfl := Name.beq_iff_eq.2 rfl instance : DecidableEq Name := fun a b => if h : a == b then .isTrue (by simp_all) else .isFalse (by simp_all) end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax abbrev Term := TSyntax `term abbrev Command := TSyntax `command protected abbrev Level := TSyntax `level abbrev Prec := TSyntax `prec abbrev Prio := TSyntax `prio abbrev Ident := TSyntax identKind abbrev StrLit := TSyntax strLitKind abbrev CharLit := TSyntax charLitKind abbrev NameLit := TSyntax nameLitKind abbrev ScientificLit := TSyntax scientificLitKind abbrev NumLit := TSyntax numLitKind end Syntax export Syntax (Term Command Prec Prio Ident StrLit CharLit NameLit ScientificLit NumLit) namespace TSyntax instance : Coe (TSyntax [k]) (TSyntax (k :: ks)) where coe stx := ⟨stx⟩ instance : Coe (TSyntax ks) (TSyntax (k' :: ks)) where coe stx := ⟨stx⟩ instance : Coe Ident Term where coe s := ⟨s.raw⟩ instance : CoeDep Term ⟨Syntax.ident info ss n res⟩ Ident where coe := ⟨Syntax.ident info ss n res⟩ instance : Coe StrLit Term where coe s := ⟨s.raw⟩ instance : Coe NameLit Term where coe s := ⟨s.raw⟩ instance : Coe ScientificLit Term where coe s := ⟨s.raw⟩ instance : Coe NumLit Term where coe s := ⟨s.raw⟩ instance : Coe CharLit Term where coe s := ⟨s.raw⟩ instance : Coe Ident Syntax.Level where coe s := ⟨s.raw⟩ instance : Coe NumLit Prio where coe s := ⟨s.raw⟩ instance : Coe NumLit Prec where coe s := ⟨s.raw⟩ namespace Compat scoped instance : CoeTail Syntax (TSyntax k) where coe s := ⟨s⟩ scoped instance : CoeTail (Array Syntax) (TSyntaxArray k) where coe := .mk end Compat end TSyntax namespace Syntax partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ instance : BEq (Lean.TSyntax k) := ⟨(·.raw == ·.raw)⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node SourceInfo.none _ args => args.findSomeRev? getTailInfo? | node info _ _ => info | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 /-- Return substring of original input covering `stx`. Result is meaningful only if all involved `SourceInfo.original`s refer to the same string (as is the case after parsing). -/ def getSubstring? (stx : Syntax) (withLeading := true) (withTrailing := true) : Option Substring := match stx.getHeadInfo, stx.getTailInfo with | SourceInfo.original lead startPos _ _, SourceInfo.original _ _ trail stopPos => some { str := lead.str startPos := if withLeading then lead.startPos else startPos stopPos := if withTrailing then trail.stopPos else stopPos } | _, _ => none @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i]! match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node info k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node info k args | none => none | _ => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos _ endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a[i] match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node i k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node i k args | _ => none | _ => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | node _ kind args => node info kind args | missing => missing /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node SourceInfo.none _ args => args.findSome? getHead? | stx@(node ..) => stx | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo /-- Ensure head position is synthetic. The server regards syntax as "original" only if both head and tail info are `original`. -/ def mkSynthetic (stx : Syntax) : Syntax := stx.setHeadInfo (SourceInfo.fromRef stx) end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : TSyntax k := ⟨Syntax.node SourceInfo.none k args⟩ /-- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand macros in the given syntax. A node with kind `k` is visited only if `p k` is true. Note that the default value for `p` returns false for `by ...` nodes. This is a "hack". The tactic framework abuses the macro system to implement extensible tactics. For example, one can define ```lean syntax "my_trivial" : tactic -- extensible tactic macro_rules | `(tactic| my_trivial) => `(tactic| decide) macro_rules | `(tactic| my_trivial) => `(tactic| assumption) ``` When the tactic evaluator finds the tactic `my_trivial`, it tries to evaluate the `macro_rule` expansions until one "works", i.e., the macro expansion is evaluated without producing an exception. We say this solution is a bit hackish because the term elaborator may invoke `expandMacros` with `(p := fun _ => true)`, and expand the tactic macros as just macros. In the example above, `my_trivial` would be replaced with `assumption`, `decide` would not be tried if `assumption` fails at tactic evaluation time. We are considering two possible solutions for this issue: 1- A proper extensible tactic feature that does not rely on the macro system. 2- Typed macros that know the syntax categories they're working in. Then, we would be able to select which syntatic categories are expanded by `expandMacros`. -/ partial def expandMacros (stx : Syntax) (p : SyntaxNodeKind → Bool := fun k => k != `Lean.Parser.Term.byTactic) : MacroM Syntax := withRef stx do match stx with | .node info k args => do if p k then match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros return .node info k args else return stx | stx => return stx /-! # Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) : Ident := ⟨Syntax.ident (SourceInfo.fromRef src) (toString val).toSubstring val []⟩ def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) : m Ident := do return mkIdentFrom (← getRef) val /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) : Ident := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope ⟨Syntax.ident (SourceInfo.fromRef src) (toString id).toSubstring id [(c, [])]⟩ def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) : m Syntax := do return mkCIdentFrom (← getRef) c def mkCIdent (c : Name) : Ident := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Ident := ⟨Syntax.ident SourceInfo.none (toString val).toSubstring val []⟩ @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := mkNode nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := mkNode groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := Id.run do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => mkNullNode #[arg] | none => mkNullNode #[] def mkHole (ref : Syntax) : Syntax := mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref "_"] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtomFrom ref sep)⟩ instance : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems instance : Coe (TSyntaxArray k) (TSepArray k sep) where coe a := ⟨mkSepArray a.raw (mkAtom sep)⟩ /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Term) : (args : TSyntaxArray `term) → Term | #[] => fn | args => ⟨mkNode `Lean.Parser.Term.app #[fn, mkNullNode args.raw]⟩ def mkCApp (fn : Name) (args : TSyntaxArray `term) : Term := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : TSyntax kind := let atom : Syntax := Syntax.atom info val mkNode kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : StrLit := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : NumLit := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : TSyntax scientificLitKind := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : NameLit := mkLit nameLitKind val info /-! Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get ⟨1⟩ if c == 'x' || c == 'X' then decodeHexLitAux s ⟨2⟩ 0 else if c == 'b' || c == 'B' then decodeBinLitAux s ⟨2⟩ 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s ⟨2⟩ 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node _ k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s ⟨1⟩ "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := do let c := s.get ⟨1⟩ if c == '\\' then do let (c, _) ← decodeQuotedChar s ⟨2⟩ pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring := let splitRest (ss : Substring) (acc : List Substring) : List Substring := if ss.front == '.' then splitNameLitAux (ss.drop 1) acc else if ss.isEmpty then acc else [] if ss.isEmpty then [] else let curr := ss.front if isIdBeginEscape curr then let escapedPart := ss.takeWhile (!isIdEndEscape ·) let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) } if !isIdEndEscape (escapedPart.get <| escapedPart.prev ⟨escapedPart.bsize⟩) then [] else splitRest (ss.extract ⟨escapedPart.bsize⟩ ⟨ss.bsize⟩) (escapedPart :: acc) else if isIdFirst curr then let idPart := ss.takeWhile isIdRest splitRest (ss.extract ⟨idPart.bsize⟩ ⟨ss.bsize⟩) (idPart :: acc) else if curr.isDigit then let idPart := ss.takeWhile Char.isDigit splitRest (ss.extract ⟨idPart.bsize⟩ ⟨ss.bsize⟩) (idPart :: acc) else [] /-- Split a name literal (without the backtick) into its dot-separated components. For example, `foo.bla.«bo.o»` ↦ `["foo", "bla", "«bo.o»"]`. If the literal cannot be parsed, return `[]`. -/ def splitNameLit (ss : Substring) : List Substring := splitNameLitAux ss [] |>.reverse def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then match splitNameLitAux (s.toSubstring.drop 1) [] with | [] => none | comps => some <| comps.foldr (init := Name.anonymous) fun comp n => let comp := comp.toString if isIdBeginEscape comp.front then Name.mkStr n (comp.drop 1 |>.dropRight 1) else if comp.front.isDigit then if let some k := decodeNatLitVal? comp then Name.mkNum n k else unreachable! else Name.mkStr n comp else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node _ k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax namespace TSyntax def getNat (s : NumLit) : Nat := s.raw.isNatLit?.get! def getId (s : Ident) : Name := s.raw.getId def getScientific (s : ScientificLit) : Nat × Bool × Nat := s.raw.isScientificLit?.get! def getString (s : StrLit) : String := s.raw.isStrLit?.get! def getChar (s : CharLit) : Char := s.raw.isCharLit?.get! def getName (s : NameLit) : Name := s.raw.isNameLit?.get! namespace Compat scoped instance : CoeTail (Array Syntax) (Syntax.TSepArray k sep) where coe a := (a : TSyntaxArray k) end Compat end TSyntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) (k : SyntaxNodeKind := `term) where quote : α → TSyntax k export Quote (quote) instance [Quote α k] [CoeHTCT (TSyntax k) (TSyntax [k'])] : Quote α k' := ⟨fun a => quote (k := k) a⟩ instance : Quote Term := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent `Bool.true | false => mkCIdent `Bool.false⟩ instance : Quote String strLitKind := ⟨Syntax.mkStrLit⟩ instance : Quote Nat numLitKind := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp `String.toSubstring #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → Option (List String) | Name.anonymous => if acc.isEmpty then none else some acc | Name.str n s => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num _ _ => none def quoteNameMk : Name → Term | Name.anonymous => mkCIdent ``Name.anonymous | Name.str n s => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | Name.num n i => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name `term where quote n := match getEscapedNameParts? [] n with | some ss => ⟨mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)]⟩ | none => ⟨quoteNameMk n⟩ instance [Quote α `term] [Quote β `term] : Quote (α × β) `term where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList [Quote α `term] : List α → Term | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance [Quote α `term] : Quote (List α) `term where quote := quoteList instance [Quote α `term] : Quote (Array α) `term where quote xs := Syntax.mkCApp ``List.toArray #[quote xs.toList] instance Option.hasQuote {α : Type} [Quote α `term] : Quote (Option α) `term where quote | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] /-- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:num) => return num.getNat | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):num) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):num) macro "eval_prec " p:prec:max : term => return quote (k := `term) (← evalPrec p) /-- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:num) => return num.getNat | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):num) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):num) macro "eval_prio " p:prio:max : term => return quote (k := `term) (← evalPrio p) def evalOptPrio : Option (TSyntax `prio) → MacroM Nat | some prio => evalPrio prio | none => return 1000 -- TODO: FIX back eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a[i] if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.pred_lt hz have : i.pred < a.size := Nat.lt_trans this h let sepStx := a[i.pred] filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a[i] if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax def SepArray.getElems (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems def TSepArray.getElems (sa : TSepArray k sep) : TSyntaxArray k := .mk sa.elemsAndSeps.getSepElems def TSepArray.push (sa : TSepArray k sep) (e : TSyntax k) : TSepArray k sep := if sa.elemsAndSeps.isEmpty then { elemsAndSeps := #[e] } else { elemsAndSeps := sa.elemsAndSeps.push (mkAtom sep) |>.push e } instance : EmptyCollection (SepArray sep) where emptyCollection := ⟨∅⟩ instance : EmptyCollection (TSepArray sep k) where emptyCollection := ⟨∅⟩ /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance : CoeTail (SepArray sep) (Array Syntax) where coe := SepArray.getElems instance : Coe (TSepArray k sep) (TSyntaxArray k) where coe := TSepArray.getElems instance [Coe (TSyntax k) (TSyntax k')] : Coe (TSyntaxArray k) (TSyntaxArray k') where coe a := a.map Coe.coe instance : Coe (TSyntaxArray k) (Array Syntax) where coe a := a.raw instance : Coe Ident (TSyntax `Lean.Parser.Command.declId) where coe id := mkNode _ #[id, mkNullNode #[]] instance : Coe (Lean.Term) (Lean.TSyntax `Lean.Parser.Term.funBinder) where coe stx := ⟨stx⟩ end Lean.Syntax set_option linter.unusedVariables.funArgs false in /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /-! # Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : Option String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop ⟨1⟩ "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace TSyntax def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result open TSyntax.Compat in def expandInterpolatedStr (interpStr : TSyntax interpolatedStrKind) (type : Term) (toTypeFn : Term) : MacroM Term := do let r ← expandInterpolatedStrChunks interpStr.raw.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) end TSyntax namespace Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr inductive EtaStructMode where | /-- Enable eta for structure and classes. -/ all | /-- Enable eta only for structures that are not classes. -/ notClasses | /-- Disable eta for structures and classes. -/ none deriving Inhabited, BEq, Repr namespace DSimp structure Config where zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : EtaStructMode := .all iota : Bool := true proj : Bool := true decide : Bool := true autoUnfold : Bool := false deriving Inhabited, BEq, Repr end DSimp namespace Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : EtaStructMode := .all iota : Bool := true proj : Bool := true decide : Bool := true arith : Bool := false autoUnfold : Bool := false /-- If `dsimp := true`, then switches to `dsimp` on dependent arguments where there is no congruence theorem that allows `simp` to visit them. If `dsimp := false`, then argument is not visited. -/ dsimp : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true def neutralConfig : Simp.Config := { zeta := false beta := false eta := false iota := false proj := false decide := false arith := false autoUnfold := false } end Simp namespace Rewrite structure Config where transparency : TransparencyMode := TransparencyMode.reducible offsetCnstrs : Bool := true end Rewrite end Meta namespace Parser.Tactic /-- `erw [rules]` is a shorthand for `rw (config := { transparency := .default }) [rules]`. This does rewriting up to unfolding of regular definitions (by comparison to regular `rw` which only unfolds `@[reducible]` definitions). -/ macro "erw " s:rwRuleSeq loc:(location)? : tactic => `(rw (config := { transparency := .default }) $s $(loc)?) syntax simpAllKind := atomic("(" &"all") " := " &"true" ")" syntax dsimpKind := atomic("(" &"dsimp") " := " &"true" ")" macro (name := declareSimpLikeTactic) doc?:(docComment)? "declare_simp_like_tactic" opt:((simpAllKind <|> dsimpKind)?) tacName:ident tacToken:str updateCfg:term : command => do let (kind, tkn, stx) ← if opt.raw.isNone then pure (← `(``simp), ← `("simp "), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&"only ")? ("[" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic)) else if opt.raw[0].getKind == ``simpAllKind then pure (← `(``simpAll), ← `("simp_all "), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic)) else pure (← `(``dsimp), ← `("dsimp "), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? (location)? : tactic)) `($stx:command @[macro $tacName] def expandSimp : Macro := fun s => do let c ← match s[1][0] with | `(config| (config := $$c)) => `(config| (config := $updateCfg $$c)) | _ => `(config| (config := $updateCfg {})) let s := s.setKind $kind let s := s.setArg 0 (mkAtomFrom s[0] $tkn) let r := s.setArg 1 (mkNullNode #[c]) return r) /-- `simp!` is shorthand for `simp` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic simpAutoUnfold "simp! " fun (c : Lean.Meta.Simp.Config) => { c with autoUnfold := true } /-- `simp_arith` is shorthand for `simp` with `arith := true`. This enables the use of normalization by linear arithmetic. -/ declare_simp_like_tactic simpArith "simp_arith " fun (c : Lean.Meta.Simp.Config) => { c with arith := true } /-- `simp_arith!` is shorthand for `simp_arith` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic simpArithAutoUnfold "simp_arith! " fun (c : Lean.Meta.Simp.Config) => { c with arith := true, autoUnfold := true } /-- `simp_all!` is shorthand for `simp_all` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic (all := true) simpAllAutoUnfold "simp_all! " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with autoUnfold := true } /-- `simp_all_arith` combines the effects of `simp_all` and `simp_arith`. -/ declare_simp_like_tactic (all := true) simpAllArith "simp_all_arith " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true } /-- `simp_all_arith!` combines the effects of `simp_all`, `simp_arith` and `simp!`. -/ declare_simp_like_tactic (all := true) simpAllArithAutoUnfold "simp_all_arith! " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true, autoUnfold := true } /-- `dsimp!` is shorthand for `dsimp` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic (dsimp := true) dsimpAutoUnfold "dsimp! " fun (c : Lean.Meta.DSimp.Config) => { c with autoUnfold := true } end Parser.Tactic end Lean
c2195def8e3c02d09ff5cdca2457461902ef906e
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/localization/integral.lean
a2defcc55fc68b72a88111de57d289508fce8d59
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
17,379
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import algebra.ring.equiv import group_theory.monoid_localization import ring_theory.algebraic import ring_theory.ideal.local_ring import ring_theory.ideal.quotient import ring_theory.integral_closure import ring_theory.localization.fraction_ring import ring_theory.localization.integer import ring_theory.non_zero_divisors import group_theory.submonoid.inverses import tactic.ring_exp /-! # Integral and algebraic elements of a fraction field ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] (M : submonoid R) {S : Type*} [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] open_locale big_operators polynomial namespace is_localization section integer_normalization open polynomial variables (M) {S} [is_localization M S] open_locale classical /-- `coeff_integer_normalization p` gives the coefficients of the polynomial `integer_normalization p` -/ noncomputable def coeff_integer_normalization (p : S[X]) (i : ℕ) : R := if hi : i ∈ p.support then classical.some (classical.some_spec (exist_integer_multiples_of_finset M (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) else 0 lemma coeff_integer_normalization_of_not_mem_support (p : S[X]) (i : ℕ) (h : coeff p i = 0) : coeff_integer_normalization M p i = 0 := by simp only [coeff_integer_normalization, h, mem_support_iff, eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff] lemma coeff_integer_normalization_mem_support (p : S[X]) (i : ℕ) (h : coeff_integer_normalization M p i ≠ 0) : i ∈ p.support := begin contrapose h, rw [ne.def, not_not, coeff_integer_normalization, dif_neg h] end /-- `integer_normalization g` normalizes `g` to have integer coefficients by clearing the denominators -/ noncomputable def integer_normalization (p : S[X]) : R[X] := ∑ i in p.support, monomial i (coeff_integer_normalization M p i) @[simp] lemma integer_normalization_coeff (p : S[X]) (i : ℕ) : (integer_normalization M p).coeff i = coeff_integer_normalization M p i := by simp [integer_normalization, coeff_monomial, coeff_integer_normalization_of_not_mem_support] {contextual := tt} lemma integer_normalization_spec (p : S[X]) : ∃ (b : M), ∀ i, algebra_map R S ((integer_normalization M p).coeff i) = (b : R) • p.coeff i := begin use classical.some (exist_integer_multiples_of_finset M (p.support.image p.coeff)), intro i, rw [integer_normalization_coeff, coeff_integer_normalization], split_ifs with hi, { exact classical.some_spec (classical.some_spec (exist_integer_multiples_of_finset M (p.support.image p.coeff)) (p.coeff i) (finset.mem_image.mpr ⟨i, hi, rfl⟩)) }, { convert (smul_zero _).symm, { apply ring_hom.map_zero }, { exact not_mem_support_iff.mp hi } } end lemma integer_normalization_map_to_map (p : S[X]) : ∃ (b : M), (integer_normalization M p).map (algebra_map R S) = (b : R) • p := let ⟨b, hb⟩ := integer_normalization_spec M p in ⟨b, polynomial.ext (λ i, by { rw [coeff_map, coeff_smul], exact hb i })⟩ variables {R' : Type*} [comm_ring R'] lemma integer_normalization_eval₂_eq_zero (g : S →+* R') (p : S[X]) {x : R'} (hx : eval₂ g x p = 0) : eval₂ (g.comp (algebra_map R S)) x (integer_normalization M p) = 0 := let ⟨b, hb⟩ := integer_normalization_map_to_map M p in trans (eval₂_map (algebra_map R S) g x).symm (by rw [hb, ← is_scalar_tower.algebra_map_smul S (b : R) p, eval₂_smul, hx, mul_zero]) lemma integer_normalization_aeval_eq_zero [algebra R R'] [algebra S R'] [is_scalar_tower R S R'] (p : S[X]) {x : R'} (hx : aeval x p = 0) : aeval x (integer_normalization M p) = 0 := by rw [aeval_def, is_scalar_tower.algebra_map_eq R S R', integer_normalization_eval₂_eq_zero _ _ _ hx] end integer_normalization end is_localization namespace is_fraction_ring open is_localization variables {A K C : Type*} [comm_ring A] [is_domain A] [field K] [algebra A K] [is_fraction_ring A K] variables [comm_ring C] lemma integer_normalization_eq_zero_iff {p : K[X]} : integer_normalization (non_zero_divisors A) p = 0 ↔ p = 0 := begin refine (polynomial.ext_iff.trans (polynomial.ext_iff.trans _).symm), obtain ⟨⟨b, nonzero⟩, hb⟩ := integer_normalization_spec _ p, split; intros h i, { apply to_map_eq_zero_iff.mp, rw [hb i, h i], apply smul_zero, assumption }, { have hi := h i, rw [polynomial.coeff_zero, ← @to_map_eq_zero_iff A _ K, hb i, algebra.smul_def] at hi, apply or.resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero hi), intro h, apply mem_non_zero_divisors_iff_ne_zero.mp nonzero, exact to_map_eq_zero_iff.mp h } end variables (A K C) /-- An element of a ring is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma is_algebraic_iff [algebra A C] [algebra K C] [is_scalar_tower A K C] {x : C} : is_algebraic A x ↔ is_algebraic K x := begin split; rintros ⟨p, hp, px⟩, { refine ⟨p.map (algebra_map A K), λ h, hp (polynomial.ext (λ i, _)), _⟩, { have : algebra_map A K (p.coeff i) = 0 := trans (polynomial.coeff_map _ _).symm (by simp [h]), exact to_map_eq_zero_iff.mp this }, { rwa is_scalar_tower.aeval_apply _ K at px } }, { exact ⟨integer_normalization _ p, mt integer_normalization_eq_zero_iff.mp hp, integer_normalization_aeval_eq_zero _ p px⟩ }, end variables {A K C} /-- A ring is algebraic over the ring `A` iff it is algebraic over the field of fractions of `A`. -/ lemma comap_is_algebraic_iff [algebra A C] [algebra K C] [is_scalar_tower A K C] : algebra.is_algebraic A C ↔ algebra.is_algebraic K C := ⟨λ h x, (is_algebraic_iff A K C).mp (h x), λ h x, (is_algebraic_iff A K C).mpr (h x)⟩ end is_fraction_ring open is_localization section is_integral variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] variables [algebra R Rₘ] [is_localization M Rₘ] variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] variables {S M} open polynomial lemma ring_hom.is_integral_elem_localization_at_leading_coeff {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (x : S) (p : R[X]) (hf : p.eval₂ f x = 0) (M : submonoid R) (hM : p.leading_coeff ∈ M) {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] [algebra R Rₘ] [is_localization M Rₘ] [algebra S Sₘ] [is_localization (M.map f : submonoid S) Sₘ] : (map Sₘ f M.le_comap_map : Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) := begin by_cases triv : (1 : Rₘ) = 0, { exact ⟨0, ⟨trans leading_coeff_zero triv.symm, eval₂_zero _ _⟩⟩ }, haveI : nontrivial Rₘ := nontrivial_of_ne 1 0 triv, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.mp (map_units Rₘ ⟨p.leading_coeff, hM⟩), refine ⟨(p.map (algebra_map R Rₘ)) * C b, ⟨_, _⟩⟩, { refine monic_mul_C_of_leading_coeff_mul_eq_one _, rwa leading_coeff_map_of_leading_coeff_ne_zero (algebra_map R Rₘ), refine λ hfp, zero_ne_one (trans (zero_mul b).symm (hfp ▸ hb) : (0 : Rₘ) = 1) }, { refine eval₂_mul_eq_zero_of_left _ _ _ _, erw [eval₂_map, is_localization.map_comp, ← hom_eval₂ _ f (algebra_map S Sₘ) x], exact trans (congr_arg (algebra_map S Sₘ) hf) (ring_hom.map_zero _) } end /-- Given a particular witness to an element being algebraic over an algebra `R → S`, We can localize to a submonoid containing the leading coefficient to make it integral. Explicitly, the map between the localizations will be an integral ring morphism -/ theorem is_integral_localization_at_leading_coeff {x : S} (p : R[X]) (hp : aeval x p = 0) (hM : p.leading_coeff ∈ M) : (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* _).is_integral_elem (algebra_map S Sₘ x) := (algebra_map R S).is_integral_elem_localization_at_leading_coeff x p hp M hM /-- If `R → S` is an integral extension, `M` is a submonoid of `R`, `Rₘ` is the localization of `R` at `M`, and `Sₘ` is the localization of `S` at the image of `M` under the extension map, then the induced map `Rₘ → Sₘ` is also an integral extension -/ theorem is_integral_localization (H : algebra.is_integral R S) : (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* _).is_integral := begin intro x, obtain ⟨⟨s, ⟨u, hu⟩⟩, hx⟩ := surj (algebra.algebra_map_submonoid S M) x, obtain ⟨v, hv⟩ := hu, obtain ⟨v', hv'⟩ := is_unit_iff_exists_inv'.1 (map_units Rₘ ⟨v, hv.1⟩), refine @is_integral_of_is_integral_mul_unit Rₘ _ _ _ (localization_algebra M S) x (algebra_map S Sₘ u) v' _ _, { replace hv' := congr_arg (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) hv', rw [ring_hom.map_mul, ring_hom.map_one, ← ring_hom.comp_apply _ (algebra_map R Rₘ)] at hv', erw is_localization.map_comp at hv', exact hv.2 ▸ hv' }, { obtain ⟨p, hp⟩ := H s, exact hx.symm ▸ is_integral_localization_at_leading_coeff p hp.2 (hp.1.symm ▸ M.one_mem) } end lemma is_integral_localization' {R S : Type*} [comm_ring R] [comm_ring S] {f : R →+* S} (hf : f.is_integral) (M : submonoid R) : (map (localization (M.map (f : R →* S))) f M.le_comap_map : localization M →+* _).is_integral := @is_integral_localization R _ M S _ f.to_algebra _ _ _ _ _ _ _ _ hf end is_integral variables {A K : Type*} [comm_ring A] [is_domain A] namespace is_integral_closure variables (A) {L : Type*} [field K] [field L] [algebra A K] [algebra A L] [is_fraction_ring A K] variables (C : Type*) [comm_ring C] [is_domain C] [algebra C L] [is_integral_closure C A L] variables [algebra A C] [is_scalar_tower A C L] open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure `C` of `A` in `L` has fraction field `L`. -/ lemma is_fraction_ring_of_algebraic (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : is_fraction_ring C L := { map_units := λ ⟨y, hy⟩, is_unit.mk0 _ (show algebra_map C L y ≠ 0, from λ h, mem_non_zero_divisors_iff_ne_zero.mp hy ((injective_iff_map_eq_zero (algebra_map C L)).mp (algebra_map_injective C A L) _ h)), surj := λ z, let ⟨x, y, hy, hxy⟩ := exists_integral_multiple (alg z) inj in ⟨⟨mk' C (x : L) x.2, algebra_map _ _ y, mem_non_zero_divisors_iff_ne_zero.mpr (λ h, hy (inj _ (by rw [is_scalar_tower.algebra_map_apply A C L, h, ring_hom.map_zero])))⟩, by rw [set_like.coe_mk, algebra_map_mk', ← is_scalar_tower.algebra_map_apply A C L, hxy]⟩, eq_iff_exists := λ x y, ⟨λ h, ⟨1, by simpa using algebra_map_injective C A L h⟩, λ ⟨c, hc⟩, congr_arg (algebra_map _ L) (mul_right_cancel₀ (mem_non_zero_divisors_iff_ne_zero.mp c.2) hc)⟩ } variables (K L) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure `C` of `A` in `L` has fraction field `L`. -/ lemma is_fraction_ring_of_finite_extension [algebra K L] [is_scalar_tower A K L] [finite_dimensional K L] : is_fraction_ring C L := is_fraction_ring_of_algebraic A C (is_fraction_ring.comap_is_algebraic_iff.mpr (is_algebraic_of_finite K L)) (λ x hx, is_fraction_ring.to_map_eq_zero_iff.mp ((algebra_map K L).map_eq_zero.mp $ (is_scalar_tower.algebra_map_apply _ _ _ _).symm.trans hx)) end is_integral_closure namespace integral_closure variables {L : Type*} [field K] [field L] [algebra A K] [is_fraction_ring A K] open algebra /-- If the field `L` is an algebraic extension of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ lemma is_fraction_ring_of_algebraic [algebra A L] (alg : is_algebraic A L) (inj : ∀ x, algebra_map A L x = 0 → x = 0) : is_fraction_ring (integral_closure A L) L := is_integral_closure.is_fraction_ring_of_algebraic A (integral_closure A L) alg inj variables (K L) /-- If the field `L` is a finite extension of the fraction field of the integral domain `A`, the integral closure of `A` in `L` has fraction field `L`. -/ lemma is_fraction_ring_of_finite_extension [algebra A L] [algebra K L] [is_scalar_tower A K L] [finite_dimensional K L] : is_fraction_ring (integral_closure A L) L := is_integral_closure.is_fraction_ring_of_finite_extension A K L (integral_closure A L) end integral_closure namespace is_fraction_ring variables (R S K) /-- `S` is algebraic over `R` iff a fraction ring of `S` is algebraic over `R` -/ lemma is_algebraic_iff' [field K] [is_domain R] [is_domain S] [algebra R K] [algebra S K] [no_zero_smul_divisors R K] [is_fraction_ring S K] [is_scalar_tower R S K] : algebra.is_algebraic R S ↔ algebra.is_algebraic R K := begin simp only [algebra.is_algebraic], split, { intros h x, rw [is_fraction_ring.is_algebraic_iff R (fraction_ring R) K, is_algebraic_iff_is_integral], obtain ⟨(a : S), b, ha, rfl⟩ := @div_surjective S _ _ _ _ _ _ x, obtain ⟨f, hf₁, hf₂⟩ := h b, rw [div_eq_mul_inv], refine is_integral_mul _ _, { rw [← is_algebraic_iff_is_integral], refine _root_.is_algebraic_of_larger_base_of_injective (no_zero_smul_divisors.algebra_map_injective R (fraction_ring R)) _, exact is_algebraic_algebra_map_of_is_algebraic (h a) }, { rw [← is_algebraic_iff_is_integral], use (f.map (algebra_map R (fraction_ring R))).reverse, split, { rwa [ne.def, polynomial.reverse_eq_zero, ← polynomial.degree_eq_bot, polynomial.degree_map_eq_of_injective (no_zero_smul_divisors.algebra_map_injective R (fraction_ring R)), polynomial.degree_eq_bot]}, { haveI : invertible (algebra_map S K b), from is_unit.invertible (is_unit_of_mem_non_zero_divisors (mem_non_zero_divisors_iff_ne_zero.2 (λ h, non_zero_divisors.ne_zero ha ((injective_iff_map_eq_zero (algebra_map S K)).1 (no_zero_smul_divisors.algebra_map_injective _ _) b h)))), rw [polynomial.aeval_def, ← inv_of_eq_inv, polynomial.eval₂_reverse_eq_zero_iff, polynomial.eval₂_map, ← is_scalar_tower.algebra_map_eq, ← polynomial.aeval_def, ← is_scalar_tower.algebra_map_aeval, hf₂, ring_hom.map_zero] } } }, { intros h x, obtain ⟨f, hf₁, hf₂⟩ := h (algebra_map S K x), use [f, hf₁], rw [← is_scalar_tower.algebra_map_aeval] at hf₂, exact (injective_iff_map_eq_zero (algebra_map S K)).1 (no_zero_smul_divisors.algebra_map_injective _ _) _ hf₂ } end open_locale non_zero_divisors variables (R) {S K} /-- If the `S`-multiples of `a` are contained in some `R`-span, then `Frac(S)`-multiples of `a` are contained in the equivalent `Frac(R)`-span. -/ lemma ideal_span_singleton_map_subset {L : Type*} [is_domain R] [is_domain S] [field K] [field L] [algebra R K] [algebra R L] [algebra S L] [is_integral_closure S R L] [is_fraction_ring S L] [algebra K L] [is_scalar_tower R S L] [is_scalar_tower R K L] {a : S} {b : set S} (alg : algebra.is_algebraic R L) (inj : function.injective (algebra_map R L)) (h : (ideal.span ({a} : set S) : set S) ⊆ submodule.span R b) : (ideal.span ({algebra_map S L a} : set L) : set L) ⊆ submodule.span K (algebra_map S L '' b) := begin intros x hx, obtain ⟨x', rfl⟩ := ideal.mem_span_singleton.mp hx, obtain ⟨y', z', rfl⟩ := is_localization.mk'_surjective (S⁰) x', obtain ⟨y, z, hz0, yz_eq⟩ := is_integral_closure.exists_smul_eq_mul alg inj y' (non_zero_divisors.coe_ne_zero z'), have injRS : function.injective (algebra_map R S), { refine function.injective.of_comp (show function.injective (algebra_map S L ∘ algebra_map R S), from _), rwa [← ring_hom.coe_comp, ← is_scalar_tower.algebra_map_eq] }, have hz0' : algebra_map R S z ∈ S⁰ := map_mem_non_zero_divisors (algebra_map R S) injRS (mem_non_zero_divisors_of_ne_zero hz0), have mk_yz_eq : is_localization.mk' L y' z' = is_localization.mk' L y ⟨_, hz0'⟩, { rw [algebra.smul_def, mul_comm _ y, mul_comm _ y', ← set_like.coe_mk (algebra_map R S z) hz0'] at yz_eq, exact is_localization.mk'_eq_of_eq yz_eq.symm }, suffices hy : algebra_map S L (a * y) ∈ submodule.span K (⇑(algebra_map S L) '' b), { rw [mk_yz_eq, is_fraction_ring.mk'_eq_div, set_like.coe_mk, ← is_scalar_tower.algebra_map_apply, is_scalar_tower.algebra_map_apply R K L, div_eq_mul_inv, ← mul_assoc, mul_comm, ← ring_hom.map_inv, ← algebra.smul_def, ← _root_.map_mul], exact (submodule.span K _).smul_mem _ hy }, refine submodule.span_subset_span R K _ _, rw submodule.span_algebra_map_image_of_tower, exact submodule.mem_map_of_mem (h (ideal.mem_span_singleton.mpr ⟨y, rfl⟩)) end end is_fraction_ring
c5d67c8fe667cc4750898ce7379f7e15e83e2b62
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/tactic/interactive.lean
b9c5e1e3f8b83ab5eea03e0bcb97b254bda10116
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
27,125
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import data.dlist data.dlist.basic data.prod category.basic tactic.basic tactic.rcases tactic.generalize_proofs tactic.split_ifs logic.basic tactic.ext tactic.tauto tactic.replacer tactic.simpa tactic.squeeze open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. `rcases` also has special support for quotient types: quotient induction into Prop works like matching on the constructor `quot.mk`. `rcases? e` will perform case splits on `e` in the same way as `rcases e`, but rather than accepting a pattern, it does a maximal cases and prints the pattern that would produce this case splitting. The default maximum depth is 5, but this can be modified with `rcases? e : n`. -/ meta def rcases : parse rcases_parse → tactic unit | (p, sum.inl ids) := tactic.rcases p ids | (p, sum.inr depth) := do patt ← tactic.rcases_hint p depth, pe ← pp p, trace $ ↑"snippet: rcases " ++ pe ++ " with " ++ to_fmt patt /-- The `rintro` tactic is a combination of the `intros` tactic with `rcases` to allow for destructuring patterns while introducing variables. See `rcases` for a description of supported patterns. For example, `rintros (a | ⟨b, c⟩) ⟨d, e⟩` will introduce two variables, and then do case splits on both of them producing two subgoals, one with variables `a d e` and the other with `b c d e`. `rintro?` will introduce and case split on variables in the same way as `rintro`, but will also print the `rintro` invocation that would have the same result. Like `rcases?`, `rintro? : n` allows for modifying the depth of splitting; the default is 5. -/ meta def rintro : parse rintro_parse → tactic unit | (sum.inl []) := intros [] | (sum.inl l) := tactic.rintro l | (sum.inr depth) := do ps ← tactic.rintro_hint depth, trace $ ↑"snippet: rintro" ++ format.join (ps.map $ λ p, format.space ++ format.group (p.format tt)) /-- Alias for `rintro`. -/ meta def rintros := rintro /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end /-- Generalize proofs in the goal, naming them with the provided list. -/ meta def generalize_proofs : parse ident_* → tactic unit := tactic.generalize_proofs /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. alternatively, when encountering an assumption of the form `sg₀ → ¬ sg₁`, after the main approach failed, the goal is dismissed and `sg₀` and `sg₁` are made into the new goal. optional arguments: - asms: list of rules to consider instead of the local constants - tac: a tactic to run on each subgoals after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (asms : tactic (list expr) := local_context) (tac : tactic unit := return ()) : tactic unit := tactic.apply_assumption asms tac open nat meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name): tactic (list expr) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, hs ← hs.mmap i_to_expr_for_apply, l ← attr.mmap $ λ a, attribute.get_instances a, let l := l.join, m ← list.mmap mk_const l, let hs := (hs ++ m).filter $ λ h, expr.const_name h ∉ gex, hs ← if no_dflt then return hs else do { congr_fun ← mk_const `congr_fun, congr_arg ← mk_const `congr_arg, return (congr_fun :: congr_arg :: hs) }, if ¬ no_dflt ∨ all_hyps then do ctx ← local_context, return $ hs.append (ctx.filter (λ h, h.local_uniq_name ∉ hex)) -- remove local exceptions else return hs /-- `solve_by_elim` calls `apply_assumption` on the main goal to find an assumption whose head matches and then repeatedly calls `apply_assumption` on the generated subgoals until no subgoals remain, performing at most `max_rep` recursive steps. `solve_by_elim` discharges the current goal or fails `solve_by_elim` performs back-tracking if `apply_assumption` chooses an unproductive assumption By default, the assumptions passed to apply_assumption are the local context, `congr_fun` and `congr_arg`. `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas. `solve_by_elim with attr₁ ... attrᵣ also applied all lemmas tagged with the specified attributes. `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `congr_fun`, or `congr_arg` unless they are explicitly included. `solve_by_elim [-id]` removes a specified assumption. optional arguments: - discharger: a subsidiary tactic to try at each step (e.g. `cc` may be helpful) - max_rep: number of attempts at discharging generated sub-goals -/ meta def solve_by_elim (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : by_elim_opt := { }) : tactic unit := do asms ← mk_assumption_set no_dflt hs attr_names, tactic.solve_by_elim { assumptions := return asms ..opt } /-- `tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _` and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged using `reflexivity` or `solve_by_elim` -/ meta def tautology (c : parse $ (tk "!")?) := tactic.tautology c.is_some /-- Shorter name for the tactic `tautology`. -/ meta def tauto (c : parse $ (tk "!")?) := tautology c /-- Make every propositions in the context decidable -/ meta def classical := tactic.classical private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], congr' n, gs' ← get_goals, set_goals $ gs' ++ gs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. example, with or without user attribute: ``` @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules -- any of the following lines would also work: -- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 -- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] -- by apply_rules [mono_rules] ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`. `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`. `h_generalize! Hx : e == x` reverts `Hx`. when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating `∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (tactic.clear tgt) meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := tactic.use l >> try triv /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do let vt := match tp with | some t := t | none := pexpr.mk_placeholder end, let pv := ``(%%pv : %%vt), v ← to_expr pv, tp ← infer_type v, definev a tp v, when h_simp.is_none $ change' pv (some (expr.const a [])) loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, pf ← to_expr (cond flip ``(%%pv = %%nv) ``(%%nv = %%pv)) >>= assert id, reflexivity | none := skip end end interactive end tactic
b1de3c7f3f8a56aa8cf6d7746092869c06d1c498
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/linear_algebra/direct_sum_module.lean
4196caf26d6301139900312c8a39148856848511
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
4,749
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of modules over commutative rings, indexed by a discrete type. -/ import algebra.direct_sum import linear_algebra.basic /-! # Direct sum of modules over commutative rings, indexed by a discrete type. This file provides constructors for finite direct sums of modules. It provides a construction of the direct sum using the universal property and proves its uniqueness. ## Implementation notes All of this file assumes that * `R` is a commutative ring, * `ι` is a discrete type, * `S` is a finite set in `ι`, * `M` is a family of `R` semimodules indexed over `ι`. -/ universes u v w u₁ variables (R : Type u) [semiring R] variables (ι : Type v) [decidable_eq ι] (M : ι → Type w) variables [Π i, add_comm_group (M i)] [Π i, semimodule R (M i)] include R namespace direct_sum open_locale direct_sum variables {R ι M} instance : semimodule R (⨁ i, M i) := dfinsupp.to_semimodule variables R ι M /-- Create the direct sum given a family `M` of `R` semimodules indexed over `ι`. -/ def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.val) →ₗ[R] (⨁ i, M i) := dfinsupp.lmk M R /-- Inclusion of each component into the direct sum. -/ def lof : Π i : ι, M i →ₗ[R] (⨁ i, M i) := dfinsupp.lsingle M R variables {ι M} lemma single_eq_lof (i : ι) (b : M i) : dfinsupp.single i b = lof R ι M i b := rfl /-- Scalar multiplication commutes with direct sums. -/ theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x := (lmk R ι M s).map_smul c x /-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/ theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x := (lof R ι M i).map_smul c x variables {N : Type u₁} [add_comm_group N] [semimodule R N] variables (φ : Π i, M i →ₗ[R] N) variables (ι N φ) /-- The linear map constructed using the universal property of the coproduct. -/ def to_module : (⨁ i, M i) →ₗ[R] N := { to_fun := to_group (λ i, φ i), map_add' := to_group_add _, map_smul' := λ c x, direct_sum.induction_on x (by rw [smul_zero, to_group_zero, smul_zero]) (λ i x, by rw [← of_smul, to_group_of, to_group_of, (φ i).map_smul c x]) (λ x y ihx ihy, by rw [smul_add, to_group_add, ihx, ihy, to_group_add, smul_add]) } variables {ι N φ} /-- The map constructed using the universal property gives back the original maps when restricted to each component. -/ @[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x := to_group_of (λ i, φ i) i x variables (ψ : (⨁ i, M i) →ₗ[R] N) /-- Every linear map from a direct sum agrees with the one obtained by applying the universal property to each of its components. -/ theorem to_module.unique (f : ⨁ i, M i) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f := to_group.unique ψ f variables {ψ} {ψ' : (⨁ i, M i) →ₗ[R] N} theorem to_module.ext (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) (f : ⨁ i, M i) : ψ f = ψ' f := by rw [to_module.unique R ψ, to_module.unique R ψ', funext H] /-- The inclusion of a subset of the direct summands into a larger subset of the direct summands, as a linear map. -/ def lset_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), M i) →ₗ (⨁ (i : T), M i) := to_module R _ _ $ λ i, lof R T (M ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ protected def lid (M : Type v) [add_comm_group M] [semimodule R M] : (⨁ (_ : punit), M) ≃ₗ M := { .. direct_sum.id M, .. to_module R punit M (λ i, linear_map.id) } variables (ι M) /-- The projection map onto one component, as a linear map. -/ def component (i : ι) : (⨁ i, M i) →ₗ[R] M i := { to_fun := λ f, f i, map_add' := λ _ _, dfinsupp.add_apply, map_smul' := λ _ _, dfinsupp.smul_apply } variables {ι M} @[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b := by rw [lof, dfinsupp.lsingle_apply, dfinsupp.single_apply, dif_pos rfl] lemma apply_eq_component (f : ⨁ i, M i) (i : ι) : f i = component R ι M i f := rfl @[simp] lemma component.lof_self (i : ι) (b : M i) : component R ι M i ((lof R ι M i) b) = b := lof_apply R i b lemma component.of (i j : ι) (b : M j) : component R ι M i ((lof R ι M j) b) = if h : j = i then eq.rec_on h b else 0 := dfinsupp.single_apply @[ext] lemma ext {f g : ⨁ i, M i} (h : ∀ i, component R ι M i f = component R ι M i g) : f = g := dfinsupp.ext h lemma ext_iff {f g : ⨁ i, M i} : f = g ↔ ∀ i, component R ι M i f = component R ι M i g := ⟨λ h _, by rw h, ext R⟩ end direct_sum
b27cf28b31f6eab87dc2ea929afb8313b3e247ab
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/sum_four_squares.lean
18e2a198015dcdcd4a1951517209b6899e8d5c76
[ "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,862
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.group_power.identities import data.zmod.basic import field_theory.finite.basic import data.int.parity import data.fintype.card /-! # 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. -/ open finset polynomial finite_field equiv open_locale big_operators namespace int lemma sq_add_sq_of_two_mul_sq_add_sq {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have even (x^2 + y^2), by simp [h.symm, even_mul], have hxaddy : even (x + y), by simpa [sq] with parity_simps, have hxsuby : even (x - y), by simpa [sq] with parity_simps, (mul_right_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 even_iff_two_dvd at hxsuby hxaddy, 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, pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sq_add_sq_add_one_eq_k (p : ℕ) [hp : fact p.prime] : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.1.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmod.sq_add_sq p (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (char_p.int_cast_eq_zero_iff (zmod p) p _).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 (sq_nonneg _) (sq_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.1.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, int.coe_nat_pow, int.coe_nat_pow, int.nat_abs_sq, int.nat_abs_sq, 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 (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) le_rfl ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, 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.1.two_le dec_trivial))) ... = p * p : by { conv_rhs { rw [← nat.mod_add_div p 2] }, ring }) (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 (char_p.int_cast_eq_zero_iff (zmod 2) 2 _).1 $ by simpa [σ] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (char_p.int_cast_eq_zero_iff (zmod 2) 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.sq_add_sq_of_two_mul_sq_add_sq hx.symm, add_assoc, ← int.sq_add_sq_of_two_mul_sq_add_sq hy.symm, ← mul_right_inj' (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : ∑ x, f (σ x)^2 = ∑ x, f x^2, { conv_rhs { rw ←equiv.sum_comp σ } }, 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, add_assoc] end⟩ private lemma prime_sum_four_squares (p : ℕ) [hp : _root_.fact 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_sq_add_sq_add_one_eq_k p 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 (sq_nonneg _) (sq_nonneg _)) zero_lt_one) hk.1 }), a, b, 1, 0, by simpa [sq] 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 by haveI hm0 : _root_.fact (0 < m) := ⟨(nat.find_spec hm).snd.1⟩; exact 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, { 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 let w := (a : zmod m).val_min_abs, x := (b : zmod m).val_min_abs, y := (c : zmod m).val_min_abs, z := (d : zmod m).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 [sq], 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 [sq, bit0, bit1, mul_add, add_mul, add_assoc] ... < 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, 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, pow_add, add_comm, add_left_comm] }, have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod m), by simp [w, x, y, z, sq], have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod m) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, cast_coe_nat, zmod.nat_cast_self, zero_mul], let ⟨n, hn⟩ := ((char_p.int_cast_eq_zero_iff _ m _).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' (sq_nonneg (_ : ℤ)) (sq_nonneg _), pow_two, w, x, y, z, (char_p.int_cast_eq_zero_iff _ m _), and.assoc] 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, (mul_right_inj' (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0.1)).1 $ by { rw [← habcd, hma, hmb, hmc, hmd], ring }⟩, (hp.1.eq_one_or_self_of_dvd _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((m : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { rw [← hwxyz0], simp, ring }, have haxbwczdy : ((m : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have haybzcwdx : ((m : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], ring }, have hazbycxdw : ((m : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from (char_p.int_cast_eq_zero_iff (zmod m) m _).1 $ by { simp [sub_eq_add_neg], 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 sq_nonneg _}} }) (int.coe_nat_pos.2 hm0.1), have hnm : n.nat_abs < m, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by { rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← sq], exact hwxyzlt }) (int.coe_nat_nonneg m)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (mul_right_inj' (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero_iff_pos.2 hm0.1))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((m : ℕ) * s)^2 + ((m : ℕ) * t)^2 + ((m : ℕ) * u)^2 + ((m : ℕ) * v)^2 : by { simp [mul_pow], 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 [m], ring }, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) /-- **Four squares theorem** -/ 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 : _root_.fact (min_fac (k+2)).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, by exactI prime_sum_four_squares (min_fac (k+2)) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * w - b * x - c * y - d * z).nat_abs, (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, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp [sum_four_sq_mul_sum_four_sq], end⟩ end nat
ce990bc222a44c6202397840eea1a10ea17e1542
4fa161becb8ce7378a709f5992a594764699e268
/src/field_theory/splitting_field.lean
6822c25f64acb7030b75e5cf6f3f5696d1125918
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
8,901
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import data.polynomial import ring_theory.principal_ideal_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial noncomputable theory open_locale classical big_operators variables [field α] [field β] [field γ] open polynomial section splits variables (i : α →+* β) /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (classical.not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tautology)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : β →+* γ) {f : polynomial α} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_X_sub_C {x : α} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_id_iff_splits {f : polynomial α} : (f.map i).splits (ring_hom.id β) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial α} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end theorem splits_prod_iff {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (by rw [ne.def, map_eq_zero]; exact hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, is_noetherian_ring.irreducible_induction_on (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 :: s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, domain.mul_left_inj hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_domain local infix ` ~ᵤ ` : 50 := associated open unique_factorization_domain associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := unique (λ p hp, irreducible_factors (mt (map_eq_zero i).1 hf0) _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map' C : units β →* units (polynomial β)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (mt (map_eq_zero i).1 hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_domain.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits (ring_hom.id _) f → splits i f := unique_factorization_domain.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β →+* γ) {f : polynomial α} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end end splits end polynomial
61d6fc7cb38d5af20135a104e9dade5eae054203
88892181780ff536a81e794003fe058062f06758
/src/100_theorems/t017.lean
4e2ff6c1ccd1b2a5e8a1a98e962960c1587e0432
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
173
lean
import data.complex.exponential open complex theorem t017 : Π (n : ℕ) (z : ℂ), (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := cos_add_sin_mul_I_pow