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
84ba32646b4633cdeaf54d634fddf809dce04acb
da3a76c514d38801bae19e8a9e496dc31f8e5866
/library/init/meta/smt/ematch.lean
0d5eb2c7fffec64de72e63c384e0baa31b7fafb9
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
7,266
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.smt.congruence_closure import init.meta.attribute init.meta.simp_tactic open tactic /- Heuristic instantiation lemma -/ meta constant hinst_lemma : Type meta constant hinst_lemmas : Type /- (mk_core m e as_simp), m is used to decide which definitions will be unfolded in patterns. If as_simp is tt, then this tactic will try to use the left-hand-side of the conclusion as a pattern. -/ meta constant hinst_lemma.mk_core : transparency → expr → bool → tactic hinst_lemma meta constant hinst_lemma.mk_from_decl_core : transparency → name → bool → tactic hinst_lemma meta constant hinst_lemma.pp : hinst_lemma → tactic format meta constant hinst_lemma.id : hinst_lemma → name meta instance : has_to_tactic_format hinst_lemma := ⟨hinst_lemma.pp⟩ meta def hinst_lemma.mk (h : expr) : tactic hinst_lemma := hinst_lemma.mk_core reducible h ff meta def hinst_lemma.mk_from_decl (h : name) : tactic hinst_lemma := hinst_lemma.mk_from_decl_core reducible h ff meta constant hinst_lemmas.mk : hinst_lemmas meta constant hinst_lemmas.add : hinst_lemmas → hinst_lemma → hinst_lemmas meta constant hinst_lemmas.fold {α : Type} : hinst_lemmas → α → (hinst_lemma → α → α) → α meta constant hinst_lemmas.merge : hinst_lemmas → hinst_lemmas → hinst_lemmas meta def mk_hinst_singleton : hinst_lemma → hinst_lemmas := hinst_lemmas.add hinst_lemmas.mk meta def hinst_lemmas.pp (s : hinst_lemmas) : tactic format := let tac := s^.fold (return format.nil) (λ h tac, do hpp ← h^.pp, r ← tac, if r^.is_nil then return hpp else return (r ++ to_fmt "," ++ format.line ++ hpp)) in do r ← tac, return $ format.cbrace (format.group r) meta instance : has_to_tactic_format hinst_lemmas := ⟨hinst_lemmas.pp⟩ open tactic private meta def add_lemma (m : transparency) (as_simp : bool) (h : name) (hs : hinst_lemmas) : tactic hinst_lemmas := do h ← hinst_lemma.mk_from_decl_core m h as_simp, return $ hs^.add h meta def to_hinst_lemmas_core (m : transparency) : bool → list name → hinst_lemmas → tactic hinst_lemmas | as_simp [] hs := return hs | as_simp (n::ns) hs := let add n := add_lemma m as_simp n hs >>= to_hinst_lemmas_core as_simp ns in do /- First check if n is the name of a function with equational lemmas associated with it -/ eqns ← tactic.get_eqn_lemmas_for tt n, match eqns with | [] := do /- n is not the name of a function definition or it does not have equational lemmas, then check if it is a lemma -/ add n | _ := do p ← is_prop_decl n, if p then add n /- n is a proposition -/ else do /- Add equational lemmas to resulting hinst_lemmas -/ new_hs ← to_hinst_lemmas_core tt eqns hs, to_hinst_lemmas_core as_simp ns new_hs end meta def mk_hinst_lemma_attr_core (attr_name : name) (as_simp : bool) : command := do t ← to_expr ``(caching_user_attribute hinst_lemmas), a ← attr_name^.to_expr, b ← if as_simp then to_expr ``(tt) else to_expr ``(ff), v ← to_expr ``({name := %%a, descr := "hinst_lemma attribute", mk_cache := λ ns, to_hinst_lemmas_core reducible %%b ns hinst_lemmas.mk, dependencies := [`reducibility] } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def mk_hinst_lemma_attrs_core (as_simp : bool) : list name → command | [] := skip | (n::ns) := (mk_hinst_lemma_attr_core n as_simp >> mk_hinst_lemma_attrs_core ns) <|> (do type ← infer_type (expr.const n []), expected ← to_expr ``(caching_user_attribute hinst_lemmas), (is_def_eq type expected <|> fail ("failed to create hinst_lemma attribute '" ++ n^.to_string ++ "', declaration already exists and has different type.")), mk_hinst_lemma_attrs_core ns) meta def merge_hinst_lemma_attrs (m : transparency) (as_simp : bool) : list name → hinst_lemmas → tactic hinst_lemmas | [] hs := return hs | (attr::attrs) hs := do ns ← attribute.get_instances attr, new_hs ← to_hinst_lemmas_core m as_simp ns hs, merge_hinst_lemma_attrs attrs new_hs /-- Create a new "cached" attribute (attr_name : caching_user_attribute hinst_lemmas). It also creates "cached" attributes for each attr_names and simp_attr_names if they have not been defined yet. Moreover, the hinst_lemmas for attr_name will be the union of the lemmas tagged with attr_name, attrs_name, and simp_attr_names. For the ones in simp_attr_names, we use the left-hand-side of the conclusion as the pattern. -/ meta def mk_hinst_lemma_attr_set (attr_name : name) (attr_names : list name) (simp_attr_names : list name) : command := do mk_hinst_lemma_attrs_core ff attr_names, mk_hinst_lemma_attrs_core tt simp_attr_names, t ← to_expr ``(caching_user_attribute hinst_lemmas), a ← attr_name^.to_expr, l1 ← list_name.to_expr attr_names, l2 ← list_name.to_expr simp_attr_names, v ← to_expr ``({name := %%a, descr := "hinst_lemma attribute set", mk_cache := λ ns, let aux1 : list name := %%l1, aux2 : list name := %%l2 in do { hs₁ ← to_hinst_lemmas_core reducible ff ns hinst_lemmas.mk, hs₂ ← merge_hinst_lemma_attrs reducible ff aux1 hs₁, merge_hinst_lemma_attrs reducible tt aux2 hs₂}, dependencies := [`reducibility] ++ %%l1 ++ %%l2 } : caching_user_attribute hinst_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_hinst_lemmas_for_attr (attr_name : name) : tactic hinst_lemmas := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute hinst_lemmas) cnst, caching_user_attribute.get_cache attr structure ematch_config := (max_instances : nat := 10000) (max_generation : nat := 10) /- Ematching -/ meta constant ematch_state : Type meta constant ematch_state.mk : ematch_config → ematch_state meta constant ematch_state.internalize : ematch_state → expr → tactic ematch_state namespace tactic meta constant ematch_core : transparency → cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) meta constant ematch_all_core : transparency → cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) meta def ematch : cc_state → ematch_state → hinst_lemma → expr → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_core reducible meta def ematch_all : cc_state → ematch_state → hinst_lemma → bool → tactic (list (expr × expr) × cc_state × ematch_state) := ematch_all_core reducible end tactic
aeabebca205a1dc6dec86b3afa1ca7b1edf7e3d0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/completion6.lean
3bcf70d9af2a4b54c928227703be2b135ae20ba0
[ "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
335
lean
structure C where f1 : Nat f2 : Bool b1 : String structure D extends C where f3 : Bool def f (c : D) : IO Unit := visit c where visit (c : D) : IO Unit := let x := c. --^ textDocument/completion abbrev E := D def E.doubleF1 (e : E) := e.f1 + e.f1 def g (e : E) := e. --^ textDocument/completion
01c7377ce4e62e3087ee61b97c136b1853805ec7
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/rewrite12.lean
2c3251d96f39b4bfe60078ee5da8e74427122524
[ "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
313
lean
import data.nat open nat algebra variables (f : nat → nat → nat → nat) (a b c : nat) example (H₁ : a = b) (H₂ : f b a b = 0) : f a a a = 0 := by rewrite [H₁ at -{2}, H₂] example (H₁ : a = b) (H₂ : f b a b = 0) (H₃ : c = f a a a) : c = 0 := by rewrite [H₁ at H₃ -{2}, H₂ at H₃, H₃]
457ef59d35016a9c3b93ff9b128ccb422b48e450
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Data/Name.lean
5f166d94459ba32403f88d77d8e2b72be3233c1a
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
5,228
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Std.Data.HashSet import Std.Data.RBMap import Std.Data.RBTree namespace Lean instance : Coe String Name := ⟨Name.mkSimple⟩ namespace Name @[export lean_name_hash] def hashEx : Name → USize := Name.hash def getPrefix : Name → Name | anonymous => anonymous | str p s _ => p | num p s _ => p def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _ _) => n | n@(num anonymous _ _) => n | str n _ _ => getRoot n | num n _ _ => getRoot n def getString! : Name → String | str _ s _ => s | _ => unreachable! def getNumParts : Name → Nat | anonymous => 0 | str p _ _ => getNumParts p + 1 | num p _ _ => getNumParts p + 1 def updatePrefix : Name → Name → Name | anonymous, newP => anonymous | str p s _, newP => Name.mkStr newP s | num p s _, newP => Name.mkNum newP s def components' : Name → List Name | anonymous => [] | str n s _ => Name.mkStr anonymous s :: components' n | num n v _ => Name.mkNum anonymous v :: components' n def components (n : Name) : List Name := n.components'.reverse def eqStr : Name → String → Bool | str anonymous s _, s' => s == s' | _, _ => false def isPrefixOf : Name → Name → Bool | p, anonymous => p == anonymous | p, n@(num p' _ _) => p == n || isPrefixOf p p' | p, n@(str p' _ _) => p == n || isPrefixOf p p' def isSuffixOf : Name → Name → Bool | anonymous, _ => true | str p₁ s₁ _, str p₂ s₂ _ => s₁ == s₂ && isSuffixOf p₁ p₂ | num p₁ n₁ _, num p₂ n₂ _ => n₁ == n₂ && isSuffixOf p₁ p₂ | _, _ => false def lt : Name → Name → Bool | anonymous, anonymous => false | anonymous, _ => true | num p₁ i₁ _, num p₂ i₂ _ => lt p₁ p₂ || (p₁ == p₂ && i₁ < i₂) | num _ _ _, str _ _ _ => true | str p₁ n₁ _, str p₂ n₂ _ => lt p₁ p₂ || (p₁ == p₂ && n₁ < n₂) | _, _ => false def quickLtAux : Name → Name → Bool | anonymous, anonymous => false | anonymous, _ => true | num n v _, num n' v' _ => v < v' || (v = v' && n.quickLtAux n') | num _ _ _, str _ _ _ => true | str n s _, str n' s' _ => s < s' || (s = s' && n.quickLtAux n') | _, _ => false def quickLt (n₁ n₂ : Name) : Bool := if n₁.hash < n₂.hash then true else if n₁.hash > n₂.hash then false else quickLtAux n₁ n₂ /- Alternative HasLt instance. -/ @[inline] protected def hasLtQuick : HasLess Name := ⟨fun a b => Name.quickLt a b = true⟩ @[inline] instance : DecidableRel (@Less Name Name.hasLtQuick) := inferInstanceAs (DecidableRel (fun a b => Name.quickLt a b = true)) /- The frontend does not allow user declarations to start with `_` in any of its parts. We use name parts starting with `_` internally to create auxiliary names (e.g., `_private`). -/ def isInternal : Name → Bool | str p s _ => s.get 0 == '_' || isInternal p | num p _ _ => isInternal p | _ => false def isAtomic : Name → Bool | anonymous => true | str anonymous _ _ => true | num anonymous _ _ => true | _ => false def isAnonymous : Name → Bool | anonymous => true | _ => false def isStr : Name → Bool | str .. => true | _ => false def isNum : Name → Bool | num .. => true | _ => false end Name open Std (RBMap RBTree mkRBMap mkRBTree) def NameMap (α : Type) := Std.RBMap Name α Name.quickLt @[inline] def mkNameMap (α : Type) : NameMap α := Std.mkRBMap Name α Name.quickLt namespace NameMap variable {α : Type} instance (α : Type) : EmptyCollection (NameMap α) := ⟨mkNameMap α⟩ instance (α : Type) : Inhabited (NameMap α) where default := {} def insert (m : NameMap α) (n : Name) (a : α) := Std.RBMap.insert m n a def contains (m : NameMap α) (n : Name) : Bool := Std.RBMap.contains m n @[inline] def find? (m : NameMap α) (n : Name) : Option α := Std.RBMap.find? m n end NameMap def NameSet := RBTree Name Name.quickLt namespace NameSet def empty : NameSet := mkRBTree Name Name.quickLt instance : EmptyCollection NameSet := ⟨empty⟩ instance : Inhabited NameSet := ⟨{}⟩ def insert (s : NameSet) (n : Name) : NameSet := Std.RBTree.insert s n def contains (s : NameSet) (n : Name) : Bool := Std.RBMap.contains s n instance : ForIn m NameSet Name := inferInstanceAs (ForIn _ (Std.RBTree ..) ..) end NameSet def NameHashSet := Std.HashSet Name namespace NameHashSet @[inline] def empty : NameHashSet := Std.HashSet.empty instance : EmptyCollection NameHashSet := ⟨empty⟩ instance : Inhabited NameHashSet := ⟨{}⟩ def insert (s : NameHashSet) (n : Name) := Std.HashSet.insert s n def contains (s : NameHashSet) (n : Name) : Bool := Std.HashSet.contains s n end NameHashSet end Lean open Lean def String.toName (s : String) : Name := let ps := s.splitOn "."; ps.foldl (fun n p => Name.mkStr n p.trim) Name.anonymous
6a02116bcc0c661107b5b3190847d63591ee36f1
abd85493667895c57a7507870867b28124b3998f
/src/data/complex/exponential.lean
d948adcc3133fca499ee862df3c77b392970ac29
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
47,752
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose import data.complex.basic local notation `abs'` := _root_.abs open is_absolute_value open_locale classical section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g), have := add_lt_add hi₁ hi₂, rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), (range m).sum (λ n, (abv x) ^ n)) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, (range m).sum f) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) = (range n).sum (λ m, (range (n - m)).sum (f m)) := have h₁ : ((range n).sigma (range ∘ nat.succ)).sum (λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) = (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) := sum_sigma, have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) = (range n).sum (λ m, (range (n - m)).sum (f m)) := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f = ((range m).filter (λ k, n ≤ k)).sum f := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n)))) (hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b - (range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : (range K).sum (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) = (range K).sum (λ m, (range (K - m)).sum (λ n, a m * b n)), by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b), by simp [finset.mul_sum], have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) = (range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b)) + (range K).sum (λ i, a i * (range K).sum b), by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum (λ i, abv (a i) * (ε / (2 * P))), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : (range (max N M + 1)).sum (λ n, abv (a n)) < P := calc (range (max N M + 1)).sum (λ n, abv (a n)) = abs ((range (max N M + 1)).sum (λ n, abv (a n))) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) + ((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ((range K).filter (λ k, max N M + 1 ≤ k)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ ((range K).filter (λ k, max N M + 1 ≤ k)).sum (λ i, abv (a i) * (2 * Q)) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) := is_cau_series_of_abv_cau (is_cau_abs_exp z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩ def exp (z : ℂ) : ℂ := lim (exp' z) def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 def tan (z : ℂ) : ℂ := sin z / cos z def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex def exp (x : ℝ) : ℝ := (exp x).re def sin (x : ℝ) : ℝ := (sin x).re def cos (x : ℝ) : ℝ := (cos x).re def tan (x : ℝ) : ℝ := (tan x).re def sinh (x : ℝ) : ℝ := (sinh x).re def cosh (x : ℝ) : ℝ := (cosh x).re def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, (range j).sum (λ m, (x + y) ^ m / m.fact) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact * (y ^ (i - k) / (i - k).fact))), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (nat.choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (nat.choose m i : ℂ), mul_assoc, mul_left_comm (nat.choose m i : ℂ)⁻¹, mul_comm (nat.choose m i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (s.sum f) = s.prod (exp ∘ f) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_right_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom _ conj, refine sum_congr rfl (λ n hn, _), rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two] @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← domain.mul_right_inj (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← domain.mul_left_inj I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj_mul, ← conj_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_sq_add_cos_sq x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (s.sum f) = s.prod (exp ∘ f) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simpa using sin_sq_add_cos_sq x lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right' (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left' (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (sin x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply sin_sq_le_one lemma abs_cos_le_one : abs' (cos x) ≤ 1 := (mul_self_le_mul_self_iff (_root_.abs_nonneg (cos x)) (by exact zero_le_one)).2 $ by rw [← _root_.abs_mul, abs_mul_self, mul_one, ← pow_two]; apply cos_sq_le_one lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) ≤ n.succ * (n.fact * n)⁻¹ := calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) = (range (j - n)).sum (λ m, 1 / (m + n).fact) : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ))) = abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ (filter (λ k, n ≤ k) (range j)).sum (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _ ... ≤ (filter (λ k, n ≤ k) (range j)).sum (λ m, abs x ^ n * (1 / m.fact)) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - (range 2).sum (λ m, x ^ m / m.fact)) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (nat.fact 2 * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) + ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) - (complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) + abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
9fd6a10dfbc643a4c2edc72f4e3904ede090b336
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/tests/lean/StxQuot.lean
7f749fff832dcdbb2180bb6149ffa8857b74fe71
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
4,408
lean
import Lean open Lean open Lean.Elab def run {α} [ToString α] : Unhygienic α → String := toString ∘ Unhygienic.run #eval run `() #eval run `(Nat.one) #eval run `($Syntax.missing) namespace Lean.Syntax #eval run `($missing) #eval run `($(missing)) #eval run `($(id Syntax.missing) + 1) #eval run $ let id := Syntax.missing; `($id + 1) end Lean.Syntax #eval run `(1 + 1) #eval run `([x,]) #eval run $ `(fun a => a) >>= pure #eval run $ `(def foo := 1) #eval run $ `(def foo := 1 def bar := 2) #eval run $ do let a ← `(Nat.one); `($a) #eval run $ do `($(← `(Nat.one))) #eval run $ do let a ← `(Nat.one); `(f $a $a) #eval run $ do let a ← `(Nat.one); `(f $ f $a 1) #eval run $ do let a ← `(Nat.one); `(f $(id a)) #eval run $ do let a ← `(Nat.one); `($(a).b) #eval run $ do let a ← `(1 + 2); match a with | `($a + $b) => `($b + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(1 + 2); match a with | stx@`($a + $b) => `($stx + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1); match a with | `($f:command) => pure f | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1 def bar := 2); match a with | `($f:command $g:command) => `($g:command $f:command) | _ => pure Syntax.missing #eval run $ do let a ← `(aa); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval match mkIdent `aa with | `(aa) => 0 | _ => 1 #eval match mkIdent `aa with | `(ab) => 0 | _ => 1 #eval run $ do let a ← `(1 + 2); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval run $ do let params ← #[`(a), `((b : Nat))].mapM id; `(fun $params* => 1) #eval run $ do let a ← `(fun (a : Nat) b => c); match a with | `(fun $aa* => $e) => pure aa | _ => pure #[] #eval run $ do let a ← `(∀ a, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a -- this one should NOT check the kind of the matched node #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $a, $e) => pure a | _ => pure a #eval run $ do let a ← `(a); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(a.{0}); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(match a with | a => 1 | _ => 2); match a with | `(match $e:term with $eqns:matchAlt*) => pure eqns | _ => pure #[] def f (stx : Syntax) : Unhygienic Syntax := match stx with | `({ $f:ident := $e $[: $a]?}) => `({ $f:ident := $e $[: $(id a)]?}) | _ => unreachable! #eval run do f (← `({ a := a : a })) #eval run do f (← `({ a := a })) def f' (stx : Syntax) : Unhygienic Syntax := match stx with | `(section $(id?)?) => `(section $(id?)?) | _ => unreachable! #eval run do f' (← `(section)) #eval run do f' (← `(section foo)) #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $[| $pats =>%$arr $rhss]*) => `(match $e:term with $[| $pats =>%$arr $rhss]*) | _ => unreachable! #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $alts:matchAlt*) => `(match $e:term with $alts:matchAlt*) | _ => unreachable! open Parser.Term #eval run do match ← `(structInstField|a := b) with | `(Parser.Term.structInstField| $lhs:ident := $rhs) => #[lhs, rhs] | _ => unreachable! #eval run do match ← `({ a := a : a }) with | `({ $f:ident := $e : 0 }) => "0" | `({ $f:ident := $e $[: $a?]?}) => "1" | stx => "2" #eval run `(sufficesDecl|x from x) #eval run do match ← `([1, 2, 3, 4]) with | `([$x, $ys,*, $z]) => #[x, mkNullNode ys, z] | _ => unreachable! #eval run do match ← `([1, 2]) with | `([$x, $y, $zs,*]) => zs.getElems | `([$x, $ys,*]) => ys.getElems | _ => unreachable! #check (match · with | `([1, $ys,*, 2, $zs,*, 3]) => _) #eval run do match Syntax.setHeadInfo (← `(fun x =>%$(Syntax.atom (SourceInfo.synthetic 2 2) "") x)) (SourceInfo.synthetic 1 1) with | `(fun%$i1 $x =>%$i2 $y) => pure #[i1.getPos?, i2.getPos?] | _ => unreachable! #eval run ``(x) #eval run ``(id) #eval run ``(pure) syntax "foo" term : term #eval run ``(foo $(Syntax.missing)) -- syntax with no quoted identifiers should be ignored #eval run ``(fun x => x) #eval run ``(fun x => y) #eval run ``(fun x y => x y) #eval run ``(fun ⟨x, y⟩ => x)
c38d0d8d8c67fabe557708a30aad95dfb88e1dd3
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/polynomial/ring_division.lean
072004c4612b368ff60f4157706d1563403b5387
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
13,794
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.div import tactic.omega /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : polynomial R} variables [comm_ring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval R S z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval R S z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) end comm_ring section integral_domain variables [integral_domain R] {p q : polynomial R} instance : integral_domain (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nontrivial, ..polynomial.comm_ring } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] @[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end lemma exists_finset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : finset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial R) : finset R := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma roots_mul (hpq : p * q ≠ 0) : (p * q).roots = p.roots ∪ q.roots := finset.ext $ λ r, by rw [mem_union, mem_roots hpq, mem_roots (mul_ne_zero_iff.1 hpq).1, mem_roots (mul_ne_zero_iff.1 hpq).2, root_mul] @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := finset.ext $ λ s, by rw [mem_roots (X_sub_C_ne_zero r), root_X_sub_C, mem_singleton, eq_comm] lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : finset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {R : Type*} [integral_domain R] {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa finsupp.mem_support_iff at hbs, refine coeff_eq_zero_of_degree_lt _, rw [degree_mul], erw degree_C this, rw [degree_pow, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], rw mul_lt_mul_right, apply lt_of_le_of_ne, assumption', swap, omega, exact le_nat_degree_of_ne_zero this, end begin intro h, contrapose! hp0, rw finsupp.mem_support_iff at h, push_neg at h, rwa ← leading_coeff_eq_zero, end ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) theorem prime_X_sub_C {r : R} : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : polynomial R) := by simpa only [C_0, sub_zero] using (prime_X_sub_C : prime (X - C 0 : polynomial R)) lemma prime_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := irreducible_of_prime prime_X_sub_C theorem irreducible_X : irreducible (X : polynomial R) := irreducible_of_prime prime_X lemma irreducible_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm) end integral_domain end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
00b9cc368de335e4983ca591bf213c8b99be32f9
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/quadratic_reciprocity.lean
08cb32c694fa141440ec9b63e9e4580c40b2f60a
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
24,998
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 field_theory.finite.basic import data.zmod.basic import data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_sq_eq_prime_iff_of_mod_four_eq_one`, and `exists_sq_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_sq_eq_neg_one_iff_mod_four_ne_three` and `exists_sq_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmod open_locale big_operators nat namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : (zmod p)ˣ) : (∃ y : (zmod p)ˣ, y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim }, obtain ⟨g, hg⟩ := is_cyclic.exists_generator (zmod p)ˣ, obtain ⟨n, hn⟩ : x ∈ submonoid.powers g, { rw mem_powers_iff_mem_zpowers, apply hg }, split, { rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, units_pow_card_sub_one_eq_one], }, { subst x, assume h, have key : 2 * (p / 2) ∣ n * (p / 2), { rw [← pow_mul] at h, rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_zpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < p / 2 := nat.div_pos (fact.out (1 < p)) dec_trivial, obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul], }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : (∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_sq_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, exact dec_trivial }, haveI := fact.mk hp_odd, have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd, { rw [p_half_even, pow_zero, eq_self_iff_true, true_iff], contrapose! p_half_even with hp, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp], exact dec_trivial }, { rw [p_half_odd, pow_one, iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd, have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp hp_odd p_half_odd, generalize : p % 4 = k, dec_trivial! } end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, revert a ha, exact dec_trivial }, rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact pow_card_sub_one_eq_one ha end /-- **Wilson's Lemma**: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : ((p - 1)! : zmod p) = -1 := begin refine calc ((p - 1)! : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) : by rw [← finset.prod_Ico_id_eq_factorial, prod_nat_cast] ... = (∏ x : (zmod p)ˣ, x) : _ ... = -1 : by simp_rw [← units.coe_hom_apply, ← (units.coe_hom (zmod p)).map_prod, prod_univ_units_id_eq_neg_one, units.coe_hom_apply, units.coe_neg, units.coe_one], have hp : 0 < p := (fact.out p.prime).pos, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [mem_Ico, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [mem_Ico, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (fact.out p.prime).pos] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_factorial, wilsons_lemma] end end zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.1.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, mem_Ico.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw nat_cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj le_rfl) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, card_Ico, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [nat_cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.1.dvd_factorial, not_le]; exact nat.div_lt_self hp.1.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap private lemma eisenstein_lemma_aux₁ (p : ℕ) [fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2.1, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_nat_cast]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, nat.cast_sum, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [nat.cast_sum] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, nat.cast_sum], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [nat.cast_sum]) rfl private lemma eisenstein_lemma_aux₂ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, nat.cast_sum, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ (mem_Ico.mp hx).2) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, mem_Ico, mem_product] at *; tauto) (nat.div_lt_self hp.1.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, nonpos_iff_eq_zero, mem_Ico, one_ne_zero, false_and, mem_product] using hx }, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, mem_Ico, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [card_Ico, tsub_zero, succ_sub_succ_eq_sub] end variables (p q : ℕ) [fact p.prime] [fact q.prime] namespace zmod /-- The Legendre symbol of `a` and `p` is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a ^ (p / 2)` is `1` modulo `p` (by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”); * `-1` otherwise. -/ def legendre_sym (a : ℤ) (p : ℕ) : ℤ := if (a : zmod p) = 0 then 0 else if (a : zmod p) ^ (p / 2) = 1 then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] : (legendre_sym a p : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [int.cast_coe_nat, if_pos, ha, zero_pow (nat.div_pos (hp.1.two_le) (succ_pos 1)), int.cast_zero] }, cases hp.1.eq_two_or_odd with hp2 hp_odd, { substI p, generalize : (a : (zmod 2)) = b, revert b, dec_trivial, }, { haveI := fact.mk hp_odd, rw [int.cast_coe_nat, if_neg ha], have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm, cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg this, int.cast_neg, int.cast_one], } } end lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) : legendre_sym a p = -1 ∨ legendre_sym a p = 1 := begin unfold legendre_sym, split_ifs; simp only [*, eq_self_iff_true, or_true, true_or, int.cast_coe_nat] at *, end lemma legendre_sym_eq_zero_iff (a p : ℕ) : legendre_sym a p = 0 ↔ (a : zmod p) = 0 := begin split, { classical, contrapose, assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h, all_goals { rw h, norm_num } }, { assume ha, rw [legendre_sym, int.cast_coe_nat, if_pos ha] } end /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} [fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a p ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) := begin rw [euler_criterion p ha0, legendre_sym, int.cast_coe_nat, if_neg ha0], split_ifs, { simp only [h, eq_self_iff_true] }, { simp only [h, iff_false], tauto } end lemma eisenstein_lemma [fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0] /-- **Quadratic reciprocity theorem** -/ theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) : legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hp1.1 hpq0, eisenstein_lemma p hq1.1 hqp0, ← pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1.1), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ (mem_Ico.mp hx).2) dec_trivial ... < _ : by conv_rhs {rw [← div_add_mod p 2, hp1.1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin erw [gauss_lemma p (prime_ne_zero p 2 hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_sq_eq_two_iff [hp1 : fact (p % 2 = 1)] : (∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1.1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2], erw [legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), resetI, rw fact_iff at hp1, revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, unfreezingI {clear_dependent p}, dec_trivial!, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] : (∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p := if hpq : p = q then by substI hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_one hp1⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, int.cast_coe_nat, int.cast_coe_nat, if_neg hqp0, if_neg hpq0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_three hp3⟩, haveI hq_odd : fact (q % 2 = 1) := ⟨odd_of_mod_four_eq_three hq3⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, int.cast_coe_nat, int.cast_coe_nat, if_neg hpq0, if_neg hqp0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction end end zmod
021a458c27ff6ec7b583f58a8d082f92b9879467
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/dsimp_at1.lean
1e077afe19ef4cdefdcf5610505dae5973f14260
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
305
lean
open tactic constants (A : Type.{1}) (x y : A) noncomputable definition f (z : A) : A := z @[simp] definition f.def (z:A) : f z = z := rfl definition foo (z₁ z₂ : A) : f z₁ = f z₂ → z₁ = z₂ := by do H ← intro `H, trace_state, dsimp_at H, trace_state, assumption
4e2b7e61be6d3065f55f2c36421a9f0bb91ef353
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/essential_image.lean
e5cbab18144e608dd0a5cad26434c780695c4844
[ "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
5,363
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.natural_isomorphism import category_theory.full_subcategory import data.set.basic /-! # Essential image of a functor The essential image `ess_image` of a functor consists of the objects in the target category which are isomorphic to an object in the image of the object function. This, for instance, allows us to talk about objects belonging to a subcategory expressed as a functor rather than a subtype, preserving the principle of equivalence. For example this lets us define exponential ideals. The essential image can also be seen as a subcategory of the target category, and witnesses that a functor decomposes into a essentially surjective functor and a fully faithful functor. (TODO: show that this decomposition forms an orthogonal factorisation system). -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₂} D] {F : C ⥤ D} namespace functor /-- The essential image of a functor `F` consists of those objects in the target category which are isomorphic to an object in the image of the function `F.obj`. In other words, this is the closure under isomorphism of the function `F.obj`. This is the "non-evil" way of describing the image of a functor. -/ def ess_image (F : C ⥤ D) : set D := λ Y, ∃ (X : C), nonempty (F.obj X ≅ Y) /-- Get the witnessing object that `Y` is in the subcategory given by `F`. -/ def ess_image.witness {Y : D} (h : Y ∈ F.ess_image) : C := h.some /-- Extract the isomorphism between `F.obj h.witness` and `Y` itself. -/ def ess_image.get_iso {Y : D} (h : Y ∈ F.ess_image) : F.obj h.witness ≅ Y := classical.choice h.some_spec /-- Being in the essential image is a "hygenic" property: it is preserved under isomorphism. -/ lemma ess_image.of_iso {Y Y' : D} (h : Y ≅ Y') (hY : Y ∈ ess_image F) : Y' ∈ ess_image F := hY.imp (λ B, nonempty.map (≪≫ h)) /-- If `Y` is in the essential image of `F` then it is in the essential image of `F'` as long as `F ≅ F'`. -/ lemma ess_image.of_nat_iso {F' : C ⥤ D} (h : F ≅ F') {Y : D} (hY : Y ∈ ess_image F) : Y ∈ ess_image F' := hY.imp (λ X, nonempty.map (λ t, h.symm.app X ≪≫ t)) /-- Isomorphic functors have equal essential images. -/ lemma ess_image_eq_of_nat_iso {F' : C ⥤ D} (h : F ≅ F') : ess_image F = ess_image F' := set.ext $ λ A, ⟨ess_image.of_nat_iso h, ess_image.of_nat_iso h.symm⟩ /-- An object in the image is in the essential image. -/ lemma obj_mem_ess_image (F : D ⥤ C) (Y : D) : F.obj Y ∈ ess_image F := ⟨Y, ⟨iso.refl _⟩⟩ /-- The essential image of a functor, interpreted of a full subcategory of the target category. -/ @[derive category, nolint has_nonempty_instance] def ess_image_subcategory (F : C ⥤ D) := full_subcategory F.ess_image /-- The essential image as a subcategory has a fully faithful inclusion into the target category. -/ @[derive [full, faithful], simps] def ess_image_inclusion (F : C ⥤ D) : F.ess_image_subcategory ⥤ D := full_subcategory_inclusion _ /-- Given a functor `F : C ⥤ D`, we have an (essentially surjective) functor from `C` to the essential image of `F`. -/ @[simps] def to_ess_image (F : C ⥤ D) : C ⥤ F.ess_image_subcategory := full_subcategory.lift _ F (obj_mem_ess_image _) /-- The functor `F` factorises through its essential image, where the first functor is essentially surjective and the second is fully faithful. -/ @[simps] def to_ess_image_comp_essential_image_inclusion (F : C ⥤ D) : F.to_ess_image ⋙ F.ess_image_inclusion ≅ F := full_subcategory.lift_comp_inclusion _ _ _ end functor /-- A functor `F : C ⥤ D` is essentially surjective if every object of `D` is in the essential image of `F`. In other words, for every `Y : D`, there is some `X : C` with `F.obj X ≅ Y`. See <https://stacks.math.columbia.edu/tag/001C>. -/ class ess_surj (F : C ⥤ D) : Prop := (mem_ess_image [] (Y : D) : Y ∈ F.ess_image) instance : ess_surj F.to_ess_image := { mem_ess_image := λ ⟨Y, hY⟩, ⟨_, ⟨⟨_, _, hY.get_iso.hom_inv_id, hY.get_iso.inv_hom_id⟩⟩⟩ } variables (F) [ess_surj F] /-- Given an essentially surjective functor, we can find a preimage for every object `Y` in the codomain. Applying the functor to this preimage will yield an object isomorphic to `Y`, see `obj_obj_preimage_iso`. -/ def functor.obj_preimage (Y : D) : C := (ess_surj.mem_ess_image F Y).witness /-- Applying an essentially surjective functor to a preimage of `Y` yields an object that is isomorphic to `Y`. -/ def functor.obj_obj_preimage_iso (Y : D) : F.obj (F.obj_preimage Y) ≅ Y := (ess_surj.mem_ess_image F Y).get_iso /-- The induced functor of a faithful functor is faithful -/ instance faithful.to_ess_image (F : C ⥤ D) [faithful F] : faithful F.to_ess_image := faithful.of_comp_iso F.to_ess_image_comp_essential_image_inclusion /-- The induced functor of a full functor is full -/ instance full.to_ess_image (F : C ⥤ D) [full F] : full F.to_ess_image := begin haveI := full.of_iso F.to_ess_image_comp_essential_image_inclusion.symm, exactI full.of_comp_faithful F.to_ess_image F.ess_image_inclusion end end category_theory
d49d290f58052df733ef1c1e8868763b76dc3c95
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/topology/sequences.lean
ace615504da43639bd23f09496d07f358258c2d1
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
8,503
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot -/ import topology.basic import topology.bases import topology.subset_properties /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. In particular, we * associate a filter with a sequence and prove equivalence of convergence of the two, * define the sequential closure of a set and prove that it's contained in the closure, * define a type class "sequential_space" in which closure and sequential closure agree, * define sequential continuity and show that it coincides with continuity in sequential spaces, * provide an instance that shows that every first-countable (and in particular metric) space is a sequential space. # TODO * Sequential compactness should be handled here. -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit) /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space α] [topological_space β] /-- A sequence converges in the sence of topological spaces iff the associated statement for filter holds. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} : tendsto x at_top (𝓝 limit) ↔ ∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $ by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id] /-- The sequential closure of a subset M ⊆ α of a topological space α is the set of all p ∈ α which arise as limit of sequences in M. -/ def sequential_closure (M : set α) : set α := {p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)} lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M := assume p (_ : p ∈ M), show p ∈ sequential_closure M, from ⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩ /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. -/ def is_seq_closed (s : set α) : Prop := s = sequential_closure s /-- A convenience lemma for showing that a set is sequentially closed. -/ lemma is_seq_closed_of_def {A : set α} (h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A := show A = sequential_closure A, from subset.antisymm (subset_sequential_closure A) (show ∀ p, p ∈ sequential_closure A → p ∈ A, from (assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›)) /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M := assume p ⟨x, xM, xp⟩, mem_closure_of_tendsto at_top_ne_bot xp (univ_mem_sets' xM) /-- A set is sequentially closed if it is closed. -/ lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M := suffices sequential_closure M ⊆ M, from set.eq_of_subset_of_subset (subset_sequential_closure M) this, calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M ... = M : closure_eq_of_is_closed ‹is_closed M› /-- The limit of a convergent sequence in a sequentially closed set is in that set.-/ lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A := have limit ∈ sequential_closure A, from show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩, eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A› /-- The limit of a convergent sequence in a closed set is in that set.-/ lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A := mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)› /-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be formalised by demanding that the sequential closure and the closure coincide. The following statements show that other topological properties can be deduced from sequences in sequential spaces. -/ class sequential_space (α : Type*) [topological_space α] : Prop := (sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M) /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} : is_seq_closed M ↔ is_closed M := iff.intro (assume _, closure_eq_iff_is_closed.mp (eq.symm (calc M = sequential_closure M : by assumption ... = closure M : sequential_space.sequential_closure_eq_closure M))) (is_seq_closed_of_is_closed M) /-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) := by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl } /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def sequentially_continuous (f : α → β) : Prop := ∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit) /- A continuous function is sequentially continuous. -/ lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) : sequentially_continuous f := assume x limit (_ : x ⟶ limit), have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit, show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)› /-- In a sequential space, continuity and sequential continuity coincide. -/ lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] : continuous f ↔ sequentially_continuous f := iff.intro (assume _, ‹continuous f›.to_sequentially_continuous) (assume : sequentially_continuous f, show continuous f, from suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›), assume A (_ : is_closed A), is_seq_closed_of_def $ assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p), have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›, show f p ∈ A, from mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›) end topological_space namespace topological_space namespace first_countable_topology variables [topological_space α] [first_countable_topology α] /-- Every first-countable space is sequential. -/ @[priority 100] -- see Note [lower instance priority] instance : sequential_space α := ⟨show ∀ M, sequential_closure M = closure M, from assume M, suffices closure M ⊆ sequential_closure M, from set.subset.antisymm (sequential_closure_subset_closure M) this, -- For every p ∈ closure M, we need to construct a sequence x in M that converges to p: assume (p : α) (hp : p ∈ closure M), -- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing -- basis `U` indexed by `ℕ`. let ⟨U, hU ⟩ := (nhds_generated_countable p).has_antimono_basis in -- Since `p ∈ closure M`, there is an element in each `M ∩ U i` have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i, by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp, begin -- The axiom of (countable) choice builds our sequence from the later fact choose u hu using hp, rw forall_and_distrib at hu, -- It clearly takes values in `M` use [u, hu.1], -- and converges to `p` because the basis is decreasing. apply hU.tendsto hu.2, end⟩ end first_countable_topology end topological_space
df14bfffe231a728b3b149804e8779df26f6b27a
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/local_eqns.lean
ff0b07874e0f350a2d1bfdd00c36499648b511ab
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,538
lean
import data.nat logic open bool nat check show nat → bool | 0 := tt | (n+1) := ff definition mult : nat → nat → nat := have plus : nat → nat → nat | 0 b := b | (succ a) b := succ (plus a b), have mult : nat → nat → nat | 0 b := 0 | (succ a) b := plus (mult a b) b, mult print definition mult example : mult 3 7 = 21 := rfl example : mult 8 7 = 56 := rfl theorem add_eq_addl : ∀ x y, x + y = x ⊕ y | 0 0 := rfl | (succ x) 0 := begin have addl_z : ∀ a : nat, a ⊕ 0 = a | 0 := rfl | (succ a) := calc (succ a) ⊕ 0 = succ (a ⊕ 0) : rfl ... = succ a : addl_z, rewrite addl_z end | 0 (succ y) := begin have z_add : ∀ a : nat, 0 + a = a | 0 := rfl | (succ a) := begin rewrite ▸ succ(0 + a) = _, rewrite z_add end, rewrite z_add end | (succ x) (succ y) := begin change (succ x + succ y = succ (x ⊕ succ y)), have s_add : ∀ a b : nat, succ a + b = succ (a + b) | 0 0 := rfl | (succ a) 0 := rfl | 0 (succ b) := begin change (succ (succ 0 + b) = succ (succ (0 + b))), rewrite -(s_add 0 b) end | (succ a) (succ b) := begin change (succ (succ (succ a) + b) = succ (succ (succ a + b))), apply (congr_arg succ), rewrite (s_add (succ a) b), end, rewrite [s_add, add_eq_addl] end reveal add_eq_addl print definition add_eq_addl
c76c1145b6c734e13a33a9dffd82e914e3ba6348
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/real/pi/wallis.lean
0795c52c2b56aa278e3fd54be37b5593197c277f
[ "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,862
lean
/- Copyright (c) 2021 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import analysis.special_functions.integrals /-! ### The Wallis Product for Pi -/ namespace real open_locale real topological_space big_operators open filter finset interval_integral lemma integral_sin_pow_div_tendsto_one : tendsto (λ k, (∫ x in 0..π, sin x ^ (2 * k + 1)) / ∫ x in 0..π, sin x ^ (2 * k)) at_top (𝓝 1) := begin have h₃ : ∀ n, (∫ x in 0..π, sin x ^ (2 * n + 1)) / ∫ x in 0..π, sin x ^ (2 * n) ≤ 1 := λ n, (div_le_one (integral_sin_pow_pos _)).mpr (integral_sin_pow_succ_le _), have h₄ : ∀ n, (∫ x in 0..π, sin x ^ (2 * n + 1)) / ∫ x in 0..π, sin x ^ (2 * n) ≥ 2 * n / (2 * n + 1), { rintro ⟨n⟩, { have : 0 ≤ (1 + 1) / π, exact div_nonneg (by norm_num) pi_pos.le, simp [this] }, calc (∫ x in 0..π, sin x ^ (2 * n.succ + 1)) / ∫ x in 0..π, sin x ^ (2 * n.succ) ≥ (∫ x in 0..π, sin x ^ (2 * n.succ + 1)) / ∫ x in 0..π, sin x ^ (2 * n + 1) : by { refine div_le_div (integral_sin_pow_pos _).le le_rfl (integral_sin_pow_pos _) _, convert integral_sin_pow_succ_le (2 * n + 1) using 1 } ... = 2 * ↑(n.succ) / (2 * ↑(n.succ) + 1) : by { rw div_eq_iff (integral_sin_pow_pos (2 * n + 1)).ne', convert integral_sin_pow (2 * n + 1), simp with field_simps, norm_cast } }, refine tendsto_of_tendsto_of_tendsto_of_le_of_le _ _ (λ n, (h₄ n).le) (λ n, (h₃ n)), { refine metric.tendsto_at_top.mpr (λ ε hε, ⟨⌈1 / ε⌉₊, λ n hn, _⟩), have h : (2:ℝ) * n / (2 * n + 1) - 1 = -1 / (2 * n + 1), { conv_lhs { congr, skip, rw ← @div_self _ _ ((2:ℝ) * n + 1) (by { norm_cast, linarith }), }, rw [← sub_div, ← sub_sub, sub_self, zero_sub] }, have hpos : (0:ℝ) < 2 * n + 1, { norm_cast, norm_num }, rw [dist_eq, h, abs_div, abs_neg, abs_one, abs_of_pos hpos, one_div_lt hpos hε], calc 1 / ε ≤ ⌈1 / ε⌉₊ : nat.le_ceil _ ... ≤ n : by exact_mod_cast hn.le ... < 2 * n + 1 : by { norm_cast, linarith } }, { exact tendsto_const_nhds }, end /-- This theorem establishes the Wallis Product for `π`. Our proof is largely about analyzing the behavior of the ratio of the integral of `sin x ^ n` as `n → ∞`. See: https://en.wikipedia.org/wiki/Wallis_product The proof can be broken down into two pieces. (Pieces involving general properties of the integral of `sin x ^n` can be found in `analysis.special_functions.integrals`.) First, we use integration by parts to obtain a recursive formula for `∫ x in 0..π, sin x ^ (n + 2)` in terms of `∫ x in 0..π, sin x ^ n`. From this we can obtain closed form products of `∫ x in 0..π, sin x ^ (2 * n)` and `∫ x in 0..π, sin x ^ (2 * n + 1)` via induction. Next, we study the behavior of the ratio `∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1)) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that it converges to one using the squeeze theorem. The final product for `π` is obtained after some algebraic manipulation. -/ theorem tendsto_prod_pi_div_two : tendsto (λ k, ∏ i in range k, (((2:ℝ) * i + 2) / (2 * i + 1)) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 (π/2)) := begin suffices h : tendsto (λ k, (π / 2)⁻¹ * ∏ i in range k, (2 * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3))) at_top (𝓝 1), { convert h.const_mul (π / 2), { simp_rw mul_inv_cancel_left₀ (show π / 2 ≠ 0, by norm_num [pi_ne_zero]) }, { rw mul_one } }, convert integral_sin_pow_div_tendsto_one, funext, rw [integral_sin_pow_even, integral_sin_pow_odd, mul_div_mul_comm, ←prod_div_distrib, inv_div], congr' with i, rw [div_div_div_comm, div_div_eq_mul_div, mul_div_assoc], end end real
f3786c9ae23f2cdfd4025a2ab93c0ba42945c212
bb31430994044506fa42fd667e2d556327e18dfe
/src/order/partial_sups.lean
41e97ca76bed38ca07525440464cc62efb77d51e
[ "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,842
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.finset.lattice import order.hom.basic import order.conditionally_complete_lattice.finset /-! # The monotone sequence of partial supremums of a sequence We define `partial_sups : (ℕ → α) → ℕ →o α` inductively. For `f : ℕ → α`, `partial_sups f` is the sequence `f 0 `, `f 0 ⊔ f 1`, `f 0 ⊔ f 1 ⊔ f 2`, ... The point of this definition is that * it doesn't need a `⨆`, as opposed to `⨆ (i ≤ n), f i` (which also means the wrong thing on `conditionally_complete_lattice`s). * it doesn't need a `⊥`, as opposed to `(finset.range (n + 1)).sup f`. * it avoids needing to prove that `finset.range (n + 1)` is nonempty to use `finset.sup'`. Equivalence with those definitions is shown by `partial_sups_eq_bsupr`, `partial_sups_eq_sup_range`, `partial_sups_eq_sup'_range` and respectively. ## Notes One might dispute whether this sequence should start at `f 0` or `⊥`. We choose the former because : * Starting at `⊥` requires... having a bottom element. * `λ f n, (finset.range n).sup f` is already effectively the sequence starting at `⊥`. * If we started at `⊥` we wouldn't have the Galois insertion. See `partial_sups.gi`. ## TODO One could generalize `partial_sups` to any locally finite bot preorder domain, in place of `ℕ`. Necessary for the TODO in the module docstring of `order.disjointed`. -/ variables {α : Type*} section semilattice_sup variables [semilattice_sup α] /-- The monotone sequence whose value at `n` is the supremum of the `f m` where `m ≤ n`. -/ def partial_sups (f : ℕ → α) : ℕ →o α := ⟨@nat.rec (λ _, α) (f 0) (λ (n : ℕ) (a : α), a ⊔ f (n + 1)), monotone_nat_of_le_succ (λ n, le_sup_left)⟩ @[simp] lemma partial_sups_zero (f : ℕ → α) : partial_sups f 0 = f 0 := rfl @[simp] lemma partial_sups_succ (f : ℕ → α) (n : ℕ) : partial_sups f (n + 1) = partial_sups f n ⊔ f (n + 1) := rfl lemma le_partial_sups_of_le (f : ℕ → α) {m n : ℕ} (h : m ≤ n) : f m ≤ partial_sups f n := begin induction n with n ih, { cases h, exact le_rfl, }, { cases h with h h, { exact le_sup_right, }, { exact (ih h).trans le_sup_left, } }, end lemma le_partial_sups (f : ℕ → α) : f ≤ partial_sups f := λ n, le_partial_sups_of_le f le_rfl lemma partial_sups_le (f : ℕ → α) (n : ℕ) (a : α) (w : ∀ m, m ≤ n → f m ≤ a) : partial_sups f n ≤ a := begin induction n with n ih, { apply w 0 le_rfl, }, { exact sup_le (ih (λ m p, w m (nat.le_succ_of_le p))) (w (n + 1) le_rfl) } end @[simp] lemma bdd_above_range_partial_sups {f : ℕ → α} : bdd_above (set.range (partial_sups f)) ↔ bdd_above (set.range f) := begin apply exists_congr (λ a, _), split, { rintros h b ⟨i, rfl⟩, exact (le_partial_sups _ _).trans (h (set.mem_range_self i)) }, { rintros h b ⟨i, rfl⟩, exact (partial_sups_le _ _ _ $ λ _ _, h (set.mem_range_self _)), }, end lemma monotone.partial_sups_eq {f : ℕ → α} (hf : monotone f) : (partial_sups f : ℕ → α) = f := begin ext n, induction n with n ih, { refl }, { rw [partial_sups_succ, ih, sup_eq_right.2 (hf (nat.le_succ _))] } end lemma partial_sups_mono : monotone (partial_sups : (ℕ → α) → ℕ →o α) := begin rintro f g h n, induction n with n ih, { exact h 0 }, { exact sup_le_sup ih (h _) } end /-- `partial_sups` forms a Galois insertion with the coercion from monotone functions to functions. -/ def partial_sups.gi : galois_insertion (partial_sups : (ℕ → α) → ℕ →o α) coe_fn := { choice := λ f h, ⟨f, begin convert (partial_sups f).monotone, exact (le_partial_sups f).antisymm h, end⟩, gc := λ f g, begin refine ⟨(le_partial_sups f).trans, λ h, _⟩, convert partial_sups_mono h, exact order_hom.ext _ _ g.monotone.partial_sups_eq.symm, end, le_l_u := λ f, le_partial_sups f, choice_eq := λ f h, order_hom.ext _ _ ((le_partial_sups f).antisymm h) } lemma partial_sups_eq_sup'_range (f : ℕ → α) (n : ℕ) : partial_sups f n = (finset.range (n + 1)).sup' ⟨n, finset.self_mem_range_succ n⟩ f := begin induction n with n ih, { simp }, { dsimp [partial_sups] at ih ⊢, simp_rw @finset.range_succ n.succ, rw [ih, finset.sup'_insert, sup_comm] } end end semilattice_sup lemma partial_sups_eq_sup_range [semilattice_sup α] [order_bot α] (f : ℕ → α) (n : ℕ) : partial_sups f n = (finset.range (n + 1)).sup f := begin induction n with n ih, { simp }, { dsimp [partial_sups] at ih ⊢, rw [finset.range_succ, finset.sup_insert, sup_comm, ih] } end /- Note this lemma requires a distributive lattice, so is not useful (or true) in situations such as submodules. -/ lemma partial_sups_disjoint_of_disjoint [distrib_lattice α] [order_bot α] (f : ℕ → α) (h : pairwise (disjoint on f)) {m n : ℕ} (hmn : m < n) : disjoint (partial_sups f m) (f n) := begin induction m with m ih, { exact h hmn.ne, }, { rw [partial_sups_succ, disjoint_sup_left], exact ⟨ih (nat.lt_of_succ_lt hmn), h hmn.ne⟩ } end section conditionally_complete_lattice variables [conditionally_complete_lattice α] lemma partial_sups_eq_csupr_Iic (f : ℕ → α) (n : ℕ) : partial_sups f n = ⨆ i : set.Iic n, f i := begin have : set.Iio (n + 1) = set.Iic n := set.ext (λ _, nat.lt_succ_iff), rw [partial_sups_eq_sup'_range, finset.sup'_eq_cSup_image, finset.coe_range, supr, set.range_comp, subtype.range_coe, this], end @[simp] lemma csupr_partial_sups_eq {f : ℕ → α} (h : bdd_above (set.range f)) : (⨆ n, partial_sups f n) = ⨆ n, f n := begin refine (csupr_le $ λ n, _).antisymm (csupr_mono _ $ le_partial_sups f), { rw partial_sups_eq_csupr_Iic, exact csupr_le (λ i, le_csupr h _), }, { rwa bdd_above_range_partial_sups }, end end conditionally_complete_lattice section complete_lattice variables [complete_lattice α] lemma partial_sups_eq_bsupr (f : ℕ → α) (n : ℕ) : partial_sups f n = ⨆ (i ≤ n), f i := by simpa only [supr_subtype] using partial_sups_eq_csupr_Iic f n @[simp] lemma supr_partial_sups_eq (f : ℕ → α) : (⨆ n, partial_sups f n) = ⨆ n, f n := csupr_partial_sups_eq $ order_top.bdd_above _ lemma supr_le_supr_of_partial_sups_le_partial_sups {f g : ℕ → α} (h : partial_sups f ≤ partial_sups g) : (⨆ n, f n) ≤ ⨆ n, g n := begin rw [←supr_partial_sups_eq f, ←supr_partial_sups_eq g], exact supr_mono h, end lemma supr_eq_supr_of_partial_sups_eq_partial_sups {f g : ℕ → α} (h : partial_sups f = partial_sups g) : (⨆ n, f n) = ⨆ n, g n := by simp_rw [←supr_partial_sups_eq f, ←supr_partial_sups_eq g, h] end complete_lattice
f66569475db53cf41cdefe5f078a5708ddb5654b
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/logic/examples/leftinv_of_inj.lean
df816efcda115398e0491c242ee99ddaf7315bd9
[ "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
1,216
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 Classical proof that if f is injective, then f has a left inverse (if domain is not empty). The proof uses the classical axioms: choice and excluded middle. The excluded middle is being used "behind the scenes" to allow us to write the if-then-else expression with (∃ a : A, f a = b). -/ open function classical noncomputable definition mk_left_inv {A B : Type} [h : nonempty A] (f : A → B) : B → A := λ b : B, if ex : (∃ a : A, f a = b) then some ex else inhabited.value (inhabited_of_nonempty h) theorem has_left_inverse_of_injective {A B : Type} {f : A → B} : nonempty A → injective f → has_left_inverse f := assume h : nonempty A, assume inj : ∀ a₁ a₂, f a₁ = f a₂ → a₁ = a₂, let finv : B → A := mk_left_inv f in have linv : left_inverse finv f, from λ a, have ex : ∃ a₁ : A, f a₁ = f a, from exists.intro a rfl, have h₁ : f (some ex) = f a, from !some_spec, begin esimp [mk_left_inv, comp, id], rewrite [dif_pos ex], exact (!inj h₁) end, exists.intro finv linv
00b74fcd0aa37de52a4c88dd6f99801a6d75e0b4
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/analysis/calculus/iterated_deriv.lean
1b2b8a9624ac4bb09f4ee1345eb1d63f20fb1e49
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
14,715
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.times_cont_diff /-! # One-dimensional iterated derivatives We define the `n`-th derivative of a function `f : 𝕜 → F` as a function `iterated_deriv n f : 𝕜 → F`, as well as a version on domains `iterated_deriv_within n f s : 𝕜 → F`, and prove their basic properties. ## Main definitions and results Let `𝕜` be a nondiscrete normed field, and `F` a normed vector space over `𝕜`. Let `f : 𝕜 → F`. * `iterated_deriv n f` is the `n`-th derivative of `f`, seen as a function from `𝕜` to `F`. It is defined as the `n`-th Fréchet derivative (which is a multilinear map) applied to the vector `(1, ..., 1)`, to take advantage of all the existing framework, but we show that it coincides with the naive iterative definition. * `iterated_deriv_eq_iterate` states that the `n`-th derivative of `f` is obtained by starting from `f` and differentiating it `n` times. * `iterated_deriv_within n f s` is the `n`-th derivative of `f` within the domain `s`. It only behaves well when `s` has the unique derivative property. * `iterated_deriv_within_eq_iterate` states that the `n`-th derivative of `f` in the domain `s` is obtained by starting from `f` and differentiating it `n` times within `s`. This only holds when `s` has the unique derivative property. ## Implementation details The results are deduced from the corresponding results for the more general (multilinear) iterated Fréchet derivative. For this, we write `iterated_deriv n f` as the composition of `iterated_fderiv 𝕜 n f` and a continuous linear equiv. As continuous linear equivs respect differentiability and commute with differentiation, this makes it possible to prove readily that the derivative of the `n`-th derivative is the `n+1`-th derivative in `iterated_deriv_within_succ`, by translating the corresponding result `iterated_fderiv_within_succ_apply_left` for the iterated Fréchet derivative. -/ noncomputable theory open_locale classical topological_space open filter asymptotics set variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- The `n`-th iterated derivative of a function from `𝕜` to `F`, as a function from `𝕜` to `F`. -/ def iterated_deriv (n : ℕ) (f : 𝕜 → F) (x : 𝕜) : F := (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) /-- The `n`-th iterated derivative of a function from `𝕜` to `F` within a set `s`, as a function from `𝕜` to `F`. -/ def iterated_deriv_within (n : ℕ) (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) : F := (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) variables {n : ℕ} {f : 𝕜 → F} {s : set 𝕜} {x : 𝕜} lemma iterated_deriv_within_univ : iterated_deriv_within n f univ = iterated_deriv n f := by { ext x, rw [iterated_deriv_within, iterated_deriv, iterated_fderiv_within_univ] } /-! ### Properties of the iterated derivative within a set -/ lemma iterated_deriv_within_eq_iterated_fderiv_within : iterated_deriv_within n f s x = (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_within_eq_equiv_comp : iterated_deriv_within n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv_within 𝕜 n f s) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_within_eq_equiv_comp : iterated_fderiv_within 𝕜 n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv_within n f s) := begin rw [iterated_deriv_within_eq_equiv_comp, ← function.comp.assoc, continuous_linear_equiv.self_comp_symm], refl end /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_within_apply_eq_iterated_deriv_within_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) m = finset.univ.prod m • iterated_deriv_within n f s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, ← continuous_multilinear_map.map_smul_univ], simp end @[simp] lemma iterated_deriv_within_zero : iterated_deriv_within 0 f s = f := by { ext x, simp [iterated_deriv_within] } @[simp] lemma iterated_deriv_within_one (hs : unique_diff_on 𝕜 s) {x : 𝕜} (hx : x ∈ s): iterated_deriv_within 1 f s x = deriv_within f s x := by { simp [iterated_deriv_within, iterated_fderiv_within_one_apply hs hx], refl } /-- If the first `n` derivatives within a set of a function are continuous, and its first `n-1` derivatives are differentiable, then the function is `C^n`. This is not an equivalence in general, but this is an equivalence when the set has unique derivatives, see `times_cont_diff_on_iff_continuous_on_differentiable_on_deriv`. -/ lemma times_cont_diff_on_of_continuous_on_differentiable_on_deriv {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_deriv_within m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_deriv_within m f s x) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_continuous_on_differentiable_on, { simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff] }, { simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff] } end /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_on_of_differentiable_on_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_differentiable_on, simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff, -coe_fn_coe_base], end /-- On a set with unique derivatives, a `C^n` function has derivatives up to `n` which are continuous. -/ lemma times_cont_diff_on.continuous_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_deriv_within m f s) s := begin simp [iterated_deriv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff, -coe_fn_coe_base], exact h.continuous_on_iterated_fderiv_within hmn hs end /-- On a set with unique derivatives, a `C^n` function has derivatives less than `n` which are differentiable. -/ lemma times_cont_diff_on.differentiable_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_deriv_within m f s) s := begin simp [iterated_deriv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff, -coe_fn_coe_base], exact h.differentiable_on_iterated_fderiv_within hmn hs end /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative on sets with unique derivatives. -/ lemma times_cont_diff_on_iff_continuous_on_differentiable_on_deriv {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous_on (iterated_deriv_within m f s) s) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) := by simp only [times_cont_diff_on_iff_continuous_on_differentiable_on hs, iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff, continuous_linear_equiv.comp_differentiable_on_iff] /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_within_succ {x : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : iterated_deriv_within (n + 1) f s x = deriv_within (iterated_deriv_within n f s) s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_fderiv_within _ hxs, deriv_within], change ((continuous_multilinear_map.mk_pi_field 𝕜 (fin n) ((fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1)) : (fin n → 𝕜 ) → F) (λ (i : fin n), 1) = (fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1, simp end /-- The `n`-th iterated derivative within a set with unique derivatives can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_within_eq_iterate {x : 𝕜} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within n f s x = nat.iterate (λ (g : 𝕜 → F), deriv_within g s) n f x := begin induction n with n IH generalizing x, { simp }, { rw [iterated_deriv_within_succ (hs x hx), nat.iterate_succ'], exact deriv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx) } end /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_within_succ' {x : 𝕜} (hxs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within (n + 1) f s x = (iterated_deriv_within n (deriv_within f s) s) x := by { rw [iterated_deriv_within_eq_iterate hxs hx, iterated_deriv_within_eq_iterate hxs hx], refl } /-! ### Properties of the iterated derivative on the whole space -/ lemma iterated_deriv_eq_iterated_fderiv : iterated_deriv n f x = (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_eq_equiv_comp : iterated_deriv n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv 𝕜 n f) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_eq_equiv_comp : iterated_fderiv 𝕜 n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv n f) := begin rw [iterated_deriv_eq_equiv_comp, ← function.comp.assoc, continuous_linear_equiv.self_comp_symm], refl end /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_apply_eq_iterated_deriv_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) m = finset.univ.prod m • iterated_deriv n f x := by { rw [iterated_deriv_eq_iterated_fderiv, ← continuous_multilinear_map.map_smul_univ], simp } @[simp] lemma iterated_deriv_zero : iterated_deriv 0 f = f := by { ext x, simp [iterated_deriv] } @[simp] lemma iterated_deriv_one : iterated_deriv 1 f = deriv f := by { ext x, simp [iterated_deriv], refl } /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative. -/ lemma times_cont_diff_iff_iterated_deriv {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous (iterated_deriv m f)) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable 𝕜 (iterated_deriv m f)) := by simp only [times_cont_diff_iff_continuous_differentiable, iterated_fderiv_eq_equiv_comp, continuous_linear_equiv.comp_continuous_iff, continuous_linear_equiv.comp_differentiable_iff] /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_of_differentiable_iterated_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_deriv m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_iterated_deriv.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ lemma times_cont_diff.continuous_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) ≤ n) : continuous (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).1 m hmn lemma times_cont_diff.differentiable_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) < n) : differentiable 𝕜 (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).2 m hmn /-- The `n+1`-th iterated derivative can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_succ : iterated_deriv (n + 1) f = deriv (iterated_deriv n f) := begin ext x, rw [← iterated_deriv_within_univ, ← iterated_deriv_within_univ, ← deriv_within_univ], exact iterated_deriv_within_succ unique_diff_within_at_univ, end /-- The `n`-th iterated derivative can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_eq_iterate : iterated_deriv n f = nat.iterate deriv n f := begin ext x, rw [← iterated_deriv_within_univ], convert iterated_deriv_within_eq_iterate unique_diff_on_univ (mem_univ x), simp [deriv_within_univ] end /-- The `n+1`-th iterated derivative can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_succ' : iterated_deriv (n + 1) f = iterated_deriv n (deriv f) := by { rw [iterated_deriv_eq_iterate, iterated_deriv_eq_iterate], refl }
8660543d8f062a52622928dc3bdc486c5701aae0
bb31430994044506fa42fd667e2d556327e18dfe
/src/field_theory/minpoly/default.lean
aa4d2da6465840d0e8fc5c7259c969f11454c977
[ "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
107
lean
import field_theory.minpoly.basic import field_theory.minpoly.field import field_theory.minpoly.gcd_monoid
1ad6c18b14d15158c6b3fc7a88734b03d3564151
3aad12fe82645d2d3173fbedc2e5c2ba945a4d75
/src/logic/nursery.lean
38b11b39f00cbffa72f4083671816f9d525d5172
[]
no_license
seanpm2001/LeanProver-Community_MathLIB-Nursery
4f88d539cb18d73a94af983092896b851e6640b5
0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec
refs/heads/master
1,688,730,786,645
1,572,070,026,000
1,572,070,026,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
143
lean
lemma eq_mp_heq : ∀ {α β : Sort*} {a : α} {a' : β} (h₂ : a == a'), (eq.mp (type_eq_of_heq h₂) a) = a' | α ._ a a' heq.rfl := rfl
3a790a4d6f62c8dc557d8620dd7a2691b89084d5
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/adjunction/basic.lean
0866be54868db8dfb8457646561d7a67b05b7246
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
17,900
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, Bhavik Mehta -/ import category_theory.equivalence import data.equiv.basic namespace category_theory open category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation local attribute [elab_simple] whisker_left whisker_right variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- `F ⊣ G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. To construct an `adjunction` between two functors, it's often easier to instead use the constructors `mk_of_hom_equiv` or `mk_of_unit_counit`. To construct a left adjoint, there are also constructors `left_adjoint_of_equiv` and `adjunction_of_equiv_left` (as well as their duals) which can be simpler in practice. Uniqueness of adjoints is shown in `category_theory.adjunction.opposites`. See https://stacks.math.columbia.edu/tag/0037. -/ structure adjunction (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously) (hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously) infix ` ⊣ `:15 := adjunction /-- A class giving a chosen right adjoint to the functor `left`. -/ class is_left_adjoint (left : C ⥤ D) := (right : D ⥤ C) (adj : left ⊣ right) /-- A class giving a chosen left adjoint to the functor `right`. -/ class is_right_adjoint (right : D ⥤ C) := (left : C ⥤ D) (adj : left ⊣ right) /-- Extract the left adjoint from the instance giving the chosen adjoint. -/ def left_adjoint (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D := is_right_adjoint.left R /-- Extract the right adjoint from the instance giving the chosen adjoint. -/ def right_adjoint (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C := is_left_adjoint.right L /-- The adjunction associated to a functor known to be a left adjoint. -/ def adjunction.of_left_adjoint (left : C ⥤ D) [is_left_adjoint left] : adjunction left (right_adjoint left) := is_left_adjoint.adj /-- The adjunction associated to a functor known to be a right adjoint. -/ def adjunction.of_right_adjoint (right : C ⥤ D) [is_right_adjoint right] : adjunction (left_adjoint right) right := is_right_adjoint.adj namespace adjunction restate_axiom hom_equiv_unit' restate_axiom hom_equiv_counit' attribute [simp, priority 10] hom_equiv_unit hom_equiv_counit section variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D} @[simp, priority 10] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) : (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g := by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm] @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit] @[simp, priority 10] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g := by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit] @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit] @[simp] lemma left_triangle : (whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit], simp end @[simp] lemma right_triangle : (whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ := begin ext, dsimp, erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit], simp end @[simp, reassoc] lemma left_triangle_components : F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) := congr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle @[simp, reassoc] lemma right_triangle_components {Y : D} : adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) := congr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle @[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) : F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f := adj.counit.naturality f @[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) : (adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y := (adj.unit.naturality f).symm lemma hom_equiv_apply_eq {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : adj.hom_equiv A B f = g ↔ f = (adj.hom_equiv A B).symm g := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ lemma eq_hom_equiv_apply {A : C} {B : D} (f : F.obj A ⟶ B) (g : A ⟶ G.obj B) : g = adj.hom_equiv A B f ↔ (adj.hom_equiv A B).symm g = f := ⟨λ h, by {cases h, simp}, λ h, by {cases h, simp}⟩ end end adjunction namespace adjunction /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_hom_equiv`. This structure won't typically be used anywhere else. -/ @[nolint has_inhabited_instance] structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y), (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously) (hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'), (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously) namespace core_hom_equiv restate_axiom hom_equiv_naturality_left_symm' restate_axiom hom_equiv_naturality_right' attribute [simp, priority 10] hom_equiv_naturality_left_symm hom_equiv_naturality_right variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D} @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp end core_hom_equiv /-- This is an auxiliary data structure useful for constructing adjunctions. See `adjunction.mk_of_hom_equiv`. This structure won't typically be used anywhere else. -/ @[nolint has_inhabited_instance] structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) := (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (left_triangle' : whisker_right unit F ≫ (functor.associator F G F).hom ≫ whisker_left F counit = nat_trans.id (𝟭 C ⋙ F) . obviously) (right_triangle' : whisker_left G unit ≫ (functor.associator G F G).inv ≫ whisker_right counit G = nat_trans.id (G ⋙ 𝟭 C) . obviously) namespace core_unit_counit restate_axiom left_triangle' restate_axiom right_triangle' attribute [simp] left_triangle right_triangle end core_unit_counit variables {F : C ⥤ D} {G : D ⥤ C} /-- Construct an adjunction between `F` and `G` out of a natural bijection between each `F.obj X ⟶ Y` and `X ⟶ G.obj Y`. -/ def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G := { unit := { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right], dsimp, simp -- See note [dsimp, simp]. end }, counit := { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm], dsimp, simp end }, hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp, hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp, .. adj } /-- Construct an adjunction between functors `F` and `G` given a unit and counit for the adjunction satisfying the triangle identities. -/ def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G := { hom_equiv := λ X Y, { to_fun := λ f, adj.unit.app X ≫ G.map f, inv_fun := λ g, F.map g ≫ adj.counit.app Y, left_inv := λ f, begin change F.map (_ ≫ _) ≫ _ = _, rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc], convert id_comp f, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle, dsimp at t, simp only [id_comp] at t, exact t, end, right_inv := λ g, begin change _ ≫ G.map (_ ≫ _) = _, rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc], convert comp_id g, have t := congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle, dsimp at t, simp only [id_comp] at t, exact t, end }, .. adj } /-- The adjunction between the identity functor on a category and itself. -/ def id : 𝟭 C ⊣ 𝟭 C := { hom_equiv := λ X Y, equiv.refl _, unit := 𝟙 _, counit := 𝟙 _ } -- Satisfy the inhabited linter. instance : inhabited (adjunction (𝟭 C) (𝟭 C)) := ⟨id⟩ /-- If F and G are naturally isomorphic functors, establish an equivalence of hom-sets. -/ def equiv_homset_left_of_nat_iso {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} : (F.obj X ⟶ Y) ≃ (F'.obj X ⟶ Y) := { to_fun := λ f, iso.inv.app _ ≫ f, inv_fun := λ g, iso.hom.app _ ≫ g, left_inv := λ f, by simp, right_inv := λ g, by simp } @[simp] lemma equiv_homset_left_of_nat_iso_apply {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} (f : F.obj X ⟶ Y) : (equiv_homset_left_of_nat_iso iso) f = iso.inv.app _ ≫ f := rfl @[simp] lemma equiv_homset_left_of_nat_iso_symm_apply {F F' : C ⥤ D} (iso : F ≅ F') {X : C} {Y : D} (g : F'.obj X ⟶ Y) : (equiv_homset_left_of_nat_iso iso).symm g = iso.hom.app _ ≫ g := rfl /-- If G and H are naturally isomorphic functors, establish an equivalence of hom-sets. -/ def equiv_homset_right_of_nat_iso {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} : (X ⟶ G.obj Y) ≃ (X ⟶ G'.obj Y) := { to_fun := λ f, f ≫ iso.hom.app _, inv_fun := λ g, g ≫ iso.inv.app _, left_inv := λ f, by simp, right_inv := λ g, by simp } @[simp] lemma equiv_homset_right_of_nat_iso_apply {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} (f : X ⟶ G.obj Y) : (equiv_homset_right_of_nat_iso iso) f = f ≫ iso.hom.app _ := rfl @[simp] lemma equiv_homset_right_of_nat_iso_symm_apply {G G' : D ⥤ C} (iso : G ≅ G') {X : C} {Y : D} (g : X ⟶ G'.obj Y) : (equiv_homset_right_of_nat_iso iso).symm g = g ≫ iso.inv.app _ := rfl /-- Transport an adjunction along an natural isomorphism on the left. -/ def of_nat_iso_left {F G : C ⥤ D} {H : D ⥤ C} (adj : F ⊣ H) (iso : F ≅ G) : G ⊣ H := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (equiv_homset_left_of_nat_iso iso.symm).trans (adj.hom_equiv X Y) } /-- Transport an adjunction along an natural isomorphism on the right. -/ def of_nat_iso_right {F : C ⥤ D} {G H : D ⥤ C} (adj : F ⊣ G) (iso : G ≅ H) : F ⊣ H := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, (adj.hom_equiv X Y).trans (equiv_homset_right_of_nat_iso iso) } /-- Transport being a right adjoint along a natural isomorphism. -/ def right_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_right_adjoint F] : is_right_adjoint G := { left := r.left, adj := of_nat_iso_right r.adj h } /-- Transport being a left adjoint along a natural isomorphism. -/ def left_adjoint_of_nat_iso {F G : C ⥤ D} (h : F ≅ G) [r : is_left_adjoint F] : is_left_adjoint G := { right := r.right, adj := of_nat_iso_left r.adj h } section variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D) /-- Composition of adjunctions. See https://stacks.math.columbia.edu/tag/0DV0. -/ def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G := { hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _), unit := adj₁.unit ≫ (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv, counit := (functor.associator _ _ _).hom ≫ (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit } /-- If `F` and `G` are left adjoints then `F ⋙ G` is a left adjoint too. -/ instance left_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] (F : C ⥤ D) (G : D ⥤ E) [Fl : is_left_adjoint F] [Gl : is_left_adjoint G] : is_left_adjoint (F ⋙ G) := { right := Gl.right ⋙ Fl.right, adj := comp _ _ Fl.adj Gl.adj } /-- If `F` and `G` are right adjoints then `F ⋙ G` is a right adjoint too. -/ instance right_adjoint_of_comp {E : Type u₃} [ℰ : category.{v₃} E] {F : C ⥤ D} {G : D ⥤ E} [Fr : is_right_adjoint F] [Gr : is_right_adjoint G] : is_right_adjoint (F ⋙ G) := { left := Gr.left ⋙ Fr.left, adj := comp _ _ Gr.adj Fr.adj } end section construct_left -- Construction of a left adjoint. In order to construct a left -- adjoint to a functor G : D → C, it suffices to give the object part -- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃ -- Hom(X, GY) natural in Y. The action of F on morphisms can be -- constructed from this data. variables {F_obj : C → D} {G} variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) variables (he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g) include he private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g := by intros; rw [equiv.symm_apply_eq, he]; simp /-- Construct a left adjoint functor to `G`, given the functor's value on objects `F_obj` and a bijection `e` between `F_obj X ⟶ Y` and `X ⟶ G.obj Y` satisfying a naturality law `he : ∀ X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g`. Dual to `right_adjoint_of_equiv`. -/ def left_adjoint_of_equiv : C ⥤ D := { obj := F_obj, map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)), map_comp' := λ X X' X'' f f', begin rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply], conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] }, simp end } /-- Show that the functor given by `left_adjoint_of_equiv` is indeed left adjoint to `G`. Dual to `adjunction_of_equiv_right`. -/ def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := begin intros, erw [← he' e he, ← equiv.apply_eq_iff_eq], simp [(he _ _ _ _ _).symm] end } end construct_left section construct_right -- Construction of a right adjoint, analogous to the above. variables {F} {G_obj : D → C} variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y)) variables (he : ∀ X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g) include he private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) := by intros; rw [equiv.eq_symm_apply, he]; simp /-- Construct a right adjoint functor to `F`, given the functor's value on objects `G_obj` and a bijection `e` between `F.obj X ⟶ Y` and `X ⟶ G_obj Y` satisfying a naturality law `he : ∀ X Y Y' g h, e X' Y (F.map f ≫ g) = f ≫ e X Y g`. Dual to `left_adjoint_of_equiv`. -/ def right_adjoint_of_equiv : D ⥤ C := { obj := G_obj, map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g), map_comp' := λ Y Y' Y'' g g', begin rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply], conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] }, simp end } /-- Show that the functor given by `right_adjoint_of_equiv` is indeed right adjoint to `F`. Dual to `adjunction_of_equiv_left`. -/ def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp, hom_equiv_naturality_right' := begin intros X Y Y' g h, erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply] end } end construct_right end adjunction open adjunction namespace equivalence /-- The adjunction given by an equivalence of categories. (To obtain the opposite adjunction, simply use `e.symm.to_adjunction`. -/ def to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse := mk_of_unit_counit ⟨e.unit, e.counit, by { ext, dsimp, simp only [id_comp], exact e.functor_unit_comp _, }, by { ext, dsimp, simp only [id_comp], exact e.unit_inverse_comp _, }⟩ end equivalence namespace functor /-- An equivalence `E` is left adjoint to its inverse. -/ def adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv := (E.as_equivalence).to_adjunction /-- If `F` is an equivalence, it's a left adjoint. -/ @[priority 10] instance left_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_left_adjoint F := { right := _, adj := functor.adjunction F } @[simp] lemma right_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : right_adjoint F = inv F := rfl /-- If `F` is an equivalence, it's a right adjoint. -/ @[priority 10] instance right_adjoint_of_equivalence {F : C ⥤ D} [is_equivalence F] : is_right_adjoint F := { left := _, adj := functor.adjunction F.inv } @[simp] lemma left_adjoint_of_is_equivalence {F : C ⥤ D} [is_equivalence F] : left_adjoint F = inv F := rfl end functor end category_theory
13b26fcbebcf89237f193b08277cf93723c1883e
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/monic.lean
360d21a747eba47bc7da097b7fca85491cb90a65
[ "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,525
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.reverse import algebra.associated import algebra.regular.smul /-! # Theory of monic polynomials We give several tools for proving that polynomials are monic, e.g. `monic.mul`, `monic.map`, `monic.pow`. -/ noncomputable theory open finset open_locale big_operators classical polynomial namespace polynomial universes u v y variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y} section semiring variables [semiring R] {p q r : R[X]} lemma monic.as_sum (hp : p.monic) : p = X^(p.nat_degree) + (∑ i in range p.nat_degree, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum_range_C_mul_X_pow, sum_range_succ_comm] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 := begin rintro rfl, rw [monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma monic.map [semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := begin nontriviality, have : f (leading_coeff p) ≠ 0, { rw [show _ = _, from hp, f.map_one], exact one_ne_zero, }, rw [monic, leading_coeff, coeff_map], suffices : p.coeff (map f p).nat_degree = 1, { simp [this], }, rwa nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), end lemma monic_C_mul_of_mul_leading_coeff_eq_one {b : R} (hp : b * p.leading_coeff = 1) : monic (C b * p) := by { nontriviality, rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp] } lemma monic_mul_C_of_leading_coeff_mul_eq_one {b : R} (hp : p.leading_coeff * b = 1) : monic (p * C b) := by { nontriviality, rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp] } theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, eq_of_zero_eq_one (H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : R[X]) ▸ monic_X_pow_add degree_C_le lemma monic.mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic.pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := by { rw pow_succ, exact hp.mul (monic.pow n) } lemma monic.add_of_left (hp : monic p) (hpq : degree q < degree p) : monic (p + q) := by rwa [monic, add_comm, leading_coeff_add_of_degree_lt hpq] lemma monic.add_of_right (hq : monic q) (hpq : degree p < degree q) : monic (p + q) := by rwa [monic, leading_coeff_add_of_degree_lt hpq] lemma monic.of_mul_monic_left (hp : p.monic) (hpq : (p * q).monic) : q.monic := begin contrapose! hpq, rw monic.def at hpq ⊢, rwa leading_coeff_monic_mul hp, end lemma monic.of_mul_monic_right (hq : q.monic) (hpq : (p * q).monic) : p.monic := begin contrapose! hpq, rw monic.def at hpq ⊢, rwa leading_coeff_mul_monic hq, end namespace monic @[simp] lemma nat_degree_eq_zero_iff_eq_one {p : R[X]} (hp : p.monic) : p.nat_degree = 0 ↔ p = 1 := begin split; intro h, swap, { rw h, exact nat_degree_one }, have : p = C (p.coeff 0), { rw ← polynomial.degree_le_zero_iff, rwa polynomial.nat_degree_eq_zero_iff_degree_le_zero at h }, rw this, convert C_1, rw ← h, apply hp, end @[simp] lemma degree_le_zero_iff_eq_one {p : R[X]} (hp : p.monic) : p.degree ≤ 0 ↔ p = 1 := by rw [←hp.nat_degree_eq_zero_iff_eq_one, nat_degree_eq_zero_iff_degree_le_zero] lemma nat_degree_mul {p q : R[X]} (hp : p.monic) (hq : q.monic) : (p * q).nat_degree = p.nat_degree + q.nat_degree := begin nontriviality R, apply nat_degree_mul', simp [hp.leading_coeff, hq.leading_coeff] end lemma degree_mul_comm {p : R[X]} (hp : p.monic) (q : R[X]) : (p * q).degree = (q * p).degree := begin by_cases h : q = 0, { simp [h] }, rw [degree_mul', hp.degree_mul], { exact add_comm _ _ }, { rwa [hp.leading_coeff, one_mul, leading_coeff_ne_zero] } end lemma nat_degree_mul' {p q : R[X]} (hp : p.monic) (hq : q ≠ 0) : (p * q).nat_degree = p.nat_degree + q.nat_degree := begin rw [nat_degree_mul', add_comm], simpa [hp.leading_coeff, leading_coeff_ne_zero] end lemma nat_degree_mul_comm {p : R[X]} (hp : p.monic) (q : R[X]) : (p * q).nat_degree = (q * p).nat_degree := begin by_cases h : q = 0, { simp [h] }, rw [hp.nat_degree_mul' h, polynomial.nat_degree_mul', add_comm], simpa [hp.leading_coeff, leading_coeff_ne_zero] end lemma next_coeff_mul {p q : R[X]} (hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q := begin nontriviality, simp only [← coeff_one_reverse], rw reverse_mul; simp [coeff_mul, nat.antidiagonal, hp.leading_coeff, hq.leading_coeff, add_comm] end lemma eq_one_of_map_eq_one {S : Type*} [semiring S] [nontrivial S] (f : R →+* S) (hp : p.monic) (map_eq : p.map f = 1) : p = 1 := begin nontriviality R, have hdeg : p.degree = 0, { rw [← degree_map_eq_of_leading_coeff_ne_zero f _, map_eq, degree_one], { rw [hp.leading_coeff, f.map_one], exact one_ne_zero } }, have hndeg : p.nat_degree = 0 := with_bot.coe_eq_coe.mp ((degree_eq_nat_degree hp.ne_zero).symm.trans hdeg), convert eq_C_of_degree_eq_zero hdeg, rw [← hndeg, ← polynomial.leading_coeff, hp.leading_coeff, C.map_one] end lemma nat_degree_pow (hp : p.monic) (n : ℕ) : (p ^ n).nat_degree = n * p.nat_degree := begin induction n with n hn, { simp }, { rw [pow_succ, hp.nat_degree_mul (hp.pow n), hn], ring } end end monic @[simp] lemma nat_degree_pow_X_add_C [nontrivial R] (n : ℕ) (r : R) : ((X + C r) ^ n).nat_degree = n := by rw [(monic_X_add_C r).nat_degree_pow, nat_degree_X_add_C, mul_one] end semiring section comm_semiring variables [comm_semiring R] {p : R[X]} lemma monic_multiset_prod_of_monic (t : multiset ι) (f : ι → R[X]) (ht : ∀ i ∈ t, monic (f i)) : monic (t.map f).prod := begin revert ht, refine t.induction_on _ _, { simp }, intros a t ih ht, rw [multiset.map_cons, multiset.prod_cons], exact (ht _ (multiset.mem_cons_self _ _)).mul (ih (λ _ hi, ht _ (multiset.mem_cons_of_mem hi))) end lemma monic_prod_of_monic (s : finset ι) (f : ι → R[X]) (hs : ∀ i ∈ s, monic (f i)) : monic (∏ i in s, f i) := monic_multiset_prod_of_monic s.1 f hs lemma is_unit_C {x : R} : is_unit (C x) ↔ is_unit x := begin rw [is_unit_iff_dvd_one, is_unit_iff_dvd_one], split, { rintros ⟨g, hg⟩, replace hg := congr_arg (eval 0) hg, rw [eval_one, eval_mul, eval_C] at hg, exact ⟨g.eval 0, hg⟩ }, { rintros ⟨y, hy⟩, exact ⟨C y, by rw [← C_mul, ← hy, C_1]⟩ } end lemma eq_one_of_is_unit_of_monic (hm : monic p) (hpu : is_unit p) : p = 1 := have degree p ≤ 0, from calc degree p ≤ degree (1 : R[X]) : let ⟨u, hu⟩ := is_unit_iff_dvd_one.1 hpu in if hu0 : u = 0 then begin rw [hu0, mul_zero] at hu, rw [← mul_one p, hu, mul_zero], simp end else have p.leading_coeff * u.leading_coeff ≠ 0, by rw [hm.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero]; exact hu0, by rw [hu, degree_mul' this]; exact le_add_of_nonneg_right (degree_nonneg_iff_ne_zero.2 hu0) ... ≤ 0 : degree_one_le, by rw [eq_C_of_degree_le_zero this, ← nat_degree_eq_zero_iff_degree_le_zero.2 this, ← leading_coeff, hm.leading_coeff, C_1] lemma monic.next_coeff_multiset_prod (t : multiset ι) (f : ι → R[X]) (h : ∀ i ∈ t, monic (f i)) : next_coeff (t.map f).prod = (t.map (λ i, next_coeff (f i))).sum := begin revert h, refine multiset.induction_on t _ (λ a t ih ht, _), { simp only [multiset.not_mem_zero, forall_prop_of_true, forall_prop_of_false, multiset.map_zero, multiset.prod_zero, multiset.sum_zero, not_false_iff, forall_true_iff], rw ← C_1, rw next_coeff_C_eq_zero }, { rw [multiset.map_cons, multiset.prod_cons, multiset.map_cons, multiset.sum_cons, monic.next_coeff_mul, ih], exacts [λ i hi, ht i (multiset.mem_cons_of_mem hi), ht a (multiset.mem_cons_self _ _), monic_multiset_prod_of_monic _ _ (λ b bs, ht _ (multiset.mem_cons_of_mem bs))] } end lemma monic.next_coeff_prod (s : finset ι) (f : ι → R[X]) (h : ∀ i ∈ s, monic (f i)) : next_coeff (∏ i in s, f i) = ∑ i in s, next_coeff (f i) := monic.next_coeff_multiset_prod s.1 f h end comm_semiring section semiring variables [semiring R] @[simp] lemma monic.nat_degree_map [semiring S] [nontrivial S] {P : polynomial R} (hmo : P.monic) (f : R →+* S) : (P.map f).nat_degree = P.nat_degree := begin refine le_antisymm (nat_degree_map_le _ _) (le_nat_degree_of_ne_zero _), rw [coeff_map, monic.coeff_nat_degree hmo, ring_hom.map_one], exact one_ne_zero end @[simp] lemma monic.degree_map [semiring S] [nontrivial S] {P : polynomial R} (hmo : P.monic) (f : R →+* S) : (P.map f).degree = P.degree := begin by_cases hP : P = 0, { simp [hP] }, { refine le_antisymm (degree_map_le _ _) _, rw [degree_eq_nat_degree hP], refine le_degree_of_ne_zero _, rw [coeff_map, monic.coeff_nat_degree hmo, ring_hom.map_one], exact one_ne_zero } end section injective open function variables [semiring S] {f : R →+* S} (hf : injective f) include hf lemma degree_map_eq_of_injective (p : R[X]) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← f.map_zero]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma nat_degree_map_eq_of_injective (p : R[X]) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_injective hf p) lemma leading_coeff_map' (p : R[X]) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_eq_of_injective hf p], end lemma next_coeff_map (p : R[X]) : (p.map f).next_coeff = f p.next_coeff := begin unfold next_coeff, rw nat_degree_map_eq_of_injective hf, split_ifs; simp end lemma leading_coeff_of_injective (p : R[X]) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map_eq_of_injective hf p] end lemma monic_of_injective {p : R[X]} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, f.map_one] end end injective end semiring section ring variables [ring R] {p : R[X]} theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := by simpa [sub_eq_add_neg] using monic_X_pow_add (show degree (-p) ≤ n, by rwa ←degree_neg p at H) /-- `X ^ n - a` is monic. -/ lemma monic_X_pow_sub_C {R : Type u} [ring R] (a : R) {n : ℕ} (h : n ≠ 0) : (X ^ n - C a).monic := begin obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero h, convert monic_X_pow_sub _, exact le_trans degree_C_le nat.with_bot.coe_nonneg, end lemma not_is_unit_X_pow_sub_one (R : Type*) [comm_ring R] [nontrivial R] (n : ℕ) : ¬ is_unit (X ^ n - 1 : R[X]) := begin intro h, rcases eq_or_ne n 0 with rfl | hn, { simpa using h }, apply hn, rwa [← @nat_degree_X_pow_sub_C _ _ _ n (1 : R), eq_one_of_is_unit_of_monic (monic_X_pow_sub_C (1 : R) hn), nat_degree_one] end lemma monic.sub_of_left {p q : R[X]} (hp : monic p) (hpq : degree q < degree p) : monic (p - q) := by { rw sub_eq_add_neg, apply hp.add_of_left, rwa degree_neg } lemma monic.sub_of_right {p q : R[X]} (hq : q.leading_coeff = -1) (hpq : degree p < degree q) : monic (p - q) := have (-q).coeff (-q).nat_degree = 1 := by rw [nat_degree_neg, coeff_neg, show q.coeff q.nat_degree = -1, from hq, neg_neg], by { rw sub_eq_add_neg, apply monic.add_of_right this, rwa degree_neg } end ring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma not_monic_zero : ¬monic (0 : R[X]) := by simpa only [monic, leading_coeff_zero] using (zero_ne_one : (0 : R) ≠ 1) end nonzero_semiring section not_zero_divisor -- TODO: using gh-8537, rephrase lemmas that involve commutation around `*` using the op-ring variables [semiring R] {p : R[X]} lemma monic.mul_left_ne_zero (hp : monic p) {q : R[X]} (hq : q ≠ 0) : q * p ≠ 0 := begin by_cases h : p = 1, { simpa [h] }, rw [ne.def, ←degree_eq_bot, hp.degree_mul, with_bot.add_eq_bot, not_or_distrib, degree_eq_bot], refine ⟨hq, _⟩, rw [←hp.degree_le_zero_iff_eq_one, not_le] at h, refine (lt_trans _ h).ne', simp end lemma monic.mul_right_ne_zero (hp : monic p) {q : R[X]} (hq : q ≠ 0) : p * q ≠ 0 := begin by_cases h : p = 1, { simpa [h] }, rw [ne.def, ←degree_eq_bot, hp.degree_mul_comm, hp.degree_mul, with_bot.add_eq_bot, not_or_distrib, degree_eq_bot], refine ⟨hq, _⟩, rw [←hp.degree_le_zero_iff_eq_one, not_le] at h, refine (lt_trans _ h).ne', simp end lemma monic.mul_nat_degree_lt_iff (h : monic p) {q : R[X]} : (p * q).nat_degree < p.nat_degree ↔ p ≠ 1 ∧ q = 0 := begin by_cases hq : q = 0, { suffices : 0 < p.nat_degree ↔ p.nat_degree ≠ 0, { simpa [hq, ←h.nat_degree_eq_zero_iff_eq_one] }, exact ⟨λ h, h.ne', λ h, lt_of_le_of_ne (nat.zero_le _) h.symm ⟩ }, { simp [h.nat_degree_mul', hq] } end lemma monic.mul_right_eq_zero_iff (h : monic p) {q : R[X]} : p * q = 0 ↔ q = 0 := begin by_cases hq : q = 0; simp [h.mul_right_ne_zero, hq] end lemma monic.mul_left_eq_zero_iff (h : monic p) {q : R[X]} : q * p = 0 ↔ q = 0 := begin by_cases hq : q = 0; simp [h.mul_left_ne_zero, hq] end lemma monic.is_regular {R : Type*} [ring R] {p : R[X]} (hp : monic p) : is_regular p := begin split, { intros q r h, rw [←sub_eq_zero, ←hp.mul_right_eq_zero_iff, mul_sub, h, sub_self] }, { intros q r h, simp only at h, rw [←sub_eq_zero, ←hp.mul_left_eq_zero_iff, sub_mul, h, sub_self] } end lemma degree_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R] {k : S} (p : R[X]) (h : is_smul_regular R k) : (k • p).degree = p.degree := begin refine le_antisymm _ _, { rw degree_le_iff_coeff_zero, intros m hm, rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl] }, { rw degree_le_iff_coeff_zero, intros m hm, rw degree_lt_iff_coeff_zero at hm, refine h _, simpa using hm m le_rfl }, end lemma nat_degree_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R] {k : S} (p : R[X]) (h : is_smul_regular R k) : (k • p).nat_degree = p.nat_degree := begin by_cases hp : p = 0, { simp [hp] }, rw [←with_bot.coe_eq_coe, ←degree_eq_nat_degree hp, ←degree_eq_nat_degree, degree_smul_of_smul_regular p h], contrapose! hp, rw ←smul_zero k at hp, exact h.polynomial hp end lemma leading_coeff_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R] {k : S} (p : R[X]) (h : is_smul_regular R k) : (k • p).leading_coeff = k • p.leading_coeff := by rw [leading_coeff, leading_coeff, coeff_smul, nat_degree_smul_of_smul_regular p h] lemma monic_of_is_unit_leading_coeff_inv_smul (h : is_unit p.leading_coeff) : monic (h.unit⁻¹ • p) := begin rw [monic.def, leading_coeff_smul_of_smul_regular _ (is_smul_regular_of_group _), units.smul_def], obtain ⟨k, hk⟩ := h, simp only [←hk, smul_eq_mul, ←units.coe_mul, units.coe_eq_one, inv_mul_eq_iff_eq_mul], simp [units.ext_iff, is_unit.unit_spec] end lemma is_unit_leading_coeff_mul_right_eq_zero_iff (h : is_unit p.leading_coeff) {q : R[X]} : p * q = 0 ↔ q = 0 := begin split, { intro hp, rw ←smul_eq_zero_iff_eq (h.unit)⁻¹ at hp, have : (h.unit)⁻¹ • (p * q) = ((h.unit)⁻¹ • p) * q, { ext, simp only [units.smul_def, coeff_smul, coeff_mul, smul_eq_mul, mul_sum], refine sum_congr rfl (λ x hx, _), rw ←mul_assoc }, rwa [this, monic.mul_right_eq_zero_iff] at hp, exact monic_of_is_unit_leading_coeff_inv_smul _ }, { rintro rfl, simp } end lemma is_unit_leading_coeff_mul_left_eq_zero_iff (h : is_unit p.leading_coeff) {q : R[X]} : q * p = 0 ↔ q = 0 := begin split, { intro hp, replace hp := congr_arg (* C ↑(h.unit)⁻¹) hp, simp only [zero_mul] at hp, rwa [mul_assoc, monic.mul_left_eq_zero_iff] at hp, refine monic_mul_C_of_leading_coeff_mul_eq_one _, simp [units.mul_inv_eq_iff_eq_mul, is_unit.unit_spec] }, { rintro rfl, rw zero_mul } end end not_zero_divisor end polynomial
426a0313b358ee4960145ae2b7a72db1aa1c3c1d
5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65
/src/exercises/src_28_powerset.lean
ab99d333df418e42bc322888c3a8b3111f62ffd9
[]
no_license
gihanmarasingha/mth1001_tutorial
8e0817feeb96e7c1bb3bac49b63e3c9a3a329061
bb277eebd5013766e1418365b91416b406275130
refs/heads/master
1,675,008,746,310
1,607,993,443,000
1,607,993,443,000
321,511,270
3
0
null
null
null
null
UTF-8
Lean
false
false
2,809
lean
import data.set open set namespace mth1001 variable A : Type* variables (S T : set A) #check powerset #check mem_set_of_eq #check mem_union_eq #check subset_def #check subset_union_left /- Type `𝒫` as `\power` -/ example : (𝒫 S) ∪ (𝒫 T) ⊆ 𝒫 (S ∪ T) := begin -- Using the definition of subset, we must show, `∀ x, x ∈ 𝒫 S ∪ 𝒫 T → x ∈ 𝒫 (S ∪ T)`. -- rw subset_def, intro x, -- Assume `x : U`. intro h, -- Assume `h : x ∈ 𝒫 S ∪ 𝒫 T`. rw mem_union_eq at h, -- By definition, `h : x ∈ 𝒫 S ∨ 𝒫 T`. /- By or elim., it suffices to prove the goal under the assumptions 1. `h₂ : x ∈ 𝒫 S`, 2. `h₃ : x ∈ 𝒫 T`. -/ -- By repeated definion of 𝒫 and ∈, `h : x ⊆ S ∨ x ⊆ T`. The goal is `x ⊆ S ∪ T`. repeat { rw [powerset, mem_set_of_eq] at *, }, cases h with h₂ h₃, { have h₄ : S ⊆ S ∪ T, from set.subset_union_left S T, transitivity, { exact h₂,}, { exact h₄, }, }, { transitivity, { exact h₃, }, { exact set.subset_union_right S T, }, }, end /- The converse of the above result is *not* true. Here's a proof by counterexample. -/ example : ¬(∀ A : Type*, ∀ S T : set A, 𝒫 (S ∪ T) ⊆ (𝒫 S) ∪ (𝒫 T)) := begin push_neg, -- Negating, the goal is `∃ A, ∃ S T : set A, ¬(𝒫 (S ∪ T) ⊆ 𝒫 S ∪ 𝒫 T)`. use [ℤ, {1}, {2}], -- We'll take `A` as `ℤ`, `S` as `{1}` and `T` as `{2}`. repeat { rw powerset }, -- Apply repeatedly the definitions of powerset repeat { rw subset_def }, -- and subset, norm_num, -- negating and noting `{1} ∪ {2} = {2, 1}`, the goal is to prove -- `∃ (x : set ℤ), x ⊆ {2, 1} ∧ ¬(x ⊆ {1} ∨ x ⊆ {2})` use {1, 2}, -- We take `{1, 2}` for `x`. split, /- It suffices to prove the two goals: 1. `{1, 2} ⊆ {2, 1}` and 2. `({1, 2} ⊆ {1} ∨ {1, 2} ⊆ {2})` -/ { rw subset_def, -- We solve the first subgoal by definition of subset finish, }, -- and rules of logic. { repeat { rw subset_def }, -- By repeated application of the definition of subset push_neg, -- and negating, we must show -- `(∃ (x : ℤ), x ∈ {1, 2} ∧ x ∉ {1}) ∧ ∃ (x : ℤ), x ∈ {1, 2} ∧ x ∉ {2}`. split, /- By and introduction, this splits into two subgoals: 2.1. `∃ (x : ℤ), x ∈ {1, 2} ∧ x ∉ {1}`. 2.2. `∃ (x : ℤ), x ∈ {1, 2} ∧ x ∉ {2}`. -/ { use 2, finish, }, -- We close the goal by showing `2 ∈ {1, 2} ∧ 2 ∉ {1}`. { use 1, finish, }, }, -- We close the goal by showing `1 ∈ {1, 2} ∧ 1 ∉ {2}`. end -- Exercise 141: example : (𝒫 S) ∩ (𝒫 T) ⊆ 𝒫 (S ∩ T) := begin sorry end -- Exercise 142: example : 𝒫 (S ∩ T) ⊆ (𝒫 S) ∩ (𝒫 T) := begin sorry end end mth1001
89d56376460d562bd061438472b7ee53e064ba1f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/sheaves/stalks.lean
90f4f1ce8cb0cd558136457e275de7e21d1d0597
[ "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
24,503
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.types import category_theory.limits.preserves.filtered import category_theory.limits.final import topology.sober import tactic.elementwise import algebra.category.Ring /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the composition of the inclusion of categories `(nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ` and the functor `F : (opens X)ᵒᵖ ⥤ C`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...) is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves. For example, in `germ_exist` we prove that in such a category, every element of the stalk is the germ of a section. Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as is the case for most algebraic structures), we have access to the unique gluing API and can prove further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are isomorphisms. See also the definition of "algebraic structures" in the stacks project: https://stacks.math.columbia.edu/tag/007L -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) @[simp, elementwise] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op /-- A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its composition with the `germ` morphisms. -/ lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU } @[simp, reassoc, elementwise] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) variables (C) /-- For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the stalk of `f _ * F` at `f x` and the stalk of `F` at `x`. -/ def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', rcases j with ⟨⟨_, _⟩, _⟩, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, induction U using opposite.rec, rcases U with ⟨⟨_, _⟩, _⟩, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end lemma stalk_pushforward_iso_of_open_embedding {f : X ⟶ Y} (hf : open_embedding f) (F : X.presheaf C) (x : X) : is_iso (F.stalk_pushforward _ f x) := begin haveI := functor.initial_of_adjunction (hf.is_open_map.adjunction_nhds x), convert is_iso.of_iso ((functor.final.colimit_iso (hf.is_open_map.functor_nhds x).op ((open_nhds.inclusion (f x)).op ⋙ f _* F) : _).symm ≪≫ colim.map_iso _), swap, { fapply nat_iso.of_components, { intro U, refine F.map_iso (eq_to_iso _), dsimp only [functor.op], exact congr_arg op (subtype.eq $ set.preimage_image_eq (unop U).1.1 hf.inj) }, { intros U V i, erw [← F.map_comp, ← F.map_comp], congr } }, { ext U, rw ← iso.comp_inv_eq, erw colimit.ι_map_assoc, rw [colimit.ι_pre, category.assoc], erw [colimit.ι_map_assoc, colimit.ι_pre, ← F.map_comp_assoc], apply colimit.w ((open_nhds.inclusion (f x)).op ⋙ f _* F) _, dsimp only [functor.op], refine ((hom_of_le _).op : op (unop U) ⟶ _), exact set.image_preimage_subset _ _ }, end end stalk_pushforward section stalk_pullback /-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/ def stalk_pullback_hom (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ⟶ (pullback_obj f F).stalk x := (stalk_functor _ (f x)).map ((pushforward_pullback_adjunction C f).unit.app F) ≫ stalk_pushforward _ _ _ x /-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/ def germ_to_pullback_stalk (f : X ⟶ Y) (F : Y.presheaf C) (U : opens X) (x : U) : (pullback_obj f F).obj (op U) ⟶ F.stalk (f x) := colimit.desc (Lan.diagram (opens.map f).op F (op U)) { X := F.stalk (f x), ι := { app := λ V, F.germ ⟨f x, V.hom.unop.le x.2⟩, naturality' := λ _ _ i, by { erw category.comp_id, exact F.germ_res i.left.unop _ } } } /-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/ def stalk_pullback_inv (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : (pullback_obj f F).stalk x ⟶ F.stalk (f x) := colimit.desc ((open_nhds.inclusion x).op ⋙ presheaf.pullback_obj f F) { X := F.stalk (f x), ι := { app := λ U, F.germ_to_pullback_stalk _ f (unop U).1 ⟨x, (unop U).2⟩, naturality' := λ _ _ _, by { erw [colimit.pre_desc, category.comp_id], congr } } } /-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/ def stalk_pullback_iso (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ≅ (pullback_obj f F).stalk x := { hom := stalk_pullback_hom _ _ _ _, inv := stalk_pullback_inv _ _ _ _, hom_inv_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward germ_to_pullback_stalk germ, ext j, induction j using opposite.rec, cases j, simp only [topological_space.open_nhds.inclusion_map_iso_inv, whisker_right_app, whisker_left_app, whiskering_left_obj_map, functor.comp_map, colimit.ι_map_assoc, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app, category.assoc, colimit.ι_pre_assoc], erw [colimit.ι_desc, colimit.pre_desc, colimit.ι_desc, category.comp_id], simpa end, inv_hom_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward, ext U j, induction U using opposite.rec, cases U, cases j, rcases j_right with ⟨⟨⟩⟩, erw [colimit.map_desc, colimit.map_desc, colimit.ι_desc_assoc, colimit.ι_desc_assoc, colimit.ι_desc, category.comp_id], simp only [cocone.whisker_ι, colimit.cocone_ι, open_nhds.inclusion_map_iso_inv, cocones.precompose_obj_ι, whisker_right_app, whisker_left_app, nat_trans.comp_app, whiskering_left_obj_map, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app], erw ←colimit.w _ (@hom_of_le (open_nhds x) _ ⟨_, U_property⟩ ⟨(opens.map f).obj (unop j_left), j_hom.unop.le U_property⟩ j_hom.unop.le).op, erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), congr, simp only [category.assoc, costructured_arrow.map_mk], delta costructured_arrow.mk, congr, end } end stalk_pullback section stalk_specializes variables {C} /-- If `x` specializes to `y`, then there is a natural map `F.stalk y ⟶ F.stalk x`. -/ noncomputable def stalk_specializes (F : X.presheaf C) {x y : X} (h : x ⤳ y) : F.stalk y ⟶ F.stalk x := begin refine colimit.desc _ ⟨_,λ U, _,_⟩, { exact colimit.ι ((open_nhds.inclusion x).op ⋙ F) (op ⟨(unop U).1, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩) }, { intros U V i, dsimp, rw category.comp_id, let U' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩, let V' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop V).1.2 (unop V).2 : _)⟩, exact colimit.w ((open_nhds.inclusion x).op ⋙ F) (show V' ⟶ U', from i.unop).op } end @[simp, reassoc, elementwise] lemma germ_stalk_specializes (F : X.presheaf C) {U : opens X} {y : U} {x : X} (h : x ⤳ y) : F.germ y ≫ F.stalk_specializes h = F.germ ⟨x, specializes_iff_forall_open.mp h _ U.2 y.prop⟩ := colimit.ι_desc _ _ @[simp, reassoc, elementwise] lemma germ_stalk_specializes' (F : X.presheaf C) {U : opens X} {x y : X} (h : x ⤳ y) (hy : y ∈ U) : F.germ ⟨y, hy⟩ ≫ F.stalk_specializes h = F.germ ⟨x, specializes_iff_forall_open.mp h _ U.2 hy⟩ := colimit.ι_desc _ _ @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_functor_map {F G : X.presheaf C} (f : F ⟶ G) {x y : X} (h : x ⤳ y) : F.stalk_specializes h ≫ (stalk_functor C x).map f = (stalk_functor C y).map f ≫ G.stalk_specializes h := by { ext, delta stalk_functor, simpa [stalk_specializes] } @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) {x y : X} (h : x ⤳ y) : (f _* F).stalk_specializes (f.map_specializes h) ≫ F.stalk_pushforward _ f x = F.stalk_pushforward _ f y ≫ F.stalk_specializes h := by { ext, delta stalk_pushforward, simpa [stalk_specializes] } end stalk_specializes section concrete variables {C} variables [concrete_category.{v} C] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] variables [preserves_filtered_colimits (forget C)] /-- For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits, every element of the stalk is the germ of a section. -/ lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective.{v v} _ (is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff.{v v} _ (is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G) (h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) : function.injective ((stalk_functor C x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)] /-- Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal. -/ lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U)) (h : ∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.presheaf.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) (U : opens X) (h : ∀ x : U, function.injective ((stalk_functor C x.val).map f)) : function.injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) : (∀ x : X, function.injective ((stalk_functor C x).map f)) ↔ (∀ U : opens X, function.injective (f.app (op U))) := ⟨λ h U, app_injective_of_stalk_functor_map_injective f U (λ x, h x.1), stalk_functor_map_injective_of_app_injective f⟩ /-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` agree on `V`. -/ lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (hinj : ∀ x : U, function.injective ((stalk_functor C x.1).map f.1)) (hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)), f.1.app (op V) s = G.1.map iVU.op t) : function.surjective (f.1.app (op U)) := begin intro t, -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using hsurj t, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, rw [← comp_apply, ← f.1.naturality, comp_apply, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (hinj ⟨z, (iVU x).le ((inf_le_left : V x ⊓ V y ≤ V x) z.2)⟩), dsimp only, erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], simp_rw [← comp_apply, f.1.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp], refl } end lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) : function.surjective (f.1.app (op U)) := begin refine app_surjective_of_injective_of_locally_surjective f U (λ x, (h x).1) (λ t x, _), -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.presheaf.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f.1 s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁], rw [← comp_apply, f.1.naturality, comp_apply, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) : function.bijective (f.1.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f.1 U (λ x, (h x).1), app_surjective_of_stalk_functor_map_bijective f U h⟩ lemma app_is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) (U : opens X) [∀ x : U, is_iso ((stalk_functor C x.val).map f.1)] : is_iso (f.1.app (op U)) := begin -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the -- underlying map between types is an isomorphism, i.e. bijective. suffices : is_iso ((forget C).map (f.1.app (op U))), { exactI is_iso_of_reflects_iso (f.1.app (op U)) (forget C) }, rw is_iso_iff_bijective, apply app_bijective_of_stalk_functor_map_bijective, intro x, apply (is_iso_iff_bijective _).mp, exact functor.map_is_iso (forget C) ((stalk_functor C x.1).map f.1) end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism `f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor C x).map f.1)] : is_iso f := begin -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to -- show that `f`, as a morphism between _presheaves_, is an isomorphism. suffices : is_iso ((sheaf.forget C X).map f), { exactI is_iso_of_fully_faithful (sheaf.forget C X) f }, -- We show that all components of `f` are isomorphisms. suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.1.app U), { exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f.1 this, }, intro U, induction U using opposite.rec, apply app_is_iso_of_stalk_functor_map_iso end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an isomorphism if and only if all of its stalk maps are isomorphisms. -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f.1) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f.1 ((sheaf.forget C X).map_is_iso f) }, { intro h, exactI is_iso_of_stalk_functor_map_iso f } end end concrete instance (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra (F.obj $ op U) (F.stalk x) := (F.germ x).to_algebra @[simp] lemma stalk_open_algebra_map {X : Top} (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra_map (F.obj $ op U) (F.stalk x) = F.germ x := rfl end Top.presheaf
0dc0d8ebcd9ce49c94da815ff64a26d280c8a235
f68ef9a599ec5575db7b285d4960e63c5d464ccc
/Exercises/Lista 3/HAM-LucasMoschen.lean
9934b8304e69055c536440628c509a6c060af9fb
[]
no_license
lucasmoschen/discrete-mathematics
a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3
0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e
refs/heads/master
1,677,111,757,003
1,611,500,097,000
1,611,500,097,000
205,903,359
1
0
null
null
null
null
UTF-8
Lean
false
false
11,858
lean
-- Considerarei um grafo de 4 vértices A, B, C, D, com arestas AB, BC, AD e BD -- Veja que um caminho Hamiltoniano possível é D -> A -> B -> C -- Farei A = 1, B = 2, C = 3, D = 4 -- Logo G = ((1,2),(2,3),(1,4),(2,4)) -- Lembrando que xij é: a i-ésima posição no caminho é ocupada pelo j-ésimo nó. variables {x11 x12 x13 x14 x21 x22 x23 x24 x31 x32 x33 x34 x41 x42 x43 x44: Prop} -- Quero provar que esse caminho é Hamiltoniano, logo essa sequência de "And's" é satisfeita. variable path: x14 ∧ x21 ∧ x32 ∧ x43 -- Também queremos que: variable not_path: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44 -- Vou demostrar que esse caminho satisfaz todas as condições -- Cada nó ocupa uma posição. lemma condition1 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (x11 ∨ x21 ∨ x31 ∨ x41) ∧ (x12 ∨ x22 ∨ x32 ∨ x42) ∧ (x13 ∨ x23 ∨ x33 ∨ x43) ∧ (x14 ∨ x24 ∨ x34 ∨ x44) := have h1: (x11 ∨ x21 ∨ x31 ∨ x41), from or.inr (or.inl p.right.left), have h2: (x12 ∨ x22 ∨ x32 ∨ x42), from or.inr (or.inr (or.inl (p.right.right.left))), have h3: (x13 ∨ x23 ∨ x33 ∨ x43), from or.inr (or.inr (or.inr (p.right.right.right))), have h4: (x14 ∨ x24 ∨ x34 ∨ x44), from or.inl p.left, show (x11 ∨ x21 ∨ x31 ∨ x41) ∧ (x12 ∨ x22 ∨ x32 ∨ x42) ∧ (x13 ∨ x23 ∨ x33 ∨ x43) ∧ (x14 ∨ x24 ∨ x34 ∨ x44), from and.intro h1 (and.intro h2 (and.intro h3 h4)) -- o nó não pode ocupar duas posições. lemma condition2_node1 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x12 ∨ ¬ x22) ∧ (¬ x12 ∨ ¬ x32) ∧ (¬ x12 ∨ ¬ x42) ∧ (¬ x22 ∨ ¬ x32) ∧ (¬ x22 ∨ ¬ x42) ∧ (¬ x32 ∨ ¬ x42) := have h1: ¬ x12, from np.right.left, have h2: ¬ x22, from np.right.right.right.left, have h3: ¬ x42, from np.right.right.right.right.right.right.right.right.right.right.left, show (¬ x12 ∨ ¬ x22) ∧ (¬ x12 ∨ ¬ x32) ∧ (¬ x12 ∨ ¬ x42) ∧ (¬ x22 ∨ ¬ x32) ∧ (¬ x22 ∨ ¬ x42) ∧ (¬ x32 ∨ ¬ x42), from and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h2) (and.intro (or.inr h3) (or.inr h3))))) lemma condition2_node2 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x11 ∨ ¬ x21) ∧ (¬ x11 ∨ ¬ x31) ∧ (¬ x11 ∨ ¬ x41) ∧ (¬ x21 ∨ ¬ x31) ∧ (¬ x21 ∨ ¬ x41) ∧ (¬ x31 ∨ ¬ x41) := have h1: ¬ x11, from np.left, have h2: ¬ x31, from np.right.right.right.right.right.right.left, have h3: ¬ x41, from np.right.right.right.right.right.right.right.right.right.left, show (¬ x11 ∨ ¬ x21) ∧ (¬ x11 ∨ ¬ x31) ∧ (¬ x11 ∨ ¬ x41) ∧ (¬ x21 ∨ ¬ x31) ∧ (¬ x21 ∨ ¬ x41) ∧ (¬ x31 ∨ ¬ x41), from and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inr h2) (and.intro (or.inr h3) (or.inl h2))))) lemma condition2_node3 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x13 ∨ ¬ x23) ∧ (¬ x13 ∨ ¬ x33) ∧ (¬ x13 ∨ ¬ x43) ∧ (¬ x23 ∨ ¬ x33) ∧ (¬ x23 ∨ ¬ x43) ∧ (¬ x33 ∨ ¬ x43) := have h1: ¬ x13, from np.right.right.left, have h2: ¬ x23, from np.right.right.right.right.left, have h3: ¬ x33, from np.right.right.right.right.right.right.right.left, show (¬ x13 ∨ ¬ x23) ∧ (¬ x13 ∨ ¬ x33) ∧ (¬ x13 ∨ ¬ x43) ∧ (¬ x23 ∨ ¬ x33) ∧ (¬ x23 ∨ ¬ x43) ∧ (¬ x33 ∨ ¬ x43), from and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h2) (and.intro (or.inl h2) (or.inl h3))))) lemma condition2_node4 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x14 ∨ ¬ x24) ∧ (¬ x14 ∨ ¬ x34) ∧ (¬ x14 ∨ ¬ x44) ∧ (¬ x24 ∨ ¬ x34) ∧ (¬ x24 ∨ ¬ x44) ∧ (¬ x34 ∨ ¬ x44) := have h1: ¬ x24, from np.right.right.right.right.right.left, have h2: ¬ x34, from np.right.right.right.right.right.right.right.right.left, have h3: ¬ x44, from np.right.right.right.right.right.right.right.right.right.right.right, show (¬ x14 ∨ ¬ x24) ∧ (¬ x14 ∨ ¬ x34) ∧ (¬ x14 ∨ ¬ x44) ∧ (¬ x24 ∨ ¬ x34) ∧ (¬ x24 ∨ ¬ x44) ∧ (¬ x34 ∨ ¬ x44), from and.intro (or.inr h1) (and.intro (or.inr h2) (and.intro (or.inr h3) (and.intro (or.inl h1) (and.intro (or.inr h3) (or.inl h2))))) -- Cada posição deve ser ocupada por um nó lemma condition3 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (x11 ∨ x12 ∨ x13 ∨ x14) ∧ (x21 ∨ x22 ∨ x23 ∨ x24) ∧ (x31 ∨ x32 ∨ x33 ∨ x34) ∧ (x41 ∨ x42 ∨ x43 ∨ x44) := show (x11 ∨ x12 ∨ x13 ∨ x14) ∧ (x21 ∨ x22 ∨ x23 ∨ x24) ∧ (x31 ∨ x32 ∨ x33 ∨ x34) ∧ (x41 ∨ x42 ∨ x43 ∨ x44), from and.intro (or.inr(or.inr(or.inr(p.left)))) (and.intro (or.inl(p.right.left)) (and.intro (or.inr(or.inl(p.right.right.left))) (or.inr(or.inr(or.inl(p.right.right.right)))))) -- Cada posição pode ser ocupada po apenas um nó. lemma condition4_position1 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x11 ∨ ¬ x12) ∧ (¬ x11 ∨ ¬ x13) ∧ (¬ x11 ∨ ¬ x14) ∧ (¬ x12 ∨ ¬ x13) ∧ (¬ x12 ∨ ¬ x14) ∧ (¬ x13 ∨ ¬ x14) := have h1: ¬ x11, from np.left, have h2: ¬ x12, from np.right.left, have h3: ¬ x13, from np.right.right.left, show (¬ x11 ∨ ¬ x12) ∧ (¬ x11 ∨ ¬ x13) ∧ (¬ x11 ∨ ¬ x14) ∧ (¬ x12 ∨ ¬ x13) ∧ (¬ x12 ∨ ¬ x14) ∧ (¬ x13 ∨ ¬ x14), from and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h2) (and.intro (or.inl h2) (or.inl h3))))) lemma condition4_position2 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x21 ∨ ¬ x22) ∧ (¬ x21 ∨ ¬ x23) ∧ (¬ x21 ∨ ¬ x24) ∧ (¬ x22 ∨ ¬ x23) ∧ (¬ x22 ∨ ¬ x24) ∧ (¬ x23 ∨ ¬ x24) := have h1: ¬ x22, from np.right.right.right.left, have h2: ¬ x23, from np.right.right.right.right.left, have h3: ¬ x24, from np.right.right.right.right.right.left, show (¬ x21 ∨ ¬ x22) ∧ (¬ x21 ∨ ¬ x23) ∧ (¬ x21 ∨ ¬ x24) ∧ (¬ x22 ∨ ¬ x23) ∧ (¬ x22 ∨ ¬ x24) ∧ (¬ x23 ∨ ¬ x24), from and.intro (or.inr h1) (and.intro (or.inr h2) (and.intro (or.inr h3) (and.intro (or.inl h1) (and.intro (or.inl h1) (or.inl h2))))) lemma condition4_position3 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x31 ∨ ¬ x32) ∧ (¬ x31 ∨ ¬ x33) ∧ (¬ x31 ∨ ¬ x34) ∧ (¬ x32 ∨ ¬ x33) ∧ (¬ x32 ∨ ¬ x34) ∧ (¬ x33 ∨ ¬ x34) := have h1: ¬ x31, from np.right.right.right.right.right.right.left, have h2: ¬ x33, from np.right.right.right.right.right.right.right.left, have h3: ¬ x34, from np.right.right.right.right.right.right.right.right.left, show (¬ x31 ∨ ¬ x32) ∧ (¬ x31 ∨ ¬ x33) ∧ (¬ x31 ∨ ¬ x34) ∧ (¬ x32 ∨ ¬ x33) ∧ (¬ x32 ∨ ¬ x34) ∧ (¬ x33 ∨ ¬ x34), from and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inr h2) (and.intro (or.inr h3) (or.inr h3))))) lemma condition4_position4 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x41 ∨ ¬ x42) ∧ (¬ x41 ∨ ¬ x43) ∧ (¬ x41 ∨ ¬ x44) ∧ (¬ x42 ∨ ¬ x43) ∧ (¬ x42 ∨ ¬ x44) ∧ (¬ x43 ∨ ¬ x44) := have h1: ¬ x41, from np.right.right.right.right.right.right.right.right.right.left, have h2: ¬ x42, from np.right.right.right.right.right.right.right.right.right.right.left, have h3: ¬ x44, from np.right.right.right.right.right.right.right.right.right.right.right, show (¬ x41 ∨ ¬ x42) ∧ (¬ x41 ∨ ¬ x43) ∧ (¬ x41 ∨ ¬ x44) ∧ (¬ x42 ∨ ¬ x43) ∧ (¬ x42 ∨ ¬ x44) ∧ (¬ x43 ∨ ¬ x44), from and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h1) (and.intro (or.inl h2) (and.intro (or.inl h2) (or.inr h3))))) -- (1,3) e (3,4) não pertencem ao grafo, portanto não podem ser subsequentes. -- Nós não adjacentes não podem fazer parte do caminho de forma adjacente. lemma condition5_13 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x11 ∨ ¬ x23) ∧ (¬ x21 ∨ ¬ x33) ∧ (¬ x31 ∨ ¬ x43) ∧ (¬ x13 ∨ ¬ x21) ∧ (¬ x23 ∨ ¬ x31) ∧ (¬ x33 ∨ ¬ x41) := have h1: ¬ x11, from np.left, have h2: ¬ x13, from np.right.right.left, have h3: ¬ x31, from np.right.right.right.right.right.right.left, have h4: ¬ x33, from np.right.right.right.right.right.right.right.left, show (¬ x11 ∨ ¬ x23) ∧ (¬ x21 ∨ ¬ x33) ∧ (¬ x31 ∨ ¬ x43) ∧ (¬ x13 ∨ ¬ x21) ∧ (¬ x23 ∨ ¬ x31) ∧ (¬ x33 ∨ ¬ x41), from and.intro (or.inl h1) (and.intro (or.inr h4) (and.intro (or.inl h3) (and.intro (or.inl h2) (and.intro (or.inr h3) (or.inl h4))))) lemma condition5_34 (p: x14 ∧ x21 ∧ x32 ∧ x43) (np: ¬ x11 ∧ ¬ x12 ∧ ¬ x13 ∧ ¬ x22 ∧ ¬ x23 ∧ ¬ x24 ∧ ¬ x31 ∧ ¬ x33 ∧ ¬ x34 ∧ ¬ x41 ∧ ¬ x42 ∧ ¬ x44) : (¬ x13 ∨ ¬ x24) ∧ (¬ x23 ∨ ¬ x34) ∧ (¬ x33 ∨ ¬ x44) ∧ (¬ x14 ∨ ¬ x23) ∧ (¬ x24 ∨ ¬ x33) ∧ (¬ x34 ∨ ¬ x43) := have h1: ¬ x13, from np.right.right.left, have h2: ¬ x23, from np.right.right.right.right.left, have h3: ¬ x33, from np.right.right.right.right.right.right.right.left, have h4: ¬ x34, from np.right.right.right.right.right.right.right.right.left, show (¬ x13 ∨ ¬ x24) ∧ (¬ x23 ∨ ¬ x34) ∧ (¬ x33 ∨ ¬ x44) ∧ (¬ x14 ∨ ¬ x23) ∧ (¬ x24 ∨ ¬ x33) ∧ (¬ x34 ∨ ¬ x43), from and.intro (or.inl h1) (and.intro (or.inl h2) (and.intro (or.inl h3) (and.intro (or.inr h2) (and.intro (or.inr h3) (or.inl h4)))))
23a50e02a93de4ccf5cac86bca7b124ff5fe2d17
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/asymptotics/asymptotic_equivalent.lean
490648229c582697b4daa8e9cdebf687dd72232b
[ "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,271
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics.asymptotics import analysis.normed_space.ordered /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent l u v`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomain `β`. While the definition only requires `β` to be a `normed_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent l u v`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) ## Implementation Notes Note that `is_equivalent` takes the parameters `(l : filter α) (u v : α → β)` in that order. This is to enable `calc` support, as `calc` requires that the last two explicit arguments are `u v`. -/ namespace asymptotics open filter function open_locale topological_space section normed_group variables {α β : Type*} [normed_group β] /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent (l : filter α) (u v : α → β) := is_o (u - v) v l localized "notation u ` ~[`:50 l:50 `] `:0 v:50 := asymptotics.is_equivalent l u v" in asymptotics variables {u v w : α → β} {l : filter α} lemma is_equivalent.is_o (h : u ~[l] v) : is_o (u - v) v l := h lemma is_equivalent.is_O (h : u ~[l] v) : is_O u v l := (is_O.congr_of_sub h.is_O.symm).mp (is_O_refl _ _) lemma is_equivalent.is_O_symm (h : u ~[l] v) : is_O v u l := begin convert h.is_o.right_is_O_add, ext, simp end @[refl] lemma is_equivalent.refl : u ~[l] u := begin rw [is_equivalent, sub_self], exact is_o_zero _ _ end @[symm] lemma is_equivalent.symm (h : u ~[l] v) : v ~[l] u := (h.is_o.trans_is_O h.is_O_symm).symm @[trans] lemma is_equivalent.trans {l : filter α} {u v w : α → β} (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := (huv.is_o.trans_is_O hvw.is_O).triangle hvw.is_o lemma is_equivalent.congr_left {u v w : α → β} {l : filter α} (huv : u ~[l] v) (huw : u =ᶠ[l] w) : w ~[l] v := is_o.congr' (huw.sub (eventually_eq.refl _ _)) (eventually_eq.refl _ _) huv lemma is_equivalent.congr_right {u v w : α → β} {l : filter α} (huv : u ~[l] v) (hvw : v =ᶠ[l] w) : u ~[l] w := (huv.symm.congr_left hvw).symm lemma is_equivalent_zero_iff_eventually_zero : u ~[l] 0 ↔ u =ᶠ[l] 0 := begin rw [is_equivalent, sub_zero], exact is_o_zero_right_iff end lemma is_equivalent_zero_iff_is_O_zero : u ~[l] 0 ↔ is_O u (0 : α → β) l := begin refine ⟨is_equivalent.is_O, λ h, _⟩, rw [is_equivalent_zero_iff_eventually_zero, eventually_eq_iff_exists_mem], exact ⟨{x : α | u x = 0}, is_O_zero_right_iff.mp h, λ x hx, hx⟩, end lemma is_equivalent_const_iff_tendsto {c : β} (h : c ≠ 0) : u ~[l] const _ c ↔ tendsto u l (𝓝 c) := begin rw [is_equivalent, is_o_const_iff h], split; intro h; [ { have := h.sub tendsto_const_nhds, rw zero_sub (-c) at this }, { have := h.sub tendsto_const_nhds, rw ← sub_self c} ]; convert this; try { ext }; simp end lemma is_equivalent.tendsto_const {c : β} (hu : u ~[l] const _ c) : tendsto u l (𝓝 c) := begin rcases (em $ c = 0) with ⟨rfl, h⟩, { exact (tendsto_congr' $ is_equivalent_zero_iff_eventually_zero.mp hu).mpr tendsto_const_nhds }, { exact (is_equivalent_const_iff_tendsto h).mp hu } end lemma is_equivalent.tendsto_nhds {c : β} (huv : u ~[l] v) (hu : tendsto u l (𝓝 c)) : tendsto v l (𝓝 c) := begin by_cases h : c = 0, { subst c, rw ← is_o_one_iff ℝ at hu ⊢, simpa using (huv.symm.is_o.trans hu).add hu }, { rw ← is_equivalent_const_iff_tendsto h at hu ⊢, exact huv.symm.trans hu } end lemma is_equivalent.tendsto_nhds_iff {c : β} (huv : u ~[l] v) : tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c) := ⟨huv.tendsto_nhds, huv.symm.tendsto_nhds⟩ lemma is_equivalent.add_is_o (huv : u ~[l] v) (hwv : is_o w v l) : (w + u) ~[l] v := begin rw is_equivalent at *, convert hwv.add huv, ext, simp [add_sub], end lemma is_o.is_equivalent (huv : is_o (u - v) v l) : u ~[l] v := huv lemma is_equivalent.neg (huv : u ~[l] v) : (λ x, - u x) ~[l] (λ x, - v x) := begin rw is_equivalent, convert huv.is_o.neg_left.neg_right, ext, simp, end end normed_group open_locale asymptotics section normed_field variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent_iff_exists_eq_mul : u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := begin rw [is_equivalent, is_o_iff_exists_eq_mul], split; rintros ⟨φ, hφ, h⟩; [use (φ + 1), use (φ - 1)]; split, { conv in (𝓝 _) { rw ← zero_add (1 : β) }, exact hφ.add (tendsto_const_nhds) }, { convert h.add (eventually_eq.refl l v); ext; simp [add_mul] }, { conv in (𝓝 _) { rw ← sub_self (1 : β) }, exact hφ.sub (tendsto_const_nhds) }, { convert h.sub (eventually_eq.refl l v); ext; simp [sub_mul] } end lemma is_equivalent.exists_eq_mul (huv : u ~[l] v) : ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := is_equivalent_iff_exists_eq_mul.mp huv lemma is_equivalent_of_tendsto_one (hz : ∀ᶠ x in l, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := begin rw is_equivalent_iff_exists_eq_mul, refine ⟨u/v, huv, hz.mono $ λ x hz', (div_mul_cancel_of_imp hz').symm⟩, end lemma is_equivalent_of_tendsto_one' (hz : ∀ x, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := is_equivalent_of_tendsto_one (eventually_of_forall hz) huv lemma is_equivalent_iff_tendsto_one (hz : ∀ᶠ x in l, v x ≠ 0) : u ~[l] v ↔ tendsto (u/v) l (𝓝 1) := begin split, { intro hequiv, have := hequiv.is_o.tendsto_div_nhds_zero, simp only [pi.sub_apply, sub_div] at this, have key : tendsto (λ x, v x / v x) l (𝓝 1), { exact (tendsto_congr' $ hz.mono $ λ x hnz, @div_self _ _ (v x) hnz).mpr tendsto_const_nhds }, convert this.add key, { ext, simp }, { norm_num } }, { exact is_equivalent_of_tendsto_one (hz.mono $ λ x hnvz hz, (hnvz hz).elim) } end end normed_field section smul lemma is_equivalent.smul {α E 𝕜 : Type*} [normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] {a b : α → 𝕜} {u v : α → E} {l : filter α} (hab : a ~[l] b) (huv : u ~[l] v) : (λ x, a x • u x) ~[l] (λ x, b x • v x) := begin rcases hab.exists_eq_mul with ⟨φ, hφ, habφ⟩, have : (λ (x : α), a x • u x) - (λ (x : α), b x • v x) =ᶠ[l] λ x, b x • ((φ x • u x) - v x), { convert (habφ.comp₂ (•) $ eventually_eq.refl _ u).sub (eventually_eq.refl _ (λ x, b x • v x)), ext, rw [pi.mul_apply, mul_comm, mul_smul, ← smul_sub] }, refine (is_o_congr this.symm $ eventually_eq.rfl).mp ((is_O_refl b l).smul_is_o _), rcases huv.is_O.exists_pos with ⟨C, hC, hCuv⟩, rw is_equivalent at *, rw is_o_iff at *, rw is_O_with at hCuv, simp only [metric.tendsto_nhds, dist_eq_norm] at hφ, intros c hc, specialize hφ ((c/2)/C) (div_pos (by linarith) hC), specialize huv (show 0 < c/2, by linarith), refine hφ.mp (huv.mp $ hCuv.mono $ λ x hCuvx huvx hφx, _), have key := calc ∥φ x - 1∥ * ∥u x∥ ≤ (c/2) / C * ∥u x∥ : mul_le_mul_of_nonneg_right hφx.le (norm_nonneg $ u x) ... ≤ (c/2) / C * (C*∥v x∥) : mul_le_mul_of_nonneg_left hCuvx (div_pos (by linarith) hC).le ... = c/2 * ∥v x∥ : by {field_simp [hC.ne.symm], ring}, calc ∥((λ (x : α), φ x • u x) - v) x∥ = ∥(φ x - 1) • u x + (u x - v x)∥ : by simp [sub_smul, sub_add] ... ≤ ∥(φ x - 1) • u x∥ + ∥u x - v x∥ : norm_add_le _ _ ... = ∥φ x - 1∥ * ∥u x∥ + ∥u x - v x∥ : by rw norm_smul ... ≤ c / 2 * ∥v x∥ + ∥u x - v x∥ : add_le_add_right key _ ... ≤ c / 2 * ∥v x∥ + c / 2 * ∥v x∥ : add_le_add_left huvx _ ... = c * ∥v x∥ : by ring, end end smul section mul_inv variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent.mul (htu : t ~[l] u) (hvw : v ~[l] w) : t * v ~[l] u * w := htu.smul hvw lemma is_equivalent.inv (huv : u ~[l] v) : (λ x, (u x)⁻¹) ~[l] (λ x, (v x)⁻¹) := begin rw is_equivalent_iff_exists_eq_mul at *, rcases huv with ⟨φ, hφ, h⟩, rw ← inv_one, refine ⟨λ x, (φ x)⁻¹, tendsto.inv₀ hφ (by norm_num) , _⟩, convert h.inv, ext, simp [mul_inv] end lemma is_equivalent.div (htu : t ~[l] u) (hvw : v ~[l] w) : (λ x, t x / v x) ~[l] (λ x, u x / w x) := by simpa only [div_eq_mul_inv] using htu.mul hvw.inv end mul_inv section normed_linear_ordered_field variables {α β : Type*} [normed_linear_ordered_field β] {u v : α → β} {l : filter α} lemma is_equivalent.tendsto_at_top [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_top) : tendsto v l at_top := let ⟨φ, hφ, h⟩ := huv.symm.exists_eq_mul in tendsto.congr' h.symm ((mul_comm u φ) ▸ (hu.at_top_mul zero_lt_one hφ)) lemma is_equivalent.tendsto_at_top_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_top ↔ tendsto v l at_top := ⟨huv.tendsto_at_top, huv.symm.tendsto_at_top⟩ lemma is_equivalent.tendsto_at_bot [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_bot) : tendsto v l at_bot := begin convert tendsto_neg_at_top_at_bot.comp (huv.neg.tendsto_at_top $ tendsto_neg_at_bot_at_top.comp hu), ext, simp end lemma is_equivalent.tendsto_at_bot_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_bot ↔ tendsto v l at_bot := ⟨huv.tendsto_at_bot, huv.symm.tendsto_at_bot⟩ end normed_linear_ordered_field end asymptotics open filter asymptotics open_locale asymptotics variables {α β : Type*} [normed_group β] lemma filter.eventually_eq.is_equivalent {u v : α → β} {l : filter α} (h : u =ᶠ[l] v) : u ~[l] v := is_o.congr' h.sub_eq.symm (eventually_eq.refl _ _) (is_o_zero v l)
dcb9b4f6469d2040c0799652a6bde7d0d8a549f8
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/HW/hw9_extra_credit_exam_prep.lean
db17e8dfae44628712ccc61b82d3ec30d9845d4a
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
9,335
lean
-- Derek Johnson namespace hidden -- you can ignore this /- 1a. Define a polymorphic tree type. A tree of objects of type α is either empty or it is a value of type α along with two smaller trees of the same kind. You can call them left and right respectively. -/ inductive tree (α : Type) : Type | empty : tree | nonempty (a : α) (left : tree) (right : tree) : tree /- 1b. Define a polymorphic function, is_empty, that takes a value of type, tree α, and that returns Boolean tt if it is empty and ff otherwise. -/ open tree def is_empty {α : Type} : (tree α) → bool | (tree.empty a) := tt | _ := ff def ee := tree.empty ℕ #check is_empty ee /- 1b. Define a polymorphic function, num_nodes, that takes a value of type, tree α, and that returns the number of nodes in the tree. -/ def num_nodes {α : Type} : (tree α) → ℕ | (tree.empty a) := 0 | (tree.nonempty a l r) := 1 + (num_nodes l) + (num_nodes r) /- 2. A bit has one of two values. Imagine a type, let's call it trit, with three values (e.g., true, false, and dont-know). How many binary functions are there, taking two values of tihs type and returning a value of the same type? -/ -- (3^1)^(3^2) = 19,683 /- 3. Define a function, sum_squares, that takes a natural number, n, as an argument, and that returns the sum of the squaress of all of the natural numbers from 0 to n, inclusive. -/ open nat def sum_squares : ℕ → ℕ | 0 := 0 | (succ n) := ((n+1)^2) + sum_squares (n) /- 4a. We represent a binary relation, R, on a set of values of some type, α, as a predicate with two arguments. In Lean such a predicate is of type α → α → Prop. A property of such a relation is a predicate on a relation, and so is of type (α → α → Prop) → Prop. Here is the definition of a property of binary relations called asymmetry. A relation is said to be asymmetric if whenever (x, y) is in the relation, (y, x) is not. For example, the less-than relation on natural numbers is asymmetric. -/ def asymmetric {α : Type} (R : α → α → Prop) : Prop := ∀ (x y : α), R x y → ¬ R y x /- Similarly, a relation is said to be irreflexive if for all x, (x, x) is not in the relation. For example, an "is-unequal-to" relation on the natural numbers would include (3, 4) because 3 is unequal to 4, but it would not include (3, 3) because 3 is not unqual to 3. Write a formal definition of irreflexive in the style of the definition of asymmetric above. Start the actual definition (after the :=) with ∀ (x : α). -/ def irreflexive {α : Type} (R : α → α → Prop) : Prop := ∀ (x : α), ¬ R x x /- 4b. Prove that if a relation is asymmetric then it is irreflexive by completing the following proof. -/ theorem asy_imp_irr : ∀ (α : Type) (F : α → α → Prop), asymmetric F → irreflexive F := begin assume α : Type, assume F, unfold asymmetric irreflexive, assume asym, assume x, assume fxx, have bbb := asym x x, have ll := bbb fxx, contradiction, --exact ll fxx, end example : ∀ (α : Type) (F : α → α → Prop), asymmetric F → irreflexive F := begin assume α, assume F, unfold asymmetric irreflexive, assume asym, assume x, assume reflex, have contra := asym x x, have contra2 := contra reflex, apply contra2 reflex, end /- 5. Prove the following. You may use a tactic script, as indicated here, or switch to another format for your proof. Whatever you are most comfortable with is fine. -/ example : ∀ (P Q R : Prop), (∀ (p : P), Q) → (∀ (q :Q), R) → (P ∨ Q) → R := begin intros, cases a_2, apply a_1 (a a_2), apply a_1 a_2, end /- 6. Prove that every natural number, n, has a successor. Formalize this statement using universal and existential quantifiers: for every natural number n there exists a natural number m such that m is the successor of n. Then complete the proof. Finish what we've started for you. -/ example : ∀ (n : ℕ), ∃(m : ℕ), m = succ n := begin assume n, apply exists.intro (n+1), refl, end /- 7. Consider a binary relation, squares, on the natural numbers. A pair, (x, y), is in this relation if and only if y=x^2. Formalize this relation in Lean as a predicate, squares, with two natural number arguments and one proof constructor called intro. Then state and prove the simple proposition that the pair, (7, 49), is in this relation. -/ -- Answer here inductive squares : ℕ → ℕ → Prop | intros : ∀(x y : ℕ), x^2=y → squares x y open squares theorem squaresEx: squares 7 49 := begin apply intros 7 49, apply eq.refl (7^2), end /- 8. This question asks you to model a little world. The world has people in it (a type) and there is a binary relation, parent_of, on people. What is means for a pair (x, y) to be in this relation is that x is a parent of y. -/ axiom Person : Type axiom ParentOf : Person → Person → Prop /- Define a GrandParentOf relation, such that (x, y) is in this relation if and only if x is a grand parent of y. What this means, of course, is that there is some z such that x is the parent of z and z is the parent of y. Define the GrandParentOf relation using an inductive type definition in the usual way. It needs only one constructor, which must enforce the condition that defines what it means "to be a grandparent of". -/ inductive GrandParentOf : Person → Person → Prop | const : ∀(x y : Person), (∃(z : Person),(ParentOf x z) ∧ (ParentOf z y)) → GrandParentOf x y /- 9. In simple English explain what it means for a binary relation on a set to be * reflexive: Every value equals itself. In variables, x = x * transitive: Results from seperate operations can be combined to form extended results. In variables, if x = y and y = z, x = z * symmetric: It does not matter what order two values are compared, they will return the same value. In variables, if x = y then y = x. Give an example of an everyday mathematical relation other than equality that is transitive. Greater-than Is the greater-than relation reflexive? Explain. No, greater than implies that one value is larger than the other, something that can not happen when the two values are the same. Is it symmetric? Explain. No, greater-than requires ordering and the symmetric property disregards ordering. For example 2 is greater than 1 but 1 is not greater than 2. -/ /- 10. Give a natural language proof, in your own words, showing that the square root of two is irrational. You may find the details of this proof easily by searching online. -/ /- If 2^(1/2) were rational we would be able to express it in a fractional form b/a in which a and b are relatively prime numbers. We can then extend the equation to 2 = (b^2)/(a^2) From here we can simplify again 2(a^2) = b^2 We know now that since it is multiplied by 2, 2(a^2) will be even and therefore, b^2 will be even as well. Therefore b can be written as 2c resulting in the equatino 2(a^2) = 4c^2 (a^2) = 2c^2 Since 2c^2 is even, a^2 is even, and since a^2 is even, so is a. However, two even numbers cannot be relatively prime because 2 would be a common multiple! Because of this 2^(1/2) can not be expressed as a rational fraction Hence, 2^(1/2) is irrational -/ /- 11. Prove formally that 0 ≠ 1, then translate your formal proof, step by step, into an English language proof, citing the reasoning principles that you use. What fundamental proof strategy is centrally involved in this proof? -/ example : 0 ≠ 1 := begin assume h : 0=1, cases h, end /- In order to prove that 0 ≠ 1, we are really proving that the Proposition (0 ≠ 1) → false. To prove this, we first need a proof of 0 =1. We then can prove then derive a proof of false for every case. This is where the cases command is applied. In this instance, there are no cases of h because there is no way to prove equality with two distint values. With no cases left to prove, the overall proof is done. -/ /- 12. Lean includes the law of the excluded middle in a closed namespace called classical. The axiom goes by the name, classical.em. You may apply it to any proposition, P, to obtain a proof of P ∨ ¬ P. Use the law of the excluded middle to show that proof by contradiction is valid, as long as you accept em as an axiom. Hint: We covered this in class. -/ theorem by_contradiction: ∀(P : Prop), ¬ ¬ P → P := begin assume P, cases (classical.em P), assume nnp, exact h, assume nnp, contradiction end /- 13. Let's define a natural number to be cool if it's either 2 or 5 or the sum or the product of two cool numbers. Formalize this definition in Lean and then state and prove the proposition that 35 is cool. -/ inductive cool : ℕ → Prop | cool2 : cool 2 | cool5 : cool 5 | coolSum : ∀(x y: ℕ), cool x → cool y → cool (x + y) | coolMult : ∀(x y: ℕ), cool x → cool y → cool (x * y) open cool example : cool 35 := begin apply coolMult 7 5, apply coolSum 5 2, exact cool5, exact cool2, exact cool5, end end hidden
45dd20c835ee2f9531f4241c27779e7d2b26e66f
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Exception.lean
1a59157ebace82d66048852af763e3c28013aca7
[ "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
6,119
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Message import Lean.InternalExceptionId import Lean.Data.Options import Lean.Util.MonadCache namespace Lean /-- Exception type used in most Lean monads -/ inductive Exception where /-- Error messages that are displayed to users. `ref` is used to provide position information. -/ | error (ref : Syntax) (msg : MessageData) /-- Internal exceptions that are not meant to be seen by users. Examples: "pospone elaboration", "stuck at universe constraint", etc -/ | internal (id : InternalExceptionId) (extra : KVMap := {}) /-- Convert exception into a structured message. -/ def Exception.toMessageData : Exception → MessageData | .error _ msg => msg | .internal id _ => id.toString /-- Return syntax object providing position information for the exception. Recall that internal exceptions do not have position information. -/ def Exception.getRef : Exception → Syntax | .error ref _ => ref | .internal _ _ => Syntax.missing instance : Inhabited Exception := ⟨Exception.error default default⟩ /-- Similar to `AddMessageContext`, but for error messages. The default instance just uses `AddMessageContext`. In error messages, we may want to provide additional information (e.g., macro expansion stack), and refine the `(ref : Syntax)`. -/ class AddErrorMessageContext (m : Type → Type) where add : Syntax → MessageData → m (Syntax × MessageData) instance (m : Type → Type) [AddMessageContext m] [Monad m] : AddErrorMessageContext m where add ref msg := do let msg ← addMessageContext msg pure (ref, msg) class abbrev MonadError (m : Type → Type) := MonadExceptOf Exception m MonadRef m AddErrorMessageContext m section Methods /-- Throw an error exception using the given message data. The result of `getRef` is used as position information. Recall that `getRef` returns the current "reference" syntax. -/ protected def throwError [Monad m] [MonadError m] (msg : MessageData) : m α := do let ref ← getRef let (ref, msg) ← AddErrorMessageContext.add ref msg throw <| Exception.error ref msg /-- Thrown an unknown constant error message. -/ def throwUnknownConstant [Monad m] [MonadError m] (constName : Name) : m α := Lean.throwError m!"unknown constant '{mkConst constName}'" /-- Throw an error exception using the given message data and reference syntax. -/ protected def throwErrorAt [Monad m] [MonadError m] (ref : Syntax) (msg : MessageData) : m α := do withRef ref <| Lean.throwError msg /-- Convert an `Except` into a `m` monadic action, where `m` is any monad that implements `MonadError`. -/ def ofExcept [Monad m] [MonadError m] [ToString ε] (x : Except ε α) : m α := match x with | .ok a => return a | .error e => Lean.throwError <| toString e /-- Throw an error exception for the given kernel exception. -/ def throwKernelException [Monad m] [MonadError m] [MonadOptions m] (ex : KernelException) : m α := do Lean.throwError <| ex.toMessageData (← getOptions) end Methods class MonadRecDepth (m : Type → Type) where withRecDepth {α} : Nat → m α → m α getRecDepth : m Nat getMaxRecDepth : m Nat instance [Monad m] [MonadRecDepth m] : MonadRecDepth (ReaderT ρ m) where withRecDepth d x := fun ctx => MonadRecDepth.withRecDepth d (x ctx) getRecDepth := fun _ => MonadRecDepth.getRecDepth getMaxRecDepth := fun _ => MonadRecDepth.getMaxRecDepth instance [Monad m] [MonadRecDepth m] : MonadRecDepth (StateRefT' ω σ m) := inferInstanceAs (MonadRecDepth (ReaderT _ _)) instance [BEq α] [Hashable α] [Monad m] [STWorld ω m] [MonadRecDepth m] : MonadRecDepth (MonadCacheT α β m) := inferInstanceAs (MonadRecDepth (StateRefT' _ _ _)) /-- Throw a "maximum recursion depth has been reached" exception using the given reference syntax. -/ def throwMaxRecDepthAt [MonadError m] (ref : Syntax) : m α := throw <| .error ref (MessageData.ofFormat (Std.Format.text maxRecDepthErrorMessage)) /-- Return true if `ex` was generated by `throwMaxRecDepthAt`. This function is a bit hackish. The max rec depth exception should probably be an internal exception, but it is also produced by `MacroM` which implemented in the prelude, and internal exceptions have not been defined yet. -/ def Exception.isMaxRecDepth (ex : Exception) : Bool := match ex with | error _ (MessageData.ofFormat (Std.Format.text msg)) => msg == maxRecDepthErrorMessage | _ => false /-- Increment the current recursion depth and then execute `x`. Throw an exception if maximum recursion depth has been reached. We use this combinator to prevent stack overflows. -/ @[inline] def withIncRecDepth [Monad m] [MonadError m] [MonadRecDepth m] (x : m α) : m α := do let curr ← MonadRecDepth.getRecDepth let max ← MonadRecDepth.getMaxRecDepth if curr == max then throwMaxRecDepthAt (← getRef) else MonadRecDepth.withRecDepth (curr+1) x /-- Macro for throwing error exceptions. The argument can be an interpolated string. It is a convenient way of building `MessageData` objects. The result of `getRef` is used as position information. Recall that `getRef` returns the current "reference" syntax. -/ syntax "throwError " (interpolatedStr(term) <|> term) : term /-- Macro for throwing error exceptions. The argument can be an interpolated string. It is a convenient way of building `MessageData` objects. The first argument must be a `Syntax` that provides position information for the error message. `throwErrorAt ref msg` is equivalent to `withRef ref <| throwError msg` -/ syntax "throwErrorAt " term:max (interpolatedStr(term) <|> term) : term macro_rules | `(throwError $msg:interpolatedStr) => `(Lean.throwError (m! $msg)) | `(throwError $msg:term) => `(Lean.throwError $msg) macro_rules | `(throwErrorAt $ref $msg:interpolatedStr) => `(Lean.throwErrorAt $ref (m! $msg)) | `(throwErrorAt $ref $msg:term) => `(Lean.throwErrorAt $ref $msg) end Lean
59747f63bb6c325d09370b9d386a0bc1d8c758ec
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/hit/two_quotient.hlean
d3cda79fbe5f4aa8bfeca828f4059cbaa80d1bf4
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
31,448
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 -/ import homotopy.circle eq2 algebra.e_closure cubical.squareover cubical.cube cubical.square2 open quotient eq circle sum sigma equiv function relation e_closure /- This files defines a general class of nonrecursive 2-HITs using just quotients. We can define any HIT X which has - a single 0-constructor f : A → X (for some type A) - a single 1-constructor e : Π{a a' : A}, R a a' → a = a' (for some (type-valued) relation R on A) and furthermore has 2-constructors which are all of the form p = p' where p, p' are of the form - refl (f a), for some a : A; - e r, for some r : R a a'; - ap f q, where q : a = a' :> A; - inverses of such paths; - concatenations of such paths. so an example 2-constructor could be (as long as it typechecks): ap f q' ⬝ ((e r)⁻¹ ⬝ ap f q)⁻¹ ⬝ e r' = idp We first define "simple two quotients" which have as requirement that the right hand side is idp Then we define "two quotients" which can have an arbitrary path on the right hand side Then we define "truncated two quotients", which is a two quotient followed by n-truncation, and show that this satisfies the desired induction principle and computation rule. Caveat: for none of these constructions we show that the induction priniciple computes on 2-paths. However, with truncated two quotients, if the truncation is a 1-truncation, then this computation rule follows automatically, since the target is a 1-type. -/ namespace simple_two_quotient section parameters {A : Type} (R : A → A → Type) local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R parameter (Q : Π⦃a⦄, T a a → Type) variables ⦃a a' : A⦄ {s : R a a'} {r : T a a} local abbreviation B := A ⊎ Σ(a : A) (r : T a a), Q r inductive pre_two_quotient_rel : B → B → Type := | pre_Rmk {} : Π⦃a a'⦄ (r : R a a'), pre_two_quotient_rel (inl a) (inl a') --BUG: if {} not provided, the alias for pre_Rmk is wrong definition pre_two_quotient := quotient pre_two_quotient_rel open pre_two_quotient_rel local abbreviation C := quotient pre_two_quotient_rel protected definition j [constructor] (a : A) : C := class_of pre_two_quotient_rel (inl a) protected definition pre_aux [constructor] (q : Q r) : C := class_of pre_two_quotient_rel (inr ⟨a, r, q⟩) protected definition e (s : R a a') : j a = j a' := eq_of_rel _ (pre_Rmk s) protected definition et (t : T a a') : j a = j a' := e_closure.elim e t protected definition f [unfold 7] (q : Q r) : S¹ → C := circle.elim (j a) (et r) protected definition pre_rec [unfold 8] {P : C → Type} (Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') (x : C) : P x := begin induction x with p, { induction p, { apply Pj}, { induction a with a1 a2, induction a2, apply Pa}}, { induction H, esimp, apply Pe}, end protected definition pre_elim [unfold 8] {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') (x : C) : P := pre_rec Pj Pa (λa a' s, pathover_of_eq (Pe s)) x protected theorem rec_e {P : C → Type} (Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (s : R a a') : apd (pre_rec Pj Pa Pe) (e s) = Pe s := !rec_eq_of_rel protected theorem elim_e {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (s : R a a') : ap (pre_elim Pj Pa Pe) (e s) = Pe s := begin apply eq_of_fn_eq_fn_inv !(pathover_constant (e s)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑pre_elim,rec_e], end protected definition elim_et {P : Type} (Pj : A → P) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄, Q r → P) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a = Pj a') ⦃a a' : A⦄ (t : T a a') : ap (pre_elim Pj Pa Pe) (et t) = e_closure.elim Pe t := ap_e_closure_elim_h e (elim_e Pj Pa Pe) t protected definition rec_et {P : C → Type} (Pj : Πa, P (j a)) (Pa : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), P (pre_aux q)) (Pe : Π⦃a a' : A⦄ (s : R a a'), Pj a =[e s] Pj a') ⦃a a' : A⦄ (t : T a a') : apd (pre_rec Pj Pa Pe) (et t) = e_closure.elimo e Pe t := ap_e_closure_elimo_h e Pe (rec_e Pj Pa Pe) t inductive simple_two_quotient_rel : C → C → Type := | Rmk {} : Π{a : A} {r : T a a} (q : Q r) (x : circle), simple_two_quotient_rel (f q x) (pre_aux q) open simple_two_quotient_rel definition simple_two_quotient := quotient simple_two_quotient_rel local abbreviation D := simple_two_quotient local abbreviation i := class_of simple_two_quotient_rel definition incl0 (a : A) : D := i (j a) protected definition aux (q : Q r) : D := i (pre_aux q) definition incl1 (s : R a a') : incl0 a = incl0 a' := ap i (e s) definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t -- "wrong" version inclt, which is ap i (p ⬝ q) instead of ap i p ⬝ ap i q -- it is used in the proof, because incltw is easier to work with protected definition incltw (t : T a a') : incl0 a = incl0 a' := ap i (et t) protected definition inclt_eq_incltw (t : T a a') : inclt t = incltw t := (ap_e_closure_elim i e t)⁻¹ definition incl2' (q : Q r) (x : S¹) : i (f q x) = aux q := eq_of_rel simple_two_quotient_rel (Rmk q x) protected definition incl2w (q : Q r) : incltw r = idp := (ap02 i (elim_loop (j a) (et r))⁻¹) ⬝ (ap_compose i (f q) loop)⁻¹ ⬝ ap_is_constant (incl2' q) loop ⬝ !con.right_inv definition incl2 (q : Q r) : inclt r = idp := inclt_eq_incltw r ⬝ incl2w q local attribute simple_two_quotient f i D incl0 aux incl1 incl2' inclt [reducible] local attribute i aux incl0 [constructor] parameters {R Q} protected definition rec {P : D → Type} (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) (x : D) : P x := begin induction x, { refine (pre_rec _ _ _ a), { exact P0}, { intro a r q, exact incl2' q base ▸ P0 a}, { intro a a' s, exact pathover_of_pathover_ap P i (P1 s)}}, { exact abstract [irreducible] begin induction H, induction x, { esimp, exact pathover_tr (incl2' q base) (P0 a)}, { apply pathover_pathover, esimp, fold [i, incl2' q], refine eq_hconcato _ _, apply _, { transitivity _, { apply ap (pathover_ap _ _), transitivity _, apply apd_compose2 (pre_rec P0 _ _) (f q) loop, apply ap (pathover_of_pathover_ap _ _), transitivity _, apply apd_change_path, exact !elim_loop⁻¹, transitivity _, apply ap (change_path _), transitivity _, apply rec_et, transitivity (pathover_of_pathover_ap P i (change_path (inclt_eq_incltw r) (e_closure.elimo incl1 (λ (a a' : A) (s : R a a'), P1 s) r))), apply e_closure_elimo_ap, exact idp, apply change_path_pathover_of_pathover_ap}, esimp, transitivity _, apply pathover_ap_pathover_of_pathover_ap P i (f q), transitivity _, apply ap (change_path _), apply to_right_inv !pathover_compose, do 2 (transitivity _; exact !change_path_con⁻¹), transitivity _, apply ap (change_path _), exact (to_left_inv (change_path_equiv _ _ (incl2 q)) _)⁻¹, esimp, rewrite P2, transitivity _; exact !change_path_con⁻¹, apply ap (λx, change_path x _), rewrite [↑incl2, con_inv], transitivity _, exact !con.assoc⁻¹, rewrite [inv_con_cancel_right, ↑incl2w, ↑ap02, +con_inv, +ap_inv, +inv_inv, -+con.assoc, +con_inv_cancel_right], reflexivity}, rewrite [change_path_con, apd_constant], apply squareover_change_path_left, apply squareover_change_path_right', apply squareover_change_path_left, refine change_square _ vrflo, symmetry, apply inv_ph_eq_of_eq_ph, rewrite [ap_is_constant_natural_square], apply whisker_bl_whisker_tl_eq} end end}, end protected definition rec_on [reducible] {P : D → Type} (x : D) (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) : P x := rec P0 P1 P2 x theorem rec_incl1 {P : D → Type} (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) ⦃a a' : A⦄ (s : R a a') : apd (rec P0 P1 P2) (incl1 s) = P1 s := begin unfold [rec, incl1], refine !apd_ap ⬝ _, esimp, rewrite rec_e, apply to_right_inv !pathover_compose end theorem rec_inclt {P : D → Type} (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), change_path (incl2 q) (e_closure.elimo incl1 P1 r) = idpo) ⦃a a' : A⦄ (t : T a a') : apd (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t := ap_e_closure_elimo_h incl1 P1 (rec_incl1 P0 P1 P2) t protected definition elim {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) (x : D) : P := begin induction x, { refine (pre_elim _ _ _ a), { exact P0}, { intro a r q, exact P0 a}, { exact P1}}, { exact abstract begin induction H, induction x, { exact idpath (P0 a)}, { unfold f, apply eq_pathover, apply hdeg_square, exact abstract ap_compose (pre_elim P0 _ P1) (f q) loop ⬝ ap _ !elim_loop ⬝ !elim_et ⬝ P2 q ⬝ !ap_constant⁻¹ end} end end}, end local attribute elim [unfold 8] protected definition elim_on {P : Type} (x : D) (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) : P := elim P0 P1 P2 x definition elim_incl1 {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s := (ap_compose (elim P0 P1 P2) i (e s))⁻¹ ⬝ !elim_e definition elim_inclt {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t := ap_e_closure_elim_h incl1 (elim_incl1 P2) t protected definition elim_incltw {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (incltw t) = e_closure.elim P1 t := (ap_compose (elim P0 P1 P2) i (et t))⁻¹ ⬝ !elim_et protected theorem elim_inclt_eq_elim_incltw {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a a' : A⦄ (t : T a a') : elim_inclt P2 t = ap (ap (elim P0 P1 P2)) (inclt_eq_incltw t) ⬝ elim_incltw P2 t := begin unfold [elim_inclt,elim_incltw,inclt_eq_incltw,et], refine !ap_e_closure_elim_h_eq ⬝ _, rewrite [ap_inv,-con.assoc], xrewrite [eq_of_square (ap_ap_e_closure_elim i (elim P0 P1 P2) e t)⁻¹ʰ], rewrite [↓incl1,con.assoc], apply whisker_left, rewrite [↑[elim_et,elim_incl1],+ap_e_closure_elim_h_eq,con_inv,↑[i,function.compose]], rewrite [-con.assoc (_ ⬝ _),con.assoc _⁻¹,con.left_inv,▸*,-ap_inv,-ap_con], apply ap (ap _), krewrite [-eq_of_homotopy3_inv,-eq_of_homotopy3_con] end definition elim_incl2' {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : ap (elim P0 P1 P2) (incl2' q base) = idpath (P0 a) := !elim_eq_of_rel protected theorem elim_incl2w {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : square (ap02 (elim P0 P1 P2) (incl2w q)) (P2 q) (elim_incltw P2 r) idp := begin esimp [incl2w,ap02], rewrite [+ap_con (ap _),▸*], xrewrite [-ap_compose (ap _) (ap i)], rewrite [+ap_inv], xrewrite [eq_top_of_square ((ap_compose_natural (elim P0 P1 P2) i (elim_loop (j a) (et r)))⁻¹ʰ⁻¹ᵛ ⬝h (ap_ap_compose (elim P0 P1 P2) i (f q) loop)⁻¹ʰ⁻¹ᵛ ⬝h ap_ap_is_constant (elim P0 P1 P2) (incl2' q) loop ⬝h ap_con_right_inv_sq (elim P0 P1 P2) (incl2' q base)), ↑[elim_incltw]], apply whisker_tl, rewrite [ap_is_constant_eq], xrewrite [naturality_apd_eq (λx, !elim_eq_of_rel) loop], rewrite [↑elim_2,rec_loop,square_of_pathover_concato_eq,square_of_pathover_eq_concato, eq_of_square_vconcat_eq,eq_of_square_eq_vconcat], apply eq_vconcat, { apply ap (λx, _ ⬝ eq_con_inv_of_con_eq ((_ ⬝ x ⬝ _)⁻¹ ⬝ _) ⬝ _), transitivity _, apply ap eq_of_square, apply to_right_inv !eq_pathover_equiv_square (hdeg_square (elim_1 P A R Q P0 P1 a r q P2)), transitivity _, apply eq_of_square_hdeg_square, unfold elim_1, reflexivity}, rewrite [+con_inv,whisker_left_inv,+inv_inv,-whisker_right_inv, con.assoc (whisker_left _ _),con.assoc _ (whisker_right _ _),▸*, whisker_right_con_whisker_left _ !ap_constant], xrewrite [-con.assoc _ _ (whisker_right _ _)], rewrite [con.assoc _ _ (whisker_left _ _),idp_con_whisker_left,▸*, con.assoc _ !ap_constant⁻¹,con.left_inv], xrewrite [eq_con_inv_of_con_eq_whisker_left,▸*], rewrite [+con.assoc _ _ !con.right_inv, right_inv_eq_idp ( (λ(x : ap (elim P0 P1 P2) (incl2' q base) = idpath (elim P0 P1 P2 (class_of simple_two_quotient_rel (f q base)))), x) (elim_incl2' P2 q)), ↑[whisker_left]], xrewrite [con2_con_con2], rewrite [idp_con,↑elim_incl2',con.left_inv,whisker_right_inv,↑whisker_right], xrewrite [con.assoc _ _ (_ ◾ _)], rewrite [con.left_inv,▸*,-+con.assoc,con.assoc _⁻¹,↑[elim,function.compose],con.left_inv, ▸*,↑j,con.left_inv,idp_con], apply square_of_eq, reflexivity end theorem elim_incl2 {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a : A⦄ ⦃r : T a a⦄ (q : Q r), e_closure.elim P1 r = idp) ⦃a : A⦄ ⦃r : T a a⦄ (q : Q r) : square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 r) idp := begin rewrite [↑incl2,↑ap02,ap_con,elim_inclt_eq_elim_incltw], apply whisker_tl, apply elim_incl2w end end end simple_two_quotient export [unfold] simple_two_quotient attribute simple_two_quotient.j simple_two_quotient.incl0 [constructor] attribute simple_two_quotient.rec simple_two_quotient.elim [unfold 8] [recursor 8] --attribute simple_two_quotient.elim_type [unfold 9] -- TODO attribute simple_two_quotient.rec_on simple_two_quotient.elim_on [unfold 5] --attribute simple_two_quotient.elim_type_on [unfold 6] -- TODO namespace two_quotient open simple_two_quotient section parameters {A : Type} (R : A → A → Type) local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R parameter (Q : Π⦃a a'⦄, T a a' → T a a' → Type) variables ⦃a a' a'' : A⦄ {s : R a a'} {t t' : T a a'} inductive two_quotient_Q : Π⦃a : A⦄, e_closure R a a → Type := | Qmk : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄, Q t t' → two_quotient_Q (t ⬝r t'⁻¹ʳ) open two_quotient_Q local abbreviation Q2 := two_quotient_Q definition two_quotient := simple_two_quotient R Q2 definition incl0 (a : A) : two_quotient := incl0 _ _ a definition incl1 (s : R a a') : incl0 a = incl0 a' := incl1 _ _ s definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t definition incl2 (q : Q t t') : inclt t = inclt t' := eq_of_con_inv_eq_idp (incl2 _ _ (Qmk R q)) parameters {R Q} protected definition rec {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') (x : two_quotient) : P x := begin induction x, { exact P0 a}, { exact P1 s}, { exact abstract [irreducible] begin induction q with a a' t t' q, rewrite [elimo_trans (simple_two_quotient.incl1 R Q2) P1, elimo_symm (simple_two_quotient.incl1 R Q2) P1, -whisker_right_eq_of_con_inv_eq_idp (simple_two_quotient.incl2 R Q2 (Qmk R q)), change_path_con], xrewrite [change_path_cono], refine ap (λx, change_path _ (_ ⬝o x)) !change_path_invo ⬝ _, esimp, apply cono_invo_eq_idpo, apply P2 end end} end protected definition rec_on [reducible] {P : two_quotient → Type} (x : two_quotient) (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') : P x := rec P0 P1 P2 x theorem rec_incl1 {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') ⦃a a' : A⦄ (s : R a a') : apd (rec P0 P1 P2) (incl1 s) = P1 s := rec_incl1 _ _ _ s theorem rec_inclt {P : two_quotient → Type} (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') ⦃a a' : A⦄ (t : T a a') : apd (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t := rec_inclt _ _ _ t protected definition elim {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') (x : two_quotient) : P := begin induction x, { exact P0 a}, { exact P1 s}, { exact abstract [unfold 10] begin induction q with a a' t t' q, esimp [e_closure.elim], apply con_inv_eq_idp, exact P2 q end end}, end local attribute elim [unfold 8] protected definition elim_on {P : Type} (x : two_quotient) (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') : P := elim P0 P1 P2 x definition elim_incl1 {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s := !elim_incl1 definition elim_inclt {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t := ap_e_closure_elim_h incl1 (elim_incl1 P2) t theorem elim_incl2 {P : Type} (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t') : square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 t) (elim_inclt P2 t') := begin rewrite [↑[incl2,elim],ap_eq_of_con_inv_eq_idp], xrewrite [eq_top_of_square (elim_incl2 P0 P1 (elim_1 A R Q P P0 P1 P2) (Qmk R q))], xrewrite [{simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) (t ⬝r t'⁻¹ʳ)} idpath (ap_con (simple_two_quotient.elim P0 P1 (elim_1 A R Q P P0 P1 P2)) (inclt t) (inclt t')⁻¹ ⬝ (simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) t ◾ (ap_inv (simple_two_quotient.elim P0 P1 (elim_1 A R Q P P0 P1 P2)) (inclt t') ⬝ inverse2 (simple_two_quotient.elim_inclt (elim_1 A R Q P P0 P1 P2) t')))),▸*], rewrite [-con.assoc _ _ (con_inv_eq_idp _),-con.assoc _ _ (_ ◾ _),con.assoc _ _ (ap_con _ _ _), con.left_inv,↑whisker_left,con2_con_con2,-con.assoc (ap_inv _ _)⁻¹, con.left_inv,+idp_con,eq_of_con_inv_eq_idp_con2], xrewrite [to_left_inv !eq_equiv_con_inv_eq_idp (P2 q)], apply top_deg_square end definition elim_inclt_rel [unfold_full] {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (r : R a a') : elim_inclt P2 [r] = elim_incl1 P2 r := idp definition elim_inclt_inv [unfold_full] {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (t : T a a') : elim_inclt P2 t⁻¹ʳ = ap_inv (elim P0 P1 P2) (inclt t) ⬝ (elim_inclt P2 t)⁻² := idp definition elim_inclt_con [unfold_full] {P : Type} {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' a'' : A⦄ (t : T a a') (t': T a' a'') : elim_inclt P2 (t ⬝r t') = ap_con (elim P0 P1 P2) (inclt t) (inclt t') ⬝ (elim_inclt P2 t ◾ elim_inclt P2 t') := idp definition inclt_rel [unfold_full] (r : R a a') : inclt [r] = incl1 r := idp definition inclt_inv [unfold_full] (t : T a a') : inclt t⁻¹ʳ = (inclt t)⁻¹ := idp definition inclt_con [unfold_full] (t : T a a') (t' : T a' a'') : inclt (t ⬝r t') = inclt t ⬝ inclt t' := idp end end two_quotient attribute two_quotient.incl0 [constructor] attribute two_quotient.rec two_quotient.elim [unfold 8] [recursor 8] --attribute two_quotient.elim_type [unfold 9] attribute two_quotient.rec_on two_quotient.elim_on [unfold 5] --attribute two_quotient.elim_type_on [unfold 6] open two_quotient is_trunc trunc namespace trunc_two_quotient section parameters (n : ℕ₋₂) {A : Type} (R : A → A → Type) local abbreviation T := e_closure R -- the (type-valued) equivalence closure of R parameter (Q : Π⦃a a'⦄, T a a' → T a a' → Type) variables ⦃a a' a'' : A⦄ {s : R a a'} {t t' : T a a'} definition trunc_two_quotient := trunc n (two_quotient R Q) parameters {n R Q} definition incl0 (a : A) : trunc_two_quotient := tr (!incl0 a) definition incl1 (s : R a a') : incl0 a = incl0 a' := ap tr (!incl1 s) definition incltw (t : T a a') : incl0 a = incl0 a' := ap tr (!inclt t) definition inclt (t : T a a') : incl0 a = incl0 a' := e_closure.elim incl1 t definition incl2w (q : Q t t') : incltw t = incltw t' := ap02 tr (!incl2 q) definition incl2 (q : Q t t') : inclt t = inclt t' := !ap_e_closure_elim⁻¹ ⬝ ap02 tr (!incl2 q) ⬝ !ap_e_closure_elim local attribute trunc_two_quotient incl0 [reducible] definition is_trunc_trunc_two_quotient [instance] : is_trunc n trunc_two_quotient := _ protected definition rec {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)] (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') (x : trunc_two_quotient) : P x := begin induction x, induction a, { exact P0 a}, { exact !pathover_of_pathover_ap (P1 s)}, { exact abstract [irreducible] by rewrite [+ e_closure_elimo_ap, ↓incl1, -P2 q, change_path_pathover_of_pathover_ap, - + change_path_con, ↑incl2, con_inv_cancel_right] end} end protected definition rec_on [reducible] {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)] (x : trunc_two_quotient) (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') : P x := rec P0 P1 P2 x theorem rec_incl1 {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)] (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') ⦃a a' : A⦄ (s : R a a') : apd (rec P0 P1 P2) (incl1 s) = P1 s := !apd_ap ⬝ ap !pathover_ap !rec_incl1 ⬝ to_right_inv !pathover_compose (P1 s) theorem rec_inclt {P : trunc_two_quotient → Type} [H : Πx, is_trunc n (P x)] (P0 : Π(a : A), P (incl0 a)) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a =[incl1 s] P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), change_path (incl2 q) (e_closure.elimo incl1 P1 t) = e_closure.elimo incl1 P1 t') ⦃a a' : A⦄ (t : T a a') : apd (rec P0 P1 P2) (inclt t) = e_closure.elimo incl1 P1 t := ap_e_closure_elimo_h incl1 P1 (rec_incl1 P0 P1 P2) t protected definition elim {P : Type} (P0 : A → P) [H : is_trunc n P] (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') (x : trunc_two_quotient) : P := begin induction x, induction a, { exact P0 a}, { exact P1 s}, { exact P2 q}, end local attribute elim [unfold 10] protected definition elim_on {P : Type} [H : is_trunc n P] (x : trunc_two_quotient) (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') : P := elim P0 P1 P2 x definition elim_incl1 {P : Type} [H : is_trunc n P] {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (s : R a a') : ap (elim P0 P1 P2) (incl1 s) = P1 s := !ap_compose⁻¹ ⬝ !elim_incl1 definition elim_inclt {P : Type} [H : is_trunc n P] {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (t : T a a') : ap (elim P0 P1 P2) (inclt t) = e_closure.elim P1 t := ap_e_closure_elim_h incl1 (elim_incl1 P2) t open function theorem elim_incl2 {P : Type} [H : is_trunc n P] (P0 : A → P) (P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a') (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t') : square (ap02 (elim P0 P1 P2) (incl2 q)) (P2 q) (elim_inclt P2 t) (elim_inclt P2 t') := begin note Ht' := ap_ap_e_closure_elim tr (elim P0 P1 P2) (two_quotient.incl1 R Q) t', note Ht := ap_ap_e_closure_elim tr (elim P0 P1 P2) (two_quotient.incl1 R Q) t, note Hn := natural_square (ap_compose (elim P0 P1 P2) tr) (two_quotient.incl2 R Q q), note H7 := eq_top_of_square (Ht⁻¹ʰ ⬝h Hn⁻¹ᵛ ⬝h Ht'), clear [Hn, Ht, Ht'], unfold [ap02,incl2], rewrite [+ap_con,ap_inv,-ap_compose (ap _)], xrewrite [H7, ↑function.compose, eq_top_of_square (elim_incl2 P0 P1 P2 q)], clear [H7], have H : Π(t : T a a'), ap_e_closure_elim (elim P0 P1 P2) (λa a' (r : R a a'), ap tr (two_quotient.incl1 R Q r)) t ⬝ (ap_e_closure_elim_h (two_quotient.incl1 R Q) (λa a' (s : R a a'), ap_compose (elim P0 P1 P2) tr (two_quotient.incl1 R Q s)) t)⁻¹ ⬝ two_quotient.elim_inclt P2 t = elim_inclt P2 t, from ap_e_closure_elim_h_zigzag (elim P0 P1 P2) (two_quotient.incl1 R Q) (two_quotient.elim_incl1 P2), rewrite [con.assoc5, con.assoc5, H t, -inv_con_inv_right, -con_inv], xrewrite [H t'], apply top_deg_square end definition elim_inclt_rel [unfold_full] {P : Type} [is_trunc n P] {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (r : R a a') : elim_inclt P2 [r] = elim_incl1 P2 r := idp definition elim_inclt_inv [unfold_full] {P : Type} [is_trunc n P] {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' : A⦄ (t : T a a') : elim_inclt P2 t⁻¹ʳ = ap_inv (elim P0 P1 P2) (inclt t) ⬝ (elim_inclt P2 t)⁻² := idp definition elim_inclt_con [unfold_full] {P : Type} [is_trunc n P] {P0 : A → P} {P1 : Π⦃a a' : A⦄ (s : R a a'), P0 a = P0 a'} (P2 : Π⦃a a' : A⦄ ⦃t t' : T a a'⦄ (q : Q t t'), e_closure.elim P1 t = e_closure.elim P1 t') ⦃a a' a'' : A⦄ (t : T a a') (t': T a' a'') : elim_inclt P2 (t ⬝r t') = ap_con (elim P0 P1 P2) (inclt t) (inclt t') ⬝ (elim_inclt P2 t ◾ elim_inclt P2 t') := idp definition inclt_rel [unfold_full] (r : R a a') : inclt [r] = incl1 r := idp definition inclt_inv [unfold_full] (t : T a a') : inclt t⁻¹ʳ = (inclt t)⁻¹ := idp definition inclt_con [unfold_full] (t : T a a') (t' : T a' a'') : inclt (t ⬝r t') = inclt t ⬝ inclt t' := idp end end trunc_two_quotient attribute trunc_two_quotient.incl0 [constructor] attribute trunc_two_quotient.rec trunc_two_quotient.elim [unfold 10] [recursor 10] attribute trunc_two_quotient.rec_on trunc_two_quotient.elim_on [unfold 7]
48387bb2e6b7b390f20bf7e4602b1d8cbe4643b8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/pretty_cases.lean
de91383575a453f6305c48ba92de9a0e62fe0c22
[ "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,827
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 tactic.core /-! # `pretty_cases` tactic When using `induction` and `cases`, `pretty_cases` prints a `"Try this:"` advice that shows how to structure the proof with `case { ... }` commands. In the following example, we apply induction on a permutation assumption about lists. `pretty_cases` gives us a proof skeleton that explicit selects the branches and explicit names the new local constants: ```lean example {α} (xs ys : list α) (h : xs ~ ys) : true := begin induction h, pretty_cases, -- Try this: -- case list.perm.nil : -- { admit }, -- case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih -- { admit }, -- case list.perm.swap : h_x h_y h_l -- { admit }, -- case list.perm.trans : h_l₁ h_l₂ h_l₃ h_a h_a_1 h_ih_a h_ih_a_1 -- { admit }, end ``` ## Main definitions * `pretty_cases_advice` return `pretty_cases` advice without printing it * `pretty_cases` main tactic -/ namespace tactic /-- Query the proof goal and print the skeleton of a proof by cases. -/ meta def pretty_cases_advice : tactic string := retrieve $ do gs ← get_goals, cases ← gs.mmap $ λ g, do { t : list name ← get_tag g, let vs := t.tail, let ⟨vs,ts⟩ := vs.span (λ n, name.last_string n = "_arg"), set_goals [g], ls ← local_context, let m := native.rb_map.of_list $ (ls.map expr.local_uniq_name).zip (ls.map expr.local_pp_name), let vs := vs.map $ λ v, (m.find v.get_prefix).get_or_else `_, let var_decls := string.intercalate " " $ vs.map to_string, let var_decls := if vs.empty then "" else " : " ++ var_decls, pure sformat!" case {ts.head}{var_decls}\n {{ admit }}" }, let cases := string.intercalate ",\n" cases, pure sformat!"Try this:\n{cases}" namespace interactive /-- Query the proof goal and print the skeleton of a proof by cases. For example, let us consider the following proof: ```lean example {α} (xs ys : list α) (h : xs ~ ys) : true := begin induction h, pretty_cases, -- Try this: -- case list.perm.nil : -- { admit }, -- case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih -- { admit }, -- case list.perm.swap : h_x h_y h_l -- { admit }, -- case list.perm.trans : h_l₁ h_l₂ h_l₃ h_a h_a_1 h_ih_a h_ih_a_1 -- { admit }, end ``` The output helps the user layout the cases and rename the introduced variables. -/ meta def pretty_cases : tactic unit := pretty_cases_advice >>= trace add_tactic_doc { name := "pretty_cases", category := doc_category.tactic, decl_names := [``tactic.interactive.pretty_cases], tags := ["context management", "goal management"] } end interactive end tactic
ab25d3c7f70bc4f19000d68700f043ee6b96e8be
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/category_theory/types.lean
55111d77ace5db6c49f768aa197de3a02d98176b
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
5,324
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl import category_theory.functor_category import category_theory.fully_faithful import data.equiv.basic namespace category_theory universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation instance types : large_category (Sort u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } @[simp] lemma types_hom {α β : Sort u} : (α ⟶ β) = (α → β) := rfl @[simp] lemma types_id (X : Sort u) : 𝟙 X = id := rfl @[simp] lemma types_comp {X Y Z : Sort u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl namespace functor variables {J : Type u} [𝒥 : category.{v} J] include 𝒥 def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [𝒞 : category.{v} C] (F G H : C ⥤ Sort w) {X Y Z : C} include 𝒞 variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp @[simp] lemma map_id (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl end functor_to_types def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { injectivity' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { refine λ H, ⟨λ Z g h H₂, _⟩, ext z, replace H₂ := congr_fun H₂ z, exact H H₂ } end lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { intros H, let g : Y ⟶ ulift Prop := λ y, ⟨true⟩, let h : Y ⟶ ulift Prop := λ y, ⟨∃ x, f x = y⟩, suffices : f ≫ g = f ≫ h, { resetI, rw cancel_epi at this, intro y, replace this := congr_fun this y, replace this : true = ∃ x, f x = y := congr_arg ulift.down this, rw ←this, trivial }, ext x, change true ↔ ∃ x', f x' = f x, rw true_iff, exact ⟨x, rfl⟩ }, { intro H, constructor, intros Z g h H₂, apply funext, rw ←forall_iff_forall_surj H, intro x, exact (congr_fun H₂ x : _) } end section /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] : Type u ⥤ Type v := { obj := m, map := λα β, _root_.functor.map, map_id' := assume α, _root_.functor.map_id, map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ } variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] @[simp] lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl @[simp] lemma of_type_functor_map {α β} (f : α → β) : (of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Sort u} def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv namespace category_theory.iso universe u variables {X Y : Sort u} def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl end category_theory.iso
759cb7d75b8fd699956535b557f8fe5cd0e7dd78
4727251e0cd73359b15b664c3170e5d754078599
/src/data/finset/finsupp.lean
bdff527eeafe475776eb7a17fc55f843a44a1ecc
[ "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,195
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.pointwise import data.finsupp.indicator import data.fintype.card /-! # Finitely supported product of finsets This file defines the finitely supported product of finsets as a `finset (ι →₀ α)`. ## Main declarations * `finset.finsupp`: Finitely supported product of finsets. `s.finset t` is the product of the `t i` over all `i ∈ s`. * `finsupp.pi`: `f.pi` is the finset of `finsupp`s whose `i`-th value lies in `f i`. This is the special case of `finset.finsupp` where we take the product of the `f i` over the support of `f`. ## Implementation notes We make heavy use of the fact that `0 : finset α` is `{0}`. This scalar actions convention turns out to be precisely what we want here too. -/ noncomputable theory open finsupp open_locale big_operators classical pointwise variables {ι α : Type*} [has_zero α] {s : finset ι} {f : ι →₀ α} namespace finset /-- Finitely supported product of finsets. -/ protected def finsupp (s : finset ι) (t : ι → finset α) : finset (ι →₀ α) := (s.pi t).map ⟨indicator s, indicator_injective s⟩ lemma mem_finsupp_iff {t : ι → finset α} : f ∈ s.finsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := begin refine mem_map.trans ⟨_, _⟩, { rintro ⟨f, hf, rfl⟩, refine ⟨support_indicator_subset _ _, λ i hi, _⟩, convert mem_pi.1 hf i hi, exact indicator_of_mem hi _ }, { refine λ h, ⟨λ i _, f i, mem_pi.2 h.2, _⟩, ext i, exact ite_eq_left_iff.2 (λ hi, (not_mem_support_iff.1 $ λ H, hi $ h.1 H).symm) } end /-- When `t` is supported on `s`, `f ∈ s.finsupp t` precisely means that `f` is pointwise in `t`. -/ @[simp] lemma mem_finsupp_iff_of_support_subset {t : ι →₀ finset α} (ht : t.support ⊆ s) : f ∈ s.finsupp t ↔ ∀ i, f i ∈ t i := begin refine mem_finsupp_iff.trans (forall_and_distrib.symm.trans $ forall_congr $ λ i, ⟨λ h, _, λ h, ⟨λ hi, ht $ mem_support_iff.2 $ λ H, mem_support_iff.1 hi _, λ _, h⟩⟩), { by_cases hi : i ∈ s, { exact h.2 hi }, { rw [not_mem_support_iff.1 (mt h.1 hi), not_mem_support_iff.1 (λ H, hi $ ht H)], exact zero_mem_zero } }, { rwa [H, mem_zero] at h } end @[simp] lemma card_finsupp (s : finset ι) (t : ι → finset α) : (s.finsupp t).card = ∏ i in s, (t i).card := (card_map _).trans $ card_pi _ _ end finset open finset namespace finsupp /-- Given a finitely supported function `f : ι →₀ finset α`, one can define the finset `f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/ def pi (f : ι →₀ finset α) : finset (ι →₀ α) := f.support.finsupp f @[simp] lemma mem_pi {f : ι →₀ finset α} {g : ι →₀ α} : g ∈ f.pi ↔ ∀ i, g i ∈ f i := mem_finsupp_iff_of_support_subset $ subset.refl _ @[simp] lemma card_pi (f : ι →₀ finset α) : f.pi.card = f.prod (λ i, (f i).card) := begin rw [pi, card_finsupp], exact finset.prod_congr rfl (λ i _, by simp only [pi.nat_apply, nat.cast_id]), end end finsupp
2f3677e30820d77717a5ea62e98def06f8b97222
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/default.lean
4ea5942916608594549d5f1a506d66a60bcdf50b
[ "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
613
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.core init.logic init.control init.data.basic init.version import init.propext init.cc_lemmas init.funext init.control.combinators init.function init.classical import init.util init.coe init.wf init.meta init.meta.well_founded_tactics init.algebra init.data import init.meta.float import init.meta.widget @[user_attribute] meta def debugger.attr : user_attribute := { name := `breakpoint, descr := "breakpoint for debugger" }
04532b9b9ec508445ae89a9471a799650f35f3f3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/quadratic_form_auto.lean
eed99e3d4325f9d8c48f2f6e789d7f7032af3bd5
[]
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
25,720
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.invertible import Mathlib.linear_algebra.bilinear_form import Mathlib.linear_algebra.determinant import Mathlib.linear_algebra.special_linear_group import Mathlib.PostPort universes u v l u_1 w u_2 u_3 namespace Mathlib /-! # Quadratic forms This file defines quadratic forms over a `R`-module `M`. A quadratic form is a map `Q : M → R` such that (`to_fun_smul`) `Q (a • x) = a * a * Q x` (`polar_...`) The map `polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. They come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.anisotropic`: anisotropic quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ namespace quadratic_form /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`.d Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def polar {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (x : M) (y : M) : R := f (x + y) - f x - f y theorem polar_add {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (g : M → R) (x : M) (y : M) : polar (f + g) x y = polar f x y + polar g x y := sorry theorem polar_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (x : M) (y : M) : polar (-f) x y = -polar f x y := sorry theorem polar_smul {R : Type u} {M : Type v} [add_comm_group M] [ring R] (f : M → R) (s : R) (x : M) (y : M) : polar (s • f) x y = s * polar f x y := sorry theorem polar_comm {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] (f : M → R₁) (x : M) (y : M) : polar f x y = polar f y x := sorry end quadratic_form /-- A quadratic form over a module. -/ structure quadratic_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] extends quadratic_form.to_fun #1 #0 R M _inst_6 _inst_7 (_inst_8 • to_fun) = _inst_8 * _inst_8 * quadratic_form.to_fun #1 #0 R M _inst_6 _inst_7 to_fun where to_fun : M → R to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x polar_add_left' : ∀ (x x' y : M), quadratic_form.polar to_fun (x + x') y = quadratic_form.polar to_fun x y + quadratic_form.polar to_fun x' y polar_smul_left' : ∀ (a : R) (x y : M), quadratic_form.polar to_fun (a • x) y = a • quadratic_form.polar to_fun x y polar_add_right' : ∀ (x y y' : M), quadratic_form.polar to_fun x (y + y') = quadratic_form.polar to_fun x y + quadratic_form.polar to_fun x y' polar_smul_right' : ∀ (a : R) (x y : M), quadratic_form.polar to_fun x (a • y) = a • quadratic_form.polar to_fun x y namespace quadratic_form protected instance has_coe_to_fun {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : has_coe_to_fun (quadratic_form R M) := has_coe_to_fun.mk (fun (B : quadratic_form R M) => M → R) fun (B : quadratic_form R M) => to_fun B /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] theorem to_fun_eq_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} : to_fun Q = ⇑Q := rfl @[simp] theorem polar_add_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (x' : M) (y : M) : polar (⇑Q) (x + x') y = polar (⇑Q) x y + polar (⇑Q) x' y := polar_add_left' Q x x' y @[simp] theorem polar_smul_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (a : R) (x : M) (y : M) : polar (⇑Q) (a • x) y = a * polar (⇑Q) x y := polar_smul_left' Q a x y @[simp] theorem polar_neg_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) : polar (⇑Q) (-x) y = -polar (⇑Q) x y := sorry @[simp] theorem polar_sub_left {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (x' : M) (y : M) : polar (⇑Q) (x - x') y = polar (⇑Q) x y - polar (⇑Q) x' y := sorry @[simp] theorem polar_add_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) (y' : M) : polar (⇑Q) x (y + y') = polar (⇑Q) x y + polar (⇑Q) x y' := polar_add_right' Q x y y' @[simp] theorem polar_smul_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (a : R) (x : M) (y : M) : polar (⇑Q) x (a • y) = a * polar (⇑Q) x y := polar_smul_right' Q a x y @[simp] theorem polar_neg_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) : polar (⇑Q) x (-y) = -polar (⇑Q) x y := sorry @[simp] theorem polar_sub_right {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) (y' : M) : polar (⇑Q) x (y - y') = polar (⇑Q) x y - polar (⇑Q) x y' := sorry theorem map_smul {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (a : R) (x : M) : coe_fn Q (a • x) = a * a * coe_fn Q x := to_fun_smul Q a x theorem map_add_self {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) : coe_fn Q (x + x) = bit0 (bit0 1) * coe_fn Q x := sorry @[simp] theorem map_zero {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} : coe_fn Q 0 = 0 := sorry @[simp] theorem map_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) : coe_fn Q (-x) = coe_fn Q x := sorry theorem map_sub {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} (x : M) (y : M) : coe_fn Q (x - y) = coe_fn Q (y - x) := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn Q (x - y) = coe_fn Q (y - x))) (Eq.symm (neg_sub y x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn Q (-(y - x)) = coe_fn Q (y - x))) (map_neg (y - x)))) (Eq.refl (coe_fn Q (y - x)))) theorem ext {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {Q : quadratic_form R M} {Q' : quadratic_form R M} (H : ∀ (x : M), coe_fn Q x = coe_fn Q' x) : Q = Q' := sorry protected instance has_zero {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : HasZero (quadratic_form R M) := { zero := mk (fun (x : M) => 0) sorry sorry sorry sorry sorry } @[simp] theorem zero_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (x : M) : coe_fn 0 x = 0 := rfl protected instance inhabited {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : Inhabited (quadratic_form R M) := { default := 0 } protected instance has_add {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : Add (quadratic_form R M) := { add := fun (Q Q' : quadratic_form R M) => mk (⇑Q + ⇑Q') sorry sorry sorry sorry sorry } @[simp] theorem coe_fn_add {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) (Q' : quadratic_form R M) : ⇑(Q + Q') = ⇑Q + ⇑Q' := rfl @[simp] theorem add_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) (Q' : quadratic_form R M) (x : M) : coe_fn (Q + Q') x = coe_fn Q x + coe_fn Q' x := rfl protected instance has_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : Neg (quadratic_form R M) := { neg := fun (Q : quadratic_form R M) => mk (-⇑Q) sorry sorry sorry sorry sorry } @[simp] theorem coe_fn_neg {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : ⇑(-Q) = -⇑Q := rfl @[simp] theorem neg_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) (x : M) : coe_fn (-Q) x = -coe_fn Q x := rfl protected instance has_scalar {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] : has_scalar R₁ (quadratic_form R₁ M) := has_scalar.mk fun (a : R₁) (Q : quadratic_form R₁ M) => mk (a • ⇑Q) sorry sorry sorry sorry sorry @[simp] theorem coe_fn_smul {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (a : R₁) (Q : quadratic_form R₁ M) : ⇑(a • Q) = a • ⇑Q := rfl @[simp] theorem smul_apply {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (a : R₁) (Q : quadratic_form R₁ M) (x : M) : coe_fn (a • Q) x = a * coe_fn Q x := rfl protected instance add_comm_group {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] : add_comm_group (quadratic_form R M) := add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg (add_group.sub._default Add.add sorry 0 sorry sorry Neg.neg) sorry sorry protected instance module {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] : module R₁ (quadratic_form R₁ M) := semimodule.mk sorry sorry /-- Compose the quadratic form with a linear function. -/ def comp {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {N : Type v} [add_comm_group N] [module R N] (Q : quadratic_form R N) (f : linear_map R M N) : quadratic_form R M := mk (fun (x : M) => coe_fn Q (coe_fn f x)) sorry sorry sorry sorry sorry @[simp] theorem comp_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {N : Type v} [add_comm_group N] [module R N] (Q : quadratic_form R N) (f : linear_map R M N) (x : M) : coe_fn (comp Q f) x = coe_fn Q (coe_fn f x) := rfl /-- Create a quadratic form in a commutative ring by proving only one side of the bilinearity. -/ def mk_left {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : M → R₁) (to_fun_smul : ∀ (a : R₁) (x : M), f (a • x) = a * a * f x) (polar_add_left : ∀ (x x' y : M), polar f (x + x') y = polar f x y + polar f x' y) (polar_smul_left : ∀ (a : R₁) (x y : M), polar f (a • x) y = a * polar f x y) : quadratic_form R₁ M := mk f to_fun_smul polar_add_left polar_smul_left sorry sorry /-- The product of linear forms is a quadratic form. -/ def lin_mul_lin {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) : quadratic_form R₁ M := mk_left (⇑f * ⇑g) sorry sorry sorry @[simp] theorem lin_mul_lin_apply {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (x : M) : coe_fn (lin_mul_lin f g) x = coe_fn f x * coe_fn g x := rfl @[simp] theorem add_lin_mul_lin {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (h : linear_map R₁ M R₁) : lin_mul_lin (f + g) h = lin_mul_lin f h + lin_mul_lin g h := ext fun (x : M) => add_mul (coe_fn f x) (coe_fn g x) (coe_fn h x) @[simp] theorem lin_mul_lin_add {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (h : linear_map R₁ M R₁) : lin_mul_lin f (g + h) = lin_mul_lin f g + lin_mul_lin f h := ext fun (x : M) => mul_add (coe_fn f x) (coe_fn g x) (coe_fn h x) @[simp] theorem lin_mul_lin_comp {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] {N : Type v} [add_comm_group N] [module R₁ N] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) (h : linear_map R₁ N M) : comp (lin_mul_lin f g) h = lin_mul_lin (linear_map.comp f h) (linear_map.comp g h) := rfl /-- `proj i j` is the quadratic form mapping the vector `x : n → R₁` to `x i * x j` -/ def proj {R₁ : Type u} [comm_ring R₁] {n : Type u_1} (i : n) (j : n) : quadratic_form R₁ (n → R₁) := lin_mul_lin (linear_map.proj i) (linear_map.proj j) @[simp] theorem proj_apply {R₁ : Type u} [comm_ring R₁] {n : Type u_1} (i : n) (j : n) (x : n → R₁) : coe_fn (proj i j) x = x i * x j := rfl end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ namespace bilin_form theorem polar_to_quadratic_form {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] {B : bilin_form R M} (x : M) (y : M) : quadratic_form.polar (fun (x : M) => coe_fn B x x) x y = coe_fn B x y + coe_fn B y x := sorry /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (B : bilin_form R M) : quadratic_form R M := quadratic_form.mk (fun (x : M) => coe_fn B x x) sorry sorry sorry sorry sorry @[simp] theorem to_quadratic_form_apply {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (B : bilin_form R M) (x : M) : coe_fn (to_quadratic_form B) x = coe_fn B x x := rfl end bilin_form namespace quadratic_form /-- `associated` is the linear map that sends a quadratic form to its associated symmetric bilinear form -/ def associated {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] : linear_map R₁ (quadratic_form R₁ M) (bilin_form R₁ M) := linear_map.mk (fun (Q : quadratic_form R₁ M) => bilin_form.mk (fun (x y : M) => ⅟ * polar (⇑Q) x y) sorry sorry sorry sorry) sorry sorry @[simp] theorem associated_apply {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} (x : M) (y : M) : coe_fn (coe_fn associated Q) x y = ⅟ * (coe_fn Q (x + y) - coe_fn Q x - coe_fn Q y) := rfl theorem associated_is_sym {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} : sym_bilin_form.is_sym (coe_fn associated Q) := sorry @[simp] theorem associated_comp {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} {N : Type v} [add_comm_group N] [module R₁ N] (f : linear_map R₁ N M) : coe_fn associated (comp Q f) = bilin_form.comp (coe_fn associated Q) f f := sorry @[simp] theorem associated_lin_mul_lin {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] (f : linear_map R₁ M R₁) (g : linear_map R₁ M R₁) : coe_fn associated (lin_mul_lin f g) = ⅟ • (bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f) := sorry theorem associated_to_quadratic_form {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] (B : bilin_form R₁ M) (x : M) (y : M) : coe_fn (coe_fn associated (bilin_form.to_quadratic_form B)) x y = ⅟ * (coe_fn B x y + coe_fn B y x) := sorry theorem associated_left_inverse {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {B₁ : bilin_form R₁ M} (h : sym_bilin_form.is_sym B₁) : coe_fn associated (bilin_form.to_quadratic_form B₁) = B₁ := sorry theorem associated_right_inverse {M : Type v} [add_comm_group M] {R₁ : Type u} [comm_ring R₁] [module R₁ M] [invertible (bit0 1)] {Q : quadratic_form R₁ M} : bilin_form.to_quadratic_form (coe_fn associated Q) = Q := sorry /-- An anisotropic quadratic form is zero only on zero vectors. -/ def anisotropic {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) := ∀ (x : M), coe_fn Q x = 0 → x = 0 theorem not_anisotropic_iff_exists {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : ¬anisotropic Q ↔ ∃ (x : M), ∃ (H : x ≠ 0), coe_fn Q x = 0 := sorry /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def {M : Type v} [add_comm_group M] {R₂ : Type u} [ordered_ring R₂] [module R₂ M] (Q₂ : quadratic_form R₂ M) := ∀ (x : M), x ≠ 0 → 0 < coe_fn Q₂ x theorem pos_def.smul {M : Type v} [add_comm_group M] {R : Type u_1} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} (a_pos : 0 < a) : pos_def (a • Q) := fun (x : M) (hx : x ≠ 0) => mul_pos a_pos (h x hx) theorem pos_def.add {M : Type v} [add_comm_group M] {R₂ : Type u} [ordered_ring R₂] [module R₂ M] (Q : quadratic_form R₂ M) (Q' : quadratic_form R₂ M) (hQ : pos_def Q) (hQ' : pos_def Q') : pos_def (Q + Q') := fun (x : M) (hx : x ≠ 0) => add_pos (hQ x hx) (hQ' x hx) theorem lin_mul_lin_self_pos_def {M : Type v} [add_comm_group M] {R : Type u_1} [linear_ordered_comm_ring R] [module R M] (f : linear_map R M R) (hf : linear_map.ker f = ⊥) : pos_def (lin_mul_lin f f) := sorry end quadratic_form /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form' {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := bilin_form.to_quadratic_form (coe_fn matrix.to_bilin' M) /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix' {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := coe_fn bilin_form.to_matrix' (coe_fn quadratic_form.associated Q) theorem quadratic_form.to_matrix'_smul {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : quadratic_form.to_matrix' (a • Q) = a • quadratic_form.to_matrix' Q := sorry namespace quadratic_form @[simp] theorem to_matrix'_comp {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] {m : Type w} [DecidableEq m] [fintype m] (Q : quadratic_form R₁ (m → R₁)) (f : linear_map R₁ (n → R₁) (m → R₁)) : to_matrix' (comp Q f) = matrix.mul (matrix.mul (matrix.transpose (coe_fn linear_map.to_matrix' f)) (to_matrix' Q)) (coe_fn linear_map.to_matrix' f) := sorry /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] (Q : quadratic_form R₁ (n → R₁)) : R₁ := matrix.det (to_matrix' Q) theorem discr_smul {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] {Q : quadratic_form R₁ (n → R₁)} (a : R₁) : discr (a • Q) = a ^ fintype.card n * discr Q := sorry theorem discr_comp {R₁ : Type u} [comm_ring R₁] {n : Type w} [fintype n] [DecidableEq n] [invertible (bit0 1)] {Q : quadratic_form R₁ (n → R₁)} (f : linear_map R₁ (n → R₁) (n → R₁)) : discr (comp Q f) = matrix.det (coe_fn linear_map.to_matrix' f) * matrix.det (coe_fn linear_map.to_matrix' f) * discr Q := sorry end quadratic_form namespace quadratic_form /-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`, is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/ structure isometry {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends linear_equiv R M₁ M₂ where map_app' : ∀ (m : M₁), coe_fn Q₂ (linear_equiv.to_fun _to_linear_equiv m) = coe_fn Q₁ m /-- Two quadratic forms over a ring `R` are equivalent if there exists an isometry between them: a linear equivalence that transforms one quadratic form into the other. -/ def equivalent {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := Nonempty (isometry Q₁ Q₂) namespace isometry protected instance linear_equiv.has_coe {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : has_coe (isometry Q₁ Q₂) (linear_equiv R M₁ M₂) := has_coe.mk to_linear_equiv protected instance has_coe_to_fun {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} : has_coe_to_fun (isometry Q₁ Q₂) := has_coe_to_fun.mk (fun (_x : isometry Q₁ Q₂) => M₁ → M₂) fun (f : isometry Q₁ Q₂) => ⇑↑f @[simp] theorem map_app {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (f : isometry Q₁ Q₂) (m : M₁) : coe_fn Q₂ (coe_fn f m) = coe_fn Q₁ m := map_app' f m /-- The identity isometry from a quadratic form to itself. -/ def refl {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : isometry Q Q := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.refl R M)) sorry sorry (linear_equiv.inv_fun (linear_equiv.refl R M)) sorry sorry) sorry /-- The inverse isometry of an isometry between two quadratic forms. -/ def symm {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (f : isometry Q₁ Q₂) : isometry Q₂ Q₁ := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.symm ↑f)) sorry sorry (linear_equiv.inv_fun (linear_equiv.symm ↑f)) sorry sorry) sorry /-- The composition of two isometries between quadratic forms. -/ def trans {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} {M₃ : Type u_3} [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] [module R M₁] [module R M₂] [module R M₃] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} (f : isometry Q₁ Q₂) (g : isometry Q₂ Q₃) : isometry Q₁ Q₃ := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.trans ↑f ↑g)) sorry sorry (linear_equiv.inv_fun (linear_equiv.trans ↑f ↑g)) sorry sorry) sorry end isometry namespace equivalent theorem refl {R : Type u} {M : Type v} [add_comm_group M] [ring R] [module R M] (Q : quadratic_form R M) : equivalent Q Q := Nonempty.intro (isometry.refl Q) theorem symm {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} (h : equivalent Q₁ Q₂) : equivalent Q₂ Q₁ := nonempty.elim h fun (f : isometry Q₁ Q₂) => Nonempty.intro (isometry.symm f) theorem trans {R : Type u} [ring R] {M₁ : Type u_1} {M₂ : Type u_2} {M₃ : Type u_3} [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃] [module R M₁] [module R M₂] [module R M₃] {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃} (h : equivalent Q₁ Q₂) (h' : equivalent Q₂ Q₃) : equivalent Q₁ Q₃ := nonempty.elim h' (nonempty.elim h fun (f : isometry Q₁ Q₂) (g : isometry Q₂ Q₃) => Nonempty.intro (isometry.trans f g)) end Mathlib
6c62d5c1898e2cc3b8fc3d951a322faa01712f0c
5c4b17dae42fab1d4f493f3b52977bffa54fefea
/4.6.6.lean
32179532b6ad716c29aaf0a222007ce17c87b9d8
[]
no_license
hyponymous/theorem-proving-in-lean-solutions
9214cb45cc87347862fd17dfdea79fdf24b9df92
a95320ae81c90c1b15da04574602cd378794400d
refs/heads/master
1,585,777,733,214
1,541,039,359,000
1,541,039,359,000
153,676,525
2
0
null
null
null
null
UTF-8
Lean
false
false
878
lean
variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := calc log (x * y) = log (exp (log x) * exp (log y)) : by rw [exp_log_eq hx, exp_log_eq hy] ... = log (exp (log x + log y)) : by rw exp_add ... = log x + log y : by rw log_exp_eq
7418529353035f1be10168d1c13206bd8173f79c
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/types/fiber.hlean
f8936d03e85ad5745f5714c94b1486c56ff3a4a0
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
21,869
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 is_equiv is_trunc function unit structure fiber {A B : Type} (f : A → B) (b : B) := (point : A) (point_eq : f point = b) variables {A B : Type} {f : A → B} {b : B} namespace fiber 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 /- equality type of a fiber -/ 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, 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_eq_equiv [constructor] (x y : fiber f b) : (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) := @equiv_change_inv _ _ (fiber_eq_equiv' x y) (λpq, fiber_eq pq.1 pq.2) begin intro pq, cases pq, reflexivity end definition point_fiber_eq {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : ap point (fiber_eq p q) = p := begin induction x with a r, induction y with a' s, esimp at *, induction p, induction q using eq.rec_symm, induction s, reflexivity end definition fiber_eq_equiv_fiber (x y : fiber f b) : x = y ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) := calc x = y ≃ fiber.sigma_char f b x = fiber.sigma_char f b y : eq_equiv_fn_eq (fiber.sigma_char f b) x y ... ≃ Σ(p : point x = point y), point_eq x =[p] point_eq y : sigma_eq_equiv ... ≃ Σ(p : point x = point y), (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : sigma_equiv_sigma_right (λp, calc point_eq x =[p] point_eq y ≃ point_eq x = ap f p ⬝ point_eq y : eq_pathover_equiv_Fl ... ≃ ap f p ⬝ point_eq y = point_eq x : eq_equiv_eq_symm ... ≃ (point_eq x)⁻¹ ⬝ (ap f p ⬝ point_eq y) = idp : eq_equiv_inv_con_eq_idp ... ≃ (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : equiv_eq_closed_left _ !con.assoc⁻¹) ... ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) : fiber.sigma_char definition point_fiber_eq_equiv_fiber {x y : fiber f b} (p : x = y) : point (fiber_eq_equiv_fiber x y p) = ap1_gen point idp idp p := by induction p; reflexivity definition fiber_eq_pr2 {x y : fiber f b} (p : x = y) : point_eq x = ap f (ap point p) ⬝ point_eq y := begin induction p, exact !idp_con⁻¹ end definition fiber_eq_eta {x y : fiber f b} (p : x = y) : p = fiber_eq (ap point p) (fiber_eq_pr2 p) := begin induction p, induction x with a q, induction q, reflexivity end definition fiber_eq_con {x y z : fiber f b} (p1 : point x = point y) (p2 : point y = point z) (q1 : point_eq x = ap f p1 ⬝ point_eq y) (q2 : point_eq y = ap f p2 ⬝ point_eq z) : fiber_eq p1 q1 ⬝ fiber_eq p2 q2 = fiber_eq (p1 ⬝ p2) (q1 ⬝ whisker_left (ap f p1) q2 ⬝ !con.assoc⁻¹ ⬝ whisker_right (point_eq z) (ap_con f p1 p2)⁻¹) := begin induction x with a₁ r₁, induction y with a₂ r₂, induction z with a₃ r₃, esimp at *, induction q2 using eq.rec_symm, induction q1 using eq.rec_symm, induction p2, induction p1, induction r₃, reflexivity end definition fiber_eq2_equiv {x y : fiber f b} (p₁ p₂ : point x = point y) (q₁ : point_eq x = ap f p₁ ⬝ point_eq y) (q₂ : point_eq x = ap f p₂ ⬝ point_eq y) : (fiber_eq p₁ q₁ = fiber_eq p₂ q₂) ≃ (Σ(r : p₁ = p₂), q₁ ⬝ whisker_right (point_eq y) (ap02 f r) = q₂) := begin refine (eq_equiv_fn_eq (fiber_eq_equiv x y)⁻¹ᵉ _ _)⁻¹ᵉ ⬝e sigma_eq_equiv _ _ ⬝e _, apply sigma_equiv_sigma_right, esimp, intro r, refine !eq_pathover_equiv_square ⬝e _, refine eq_hconcat_equiv !ap_constant ⬝e hconcat_eq_equiv (ap_compose (λx, x ⬝ _) _ _) ⬝e _, refine !square_equiv_eq ⬝e _, exact eq_equiv_eq_closed idp (idp_con q₂) end definition fiber_eq2 {x y : fiber f b} {p₁ p₂ : point x = point y} {q₁ : point_eq x = ap f p₁ ⬝ point_eq y} {q₂ : point_eq x = ap f p₂ ⬝ point_eq y} (r : p₁ = p₂) (s : q₁ ⬝ whisker_right (point_eq y) (ap02 f r) = q₂) : (fiber_eq p₁ q₁ = fiber_eq p₂ q₂) := (fiber_eq2_equiv p₁ p₂ q₁ q₂)⁻¹ᵉ ⟨r, s⟩ 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 definition is_trunc_fiber (n : ℕ₋₂) {A B : Type} (f : A → B) (b : B) (HA : is_trunc n A) (HB : is_trunc (n.+1) B) : is_trunc n (fiber f b) := is_trunc_equiv_closed_rev n !fiber.sigma_char _ definition is_contr_fiber_id (A : Type) (a : A) : is_contr (fiber (@id A) a) := is_contr.mk (fiber.mk a idp) begin intro x, induction x with a p, esimp at p, cases p, reflexivity end /- the general functoriality between fibers -/ -- todo: transpose the hsquare in fiber_functor? -- todo: show that the underlying map of fiber_equiv_of_square is fiber_functor definition fiber_functor [constructor] {A A' B B' : Type} {f : A → B} {f' : A' → B'} {b : B} {b' : B'} (g : A → A') (h : B → B') (H : hsquare g h f f') (p : h b = b') (x : fiber f b) : fiber f' b' := fiber.mk (g (point x)) (H (point x) ⬝ ap h (point_eq x) ⬝ p) /- equivalences between fibers -/ definition fiber_equiv_of_homotopy {A B : Type} {f g : A → B} (h : f ~ g) (b : B) : fiber f b ≃ fiber g b := begin refine (fiber.sigma_char f b ⬝e _ ⬝e (fiber.sigma_char g b)⁻¹ᵉ), apply sigma_equiv_sigma_right, intros a, apply equiv_eq_closed_left, apply h end definition fiber_equiv_basepoint [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 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 ... ≃ Σu, B u.1 : sigma_assoc_comm_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 fiber_compose_equiv {A B C : Type} (g : B → C) (f : A → B) (c : C) : fiber (g ∘ f) c ≃ Σ(x : fiber g c), fiber f (point x) := begin fapply equiv.MK, { intro x, exact ⟨fiber.mk (f (point x)) (point_eq x), fiber.mk (point x) idp⟩ }, { intro x, exact fiber.mk (point x.2) (ap g (point_eq x.2) ⬝ point_eq x.1) }, { intro x, induction x with x₁ x₂, induction x₁ with b p, induction x₂ with a q, induction p, esimp at q, induction q, reflexivity }, { intro x, induction x with a p, induction p, reflexivity } end -- pre and post composition with equivalences 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 definition fiber_equiv_of_square {A B C D : Type} {b : B} {d : D} {f : A → B} {g : C → D} (h : A ≃ C) (k : B ≃ D) (s : hsquare f g h k) (p : k b = d) : fiber f b ≃ fiber g d := calc fiber f b ≃ fiber (k ∘ f) (k b) : fiber.equiv_postcompose ... ≃ fiber (k ∘ f) d : fiber_equiv_basepoint (k ∘ f) p ... ≃ fiber (g ∘ h) d : fiber_equiv_of_homotopy s d ... ≃ fiber g d : fiber.equiv_precompose definition fiber_equiv_of_triangle {A B C : Type} {b : B} {f : A → B} {g : C → B} (h : A ≃ C) (s : f ~ g ∘ h) : fiber f b ≃ fiber g b := fiber_equiv_of_square h erfl s idp definition is_contr_fiber_equiv [instance] (f : A ≃ B) (b : B) : is_contr (fiber f b) := is_contr_equiv_closed (fiber_equiv_of_homotopy (to_left_inv f)⁻¹ʰᵗʸ _ ⬝e fiber.equiv_postcompose f f⁻¹ᵉ b) !is_contr_fiber_id definition is_contr_fiber_of_is_equiv [instance] [is_equiv f] (b : B) : is_contr (fiber f b) := is_contr_fiber_equiv (equiv.mk f _) b 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 definition fiber_total_equiv [constructor] {P Q : A → Type} (f : Πa, P a → Q a) {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 ... ≃ Σ(p : P a), f a p =[idpath a] q : sigma_sigma_eq_left ... ≃ Σ(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 definition fiber_equiv_of_is_contr [constructor] {A B : Type} (f : A → B) (b : B) (H : is_contr B) : fiber f b ≃ A := !fiber.sigma_char ⬝e sigma_equiv_of_is_contr_right _ _ /- the pointed fiber of a pointed map, which is the fiber over the basepoint -/ 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_pequiv_of_phomotopy {A B : Type*} {f g : A →* B} (h : f ~* g) : pfiber f ≃* pfiber g := begin fapply pequiv_of_equiv, { exact fiber_equiv_of_homotopy h pt }, { 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 pequiv_postcompose {A B B' : Type*} (f : A →* B) (g : B ≃* B') : pfiber (g ∘* f) ≃* pfiber f := begin fapply pequiv_of_equiv, esimp, refine fiber_equiv_basepoint (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'], exact ap_con_eq_con (λ x, ap g⁻¹ᵉ* (ap g (pleft_inv' g x)⁻¹) ⬝ ap g⁻¹ᵉ* (pright_inv g (g x)) ⬝ pleft_inv' g x) (respect_pt f) 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 (inj (fiber.sigma_char _ _)), fapply sigma_eq: esimp, { apply respect_pt g }, { apply eq_pathover_Fl' } end definition pfiber_pequiv_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_pequiv_of_phomotopy s ... ≃* pfiber g : pequiv_precompose definition pcompose_ppoint {A B : Type*} (f : A →* B) : f ∘* ppoint f ~* pconst (pfiber f) B := begin fapply phomotopy.mk, { exact point_eq }, { exact !idp_con⁻¹ } end definition loop_pfiber [constructor] {A B : Type*} (f : A →* B) : Ω (pfiber f) ≃* pfiber (Ω→ f) := pequiv_of_equiv (fiber_eq_equiv_fiber pt pt) begin induction f with f f₀, induction B with B b₀, esimp at (f,f₀), induction f₀, reflexivity end definition pfiber_loop_space {A B : Type*} (f : A →* B) : pfiber (Ω→ f) ≃* Ω (pfiber f) := (loop_pfiber f)⁻¹ᵉ* lemma ppoint_loop_pfiber {A B : Type*} (f : A →* B) : ppoint (Ω→ f) ∘* loop_pfiber f ~* Ω→ (ppoint f) := phomotopy.mk (point_fiber_eq_equiv_fiber) begin induction f with f f₀, induction B with B b₀, esimp at (f,f₀), induction f₀, reflexivity end lemma ppoint_loop_pfiber_inv {A B : Type*} (f : A →* B) : Ω→ (ppoint f) ∘* (loop_pfiber f)⁻¹ᵉ* ~* ppoint (Ω→ f) := (phomotopy_pinv_right_of_phomotopy (ppoint_loop_pfiber f))⁻¹* lemma pfiber_pequiv_of_phomotopy_ppoint {A B : Type*} {f g : A →* B} (h : f ~* g) : ppoint g ∘* pfiber_pequiv_of_phomotopy h ~* ppoint f := begin induction f with f f₀, induction g with g g₀, induction h with h h₀, induction B with B b₀, esimp at *, induction h₀, induction g₀, fapply phomotopy.mk, { reflexivity }, { symmetry, rexact point_fiber_eq (idpath pt) (inv_con_eq_of_eq_con (idpath (h pt ⬝ (idp ⬝ point_eq (fiber.mk pt idp))))) } end lemma pequiv_postcompose_ppoint {A B B' : Type*} (f : A →* B) (g : B ≃* B') : ppoint f ∘* fiber.pequiv_postcompose f g ~* ppoint (g ∘* f) := begin induction f with f f₀, induction g with g hg g₀, induction B with B b₀, induction B' with B' b₀', esimp at * ⊢, induction g₀, induction f₀, fapply phomotopy.mk, { reflexivity }, { symmetry, refine !ap_compose⁻¹ ⬝ _, apply ap_constant } end lemma pequiv_precompose_ppoint {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : ppoint f ∘* fiber.pequiv_precompose f g ~* g ∘* ppoint (f ∘* g) := begin induction f with f f₀, induction g with g h₁ h₂ p₁ p₂, induction B with B b₀, induction g with g g₀, induction A with A a₀', esimp at *, induction g₀, induction f₀, reflexivity end definition pfiber_pequiv_of_square_ppoint {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k ∘* f ~* g ∘* h) : ppoint g ∘* pfiber_pequiv_of_square h k s ~* h ∘* ppoint f := begin refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ !pequiv_precompose_ppoint ⬝* _, refine !passoc ⬝* _, apply pwhisker_left, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ !pfiber_pequiv_of_phomotopy_ppoint ⬝* _, apply pinv_right_phomotopy_of_phomotopy, refine !pequiv_postcompose_ppoint⁻¹*, end definition is_trunc_pfiber (n : ℕ₋₂) {A B : Type*} (f : A →* B) (HA : is_trunc n A) (HB : is_trunc (n.+1) B) : is_trunc n (pfiber f) := is_trunc_fiber n f pt HA HB definition pfiber_pequiv_of_is_contr [constructor] {A B : Type*} (f : A →* B) (H : is_contr B) : pfiber f ≃* A := pequiv_of_equiv (fiber_equiv_of_is_contr f pt H) idp definition pfiber_ppoint_equiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃ Ω B := calc pfiber (ppoint f) ≃ Σ(x : pfiber f), ppoint f x = pt : fiber.sigma_char ... ≃ Σ(x : Σa, f a = pt), x.1 = pt : by exact sigma_equiv_sigma !fiber.sigma_char (λa, erfl) ... ≃ Σ(x : Σa, a = pt), f x.1 = pt : by exact !sigma_assoc_comm_equiv ... ≃ f pt = pt : by exact sigma_equiv_of_is_contr_left _ _ ... ≃ Ω B : by exact !equiv_eq_closed_left !respect_pt definition pfiber_ppoint_pequiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃* Ω B := pequiv_of_equiv (pfiber_ppoint_equiv f) !con.left_inv definition pfiber_ppoint_equiv_eq {A B : Type*} {f : A →* B} {a : A} (p : f a = pt) (q : ppoint f (fiber.mk a p) = pt) : pfiber_ppoint_equiv f (fiber.mk (fiber.mk a p) q) = (respect_pt f)⁻¹ ⬝ ap f q⁻¹ ⬝ p := begin refine _ ⬝ !con.assoc⁻¹, apply whisker_left, refine eq_transport_Fl _ _ ⬝ _, apply whisker_right, refine inverse2 !ap_inv ⬝ !inv_inv ⬝ _, refine ap_compose f pr₁ _ ⬝ ap02 f !ap_pr1_center_eq_sigma_eq', end definition pfiber_ppoint_equiv_inv_eq {A B : Type*} (f : A →* B) (p : Ω B) : (pfiber_ppoint_equiv f)⁻¹ᵉ p = fiber.mk (fiber.mk pt (respect_pt f ⬝ p)) idp := begin apply inv_eq_of_eq, refine _ ⬝ !pfiber_ppoint_equiv_eq⁻¹, exact !inv_con_cancel_left⁻¹ end definition loopn_pfiber [constructor] {A B : Type*} (n : ℕ) (f : A →* B) : Ω[n] (pfiber f) ≃* pfiber (Ω→[n] f) := begin induction n with n IH, reflexivity, exact loop_pequiv_loop IH ⬝e* loop_pfiber (Ω→[n] f), end definition is_contr_pfiber_pid (A : Type*) : is_contr (pfiber (pid A)) := by exact is_contr_fiber_id A pt definition pfiber_functor [constructor] {A A' B B' : Type*} {f : A →* B} {f' : A' →* B'} (g : A →* A') (h : B →* B') (H : psquare g h f f') : pfiber f →* pfiber f' := pmap.mk (fiber_functor g h H (respect_pt h)) begin fapply fiber_eq, exact respect_pt g, exact !con.assoc ⬝ to_homotopy_pt H end definition ppoint_natural {A A' B B' : Type*} {f : A →* B} {f' : A' →* B'} (g : A →* A') (h : B →* B') (H : psquare g h f f') : psquare (ppoint f) (ppoint f') (pfiber_functor g h H) g := begin fapply phomotopy.mk, { intro x, reflexivity }, { refine !idp_con ⬝ _ ⬝ !idp_con⁻¹, esimp, apply point_fiber_eq } end /- A less commonly used pointed fiber with basepoint (f a) for some a in the domain of f -/ definition pointed_fiber [constructor] (f : A → B) (a : A) : Type* := pointed.Mk (fiber.mk a (idpath (f a))) end fiber open fiber /- A function is truncated if it has truncated fibers -/ 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 definition is_trunc_fun_id (k : ℕ₋₂) (A : Type) : is_trunc_fun k (@id A) := λa, is_trunc_of_is_contr _ _ !is_contr_fiber_id definition is_trunc_fun_compose (k : ℕ₋₂) {A B C : Type} {g : B → C} {f : A → B} (Hg : is_trunc_fun k g) (Hf : is_trunc_fun k f) : is_trunc_fun k (g ∘ f) := λc, is_trunc_equiv_closed_rev k (fiber_compose_equiv g f c) _
827df1d12d8ac17d4abb632a804ffeceda751e28
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast_cc4.lean
b4bf66ed0c7d7fe4850867629a3dfd2990151e59
[ "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
233
lean
open nat set_option blast.subst false definition tst (a₁ a₂ b₁ b₂ c d : nat) : a₁ = c → a₂ = c → b₁ = d → d = b₂ → a₁ + b₁ + a₁ = a₂ + b₂ + c := by blast print tst
2e1bb287d2dc1189db6777bf2bd688dc944b1b23
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/polynomial/lifts.lean
8ebebc75e811e32fae29431e6c6e76176d9d2c58
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
10,803
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import data.polynomial.algebra_map import algebra.algebra.subalgebra import algebra.polynomial.big_operators import data.polynomial.erase_lead /-! # Polynomials that lift Given semirings `R` and `S` with a morphism `f : R →+* S`, we define a subsemiring `lifts` of `polynomial S` by the image of `ring_hom.of (map f)`. Then, we prove that a polynomial that lifts can always be lifted to a polynomial of the same degree and that a monic polynomial that lifts can be lifted to a monic polynomial (of the same degree). ## Main definition * `lifts (f : R →+* S)` : the subsemiring of polynomials that lift. ## Main results * `lifts_and_degree_eq` : A polynomial lifts if and only if it can be lifted to a polynomial of the same degree. * `lifts_and_degree_eq_and_monic` : A monic polynomial lifts if and only if it can be lifted to a monic polynomial of the same degree. * `lifts_iff_alg` : if `R` is commutative, a polynomial lifts if and only if it is in the image of `map_alg`, where `map_alg : polynomial R →ₐ[R] polynomial S` is the only `R`-algebra map that sends `X` to `X`. ## Implementation details In general `R` and `S` are semiring, so `lifts` is a semiring. In the case of rings, see `lifts_iff_lifts_ring`. Since we do not assume `R` to be commutative, we cannot say in general that the set of polynomials that lift is a subalgebra. (By `lift_iff` this is true if `R` is commutative.) -/ open_locale classical big_operators noncomputable theory namespace polynomial universes u v w section semiring variables {R : Type u} [semiring R] {S : Type v} [semiring S] {f : R →+* S} /-- We define the subsemiring of polynomials that lifts as the image of `ring_hom.of (map f)`. -/ def lifts (f : R →+* S) : subsemiring (polynomial S) := ring_hom.srange (ring_hom.of (map f)) lemma mem_lifts (p : polynomial S) : p ∈ lifts f ↔ ∃ (q : polynomial R), map f q = p := by simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange] lemma lifts_iff_set_range (p : polynomial S) : p ∈ lifts f ↔ p ∈ set.range (map f) := by simp only [lifts, set.mem_range, ring_hom.coe_of, ring_hom.mem_srange] lemma lifts_iff_coeff_lifts (p : polynomial S) : p ∈ lifts f ↔ ∀ (n : ℕ), p.coeff n ∈ set.range f := by rw [lifts_iff_set_range, mem_map_range] /--If `(r : R)`, then `C (f r)` lifts. -/ lemma C_mem_lifts (f : R →+* S) (r : R) : (C (f r)) ∈ lifts f := ⟨C r, by simp only [map_C, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, ring_hom.coe_of, and_self]⟩ /-- If `(s : S)` is in the image of `f`, then `C s` lifts. -/ lemma C'_mem_lifts {f : R →+* S} {s : S} (h : s ∈ set.range f) : (C s) ∈ lifts f := begin obtain ⟨r, rfl⟩ := set.mem_range.1 h, use C r, simp only [map_C, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, ring_hom.coe_of, and_self] end /-- The polynomial `X` lifts. -/ lemma X_mem_lifts (f : R →+* S) : (X : polynomial S) ∈ lifts f := ⟨X, by simp only [set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_X, ring_hom.coe_of, and_self]⟩ /-- The polynomial `X ^ n` lifts. -/ lemma X_pow_mem_lifts (f : R →+* S) (n : ℕ) : (X ^ n : polynomial S) ∈ lifts f := ⟨X ^ n, by simp only [map_pow, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, map_X, ring_hom.coe_of, and_self]⟩ /-- If `p` lifts and `(r : R)` then `r * p` lifts. -/ lemma base_mul_mem_lifts {p : polynomial S} (r : R) (hp : p ∈ lifts f) : C (f r) * p ∈ lifts f := begin simp only [lifts, ring_hom.coe_of, ring_hom.mem_srange] at hp ⊢, obtain ⟨p₁, rfl⟩ := hp, use C r * p₁, simp only [map_C, map_mul] end /-- If `(s : S)` is in the image of `f`, then `monomial n s` lifts. -/ lemma monomial_mem_lifts {s : S} (n : ℕ) (h : s ∈ set.range f) : (monomial n s) ∈ lifts f := begin obtain ⟨r, rfl⟩ := set.mem_range.1 h, use monomial n r, simp only [set.mem_univ, map_monomial, subsemiring.coe_top, eq_self_iff_true, ring_hom.coe_of, and_self], end /-- If `p` lifts then `p.erase n` lifts. -/ lemma erase_mem_lifts {p : polynomial S} (n : ℕ) (h : p ∈ lifts f) : p.erase n ∈ lifts f := begin rw [lifts_iff_set_range, mem_map_range] at h ⊢, intros k, by_cases hk : k = n, { use 0, simp only [hk, ring_hom.map_zero, erase_same] }, obtain ⟨i, hi⟩ := h k, use i, simp only [hi, hk, erase_ne, ne.def, not_false_iff], end section lift_deg lemma monomial_mem_lifts_and_degree_eq {s : S} {n : ℕ} (hl : monomial n s ∈ lifts f) : ∃ (q : polynomial R), map f q = (monomial n s) ∧ q.degree = (monomial n s).degree := begin by_cases hzero : s = 0, { use 0, simp only [hzero, degree_zero, eq_self_iff_true, and_self, monomial_zero_right, map_zero] }, rw lifts_iff_set_range at hl, obtain ⟨q, hq⟩ := hl, replace hq := (ext_iff.1 hq) n, have hcoeff : f (q.coeff n) = s, { simp [coeff_monomial] at hq, exact hq }, use (monomial n (q.coeff n)), split, { simp only [hcoeff, map_monomial] }, have hqzero : q.coeff n ≠ 0, { intro habs, simp only [habs, ring_hom.map_zero] at hcoeff, exact hzero hcoeff.symm }, repeat {rw monomial_eq_C_mul_X}, simp only [hzero, hqzero, ne.def, not_false_iff, degree_C_mul_X_pow], end /-- A polynomial lifts if and only if it can be lifted to a polynomial of the same degree. -/ lemma mem_lifts_and_degree_eq {p : polynomial S} (hlifts : p ∈ lifts f) : ∃ (q : polynomial R), map f q = p ∧ q.degree = p.degree := begin generalize' hd : p.nat_degree = d, revert hd p, apply nat.strong_induction_on d, intros n hn p hlifts hdeg, by_cases erase_zero : p.erase_lead = 0, { rw [← erase_lead_add_monomial_nat_degree_leading_coeff p, erase_zero, zero_add, leading_coeff], exact monomial_mem_lifts_and_degree_eq (monomial_mem_lifts p.nat_degree ((lifts_iff_coeff_lifts p).1 hlifts p.nat_degree)) }, have deg_erase := or.resolve_right (erase_lead_nat_degree_lt_or_erase_lead_eq_zero p) erase_zero, have pzero : p ≠ 0, { intro habs, exfalso, rw [habs, erase_lead_zero, eq_self_iff_true, not_true] at erase_zero, exact erase_zero }, have lead_zero : p.coeff p.nat_degree ≠ 0, { rw [← leading_coeff, ne.def, leading_coeff_eq_zero]; exact pzero }, obtain ⟨lead, hlead⟩ := monomial_mem_lifts_and_degree_eq (monomial_mem_lifts p.nat_degree ((lifts_iff_coeff_lifts p).1 hlifts p.nat_degree)), have deg_lead : lead.degree = p.nat_degree, { rw [hlead.2, monomial_eq_C_mul_X, degree_C_mul_X_pow p.nat_degree lead_zero] }, rw hdeg at deg_erase, obtain ⟨erase, herase⟩ := hn p.erase_lead.nat_degree deg_erase (erase_mem_lifts p.nat_degree hlifts) (refl p.erase_lead.nat_degree), use erase + lead, split, { simp only [hlead, herase, map_add], nth_rewrite 0 erase_lead_add_monomial_nat_degree_leading_coeff p }, rw [←hdeg, erase_lead] at deg_erase, replace deg_erase := lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 deg_erase), rw [← deg_lead, ← herase.2] at deg_erase, rw [degree_add_eq_right_of_degree_lt deg_erase, deg_lead, degree_eq_nat_degree pzero] end end lift_deg section monic /-- A monic polynomial lifts if and only if it can be lifted to a monic polynomial of the same degree. -/ lemma lifts_and_degree_eq_and_monic [nontrivial S] {p : polynomial S} (hlifts :p ∈ lifts f) (hmonic : p.monic) : ∃ (q : polynomial R), map f q = p ∧ q.degree = p.degree ∧ q.monic := begin by_cases Rtrivial : nontrivial R, swap, { rw not_nontrivial_iff_subsingleton at Rtrivial, obtain ⟨q, hq⟩ := mem_lifts_and_degree_eq hlifts, use q, exact ⟨hq.1, hq.2, @monic_of_subsingleton _ _ Rtrivial q⟩ }, by_cases er_zero : p.erase_lead = 0, { rw [← erase_lead_add_C_mul_X_pow p, er_zero, zero_add, monic.def.1 hmonic, C_1, one_mul], use X ^ p.nat_degree, repeat {split}, { simp only [map_pow, map_X] }, { rw [@degree_X_pow R _ Rtrivial, degree_X_pow] }, {exact monic_pow monic_X p.nat_degree } }, obtain ⟨q, hq⟩ := mem_lifts_and_degree_eq (erase_mem_lifts p.nat_degree hlifts), have deg_er : p.erase_lead.nat_degree < p.nat_degree := or.resolve_right (erase_lead_nat_degree_lt_or_erase_lead_eq_zero p) er_zero, replace deg_er := with_bot.coe_lt_coe.2 deg_er, rw [← degree_eq_nat_degree er_zero, erase_lead, ← hq.2, ← @degree_X_pow R _ Rtrivial p.nat_degree] at deg_er, use q + X ^ p.nat_degree, repeat {split}, { simp only [hq, map_add, map_pow, map_X], nth_rewrite 3 [← erase_lead_add_C_mul_X_pow p], rw [erase_lead, monic.leading_coeff hmonic, C_1, one_mul] }, { rw [degree_add_eq_right_of_degree_lt deg_er, @degree_X_pow R _ Rtrivial p.nat_degree, degree_eq_nat_degree (monic.ne_zero hmonic)] }, { rw [monic.def, leading_coeff_add_of_degree_lt deg_er], exact monic_pow monic_X p.nat_degree } end end monic end semiring section ring variables {R : Type u} [ring R] {S : Type v} [ring S] (f : R →+* S) /-- The subring of polynomials that lift. -/ def lifts_ring (f : R →+* S) : subring (polynomial S) := ring_hom.range (ring_hom.of (map f)) /-- If `R` and `S` are rings, `p` is in the subring of polynomials that lift if and only if it is in the subsemiring of polynomials that lift. -/ lemma lifts_iff_lifts_ring (p : polynomial S) : p ∈ lifts f ↔ p ∈ lifts_ring f := by simp only [lifts, lifts_ring, ring_hom.mem_range, ring_hom.mem_srange] end ring section algebra variables {R : Type u} [comm_semiring R] {S : Type v} [semiring S] [algebra R S] /-- The map `polynomial R → polynomial S` as an algebra homomorphism. -/ def map_alg (R : Type u) [comm_semiring R] (S : Type v) [semiring S] [algebra R S] : polynomial R →ₐ[R] polynomial S := @aeval _ (polynomial S) _ _ _ (X : polynomial S) /-- `map_alg` is the morphism induced by `R → S`. -/ lemma map_alg_eq_map (p : polynomial R) : map_alg R S p = map (algebra_map R S) p := by simp only [map_alg, aeval_def, eval₂, map, algebra_map_apply, ring_hom.coe_comp] /-- A polynomial `p` lifts if and only if it is in the image of `map_alg`. -/ lemma mem_lifts_iff_mem_alg (R : Type u) [comm_semiring R] {S : Type v} [semiring S] [algebra R S] (p : polynomial S) :p ∈ lifts (algebra_map R S) ↔ p ∈ (alg_hom.range (@map_alg R _ S _ _)) := by simp only [lifts, map_alg_eq_map, alg_hom.mem_range, ring_hom.coe_of, ring_hom.mem_srange] /-- If `p` lifts and `(r : R)` then `r • p` lifts. -/ lemma smul_mem_lifts {p : polynomial S} (r : R) (hp : p ∈ lifts (algebra_map R S)) : r • p ∈ lifts (algebra_map R S) := by { rw mem_lifts_iff_mem_alg at hp ⊢, exact subalgebra.smul_mem (map_alg R S).range hp r } end algebra end polynomial
cc606135a50d9ec273ed51ab8bc582d9969f4d97
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/library/algebra/ring.lean
685225875d6e46e9f8621d20393ce944fab97b8e
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,374
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 Structures with multiplicative and additive components, including semirings, rings, and fields. The development is modeled after Isabelle's library. -/ import logic.eq logic.connectives data.unit data.sigma data.prod import algebra.binary algebra.group open eq eq.ops variable {A : Type} /- auxiliary classes -/ structure distrib [class] (A : Type) extends has_mul A, has_add A := (left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c)) (right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c)) theorem left_distrib [distrib A] (a b c : A) : a * (b + c) = a * b + a * c := !distrib.left_distrib theorem right_distrib [distrib A] (a b c : A) : (a + b) * c = a * c + b * c := !distrib.right_distrib structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A := (zero_mul : ∀a, mul zero a = zero) (mul_zero : ∀a, mul a zero = zero) theorem zero_mul [simp] [mul_zero_class A] (a : A) : 0 * a = 0 := !mul_zero_class.zero_mul theorem mul_zero [simp] [mul_zero_class A] (a : A) : a * 0 = 0 := !mul_zero_class.mul_zero structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A := (zero_ne_one : zero ≠ one) theorem zero_ne_one [s: zero_ne_one_class A] : 0 ≠ (1:A) := @zero_ne_one_class.zero_ne_one A s /- semiring -/ structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A, mul_zero_class A section semiring variables [s : semiring A] (a b c : A) include s theorem one_add_one_eq_two : 1 + 1 = (2:A) := by unfold bit0 theorem ne_zero_of_mul_ne_zero_right {a b : A} (H : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, by rewrite [this, zero_mul], H this theorem ne_zero_of_mul_ne_zero_left {a b : A} (H : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, by rewrite [this, mul_zero], H this local attribute right_distrib [simp] theorem distrib_three_right (a b c d : A) : (a + b + c) * d = a * d + b * d + c * d := by simp end semiring /- comm semiring -/ structure comm_semiring [class] (A : Type) extends semiring A, comm_monoid A -- TODO: we could also define a cancelative comm_semiring, i.e. satisfying -- c ≠ 0 → c * a = c * b → a = b. section comm_semiring variables [s : comm_semiring A] (a b c : A) include s protected definition algebra.dvd (a b : A) : Prop := ∃c, b = a * c definition comm_semiring_has_dvd [reducible] [instance] [priority algebra.prio] : has_dvd A := has_dvd.mk algebra.dvd theorem dvd.intro {a b c : A} (H : a * c = b) : a ∣ b := exists.intro _ H⁻¹ theorem dvd_of_mul_right_eq {a b c : A} (H : a * c = b) : a ∣ b := dvd.intro H theorem dvd.intro_left {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro (by rewrite mul.comm at H; exact H) theorem dvd_of_mul_left_eq {a b c : A} (H : c * a = b) : a ∣ b := dvd.intro_left H theorem exists_eq_mul_right_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = a * c := H theorem dvd.elim {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd {a b : A} (H : a ∣ b) : ∃c, b = c * a := dvd.elim H (take c, assume H1 : b = a * c, exists.intro c (H1 ⬝ !mul.comm)) theorem dvd.elim_left {P : Prop} {a b : A} (H₁ : a ∣ b) (H₂ : ∀c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd H₁) (take c, assume H₃ : b = c * a, H₂ c H₃) theorem dvd.refl [simp] : a ∣ a := dvd.intro !mul_one theorem dvd.trans {a b c : A} (H₁ : a ∣ b) (H₂ : b ∣ c) : a ∣ c := dvd.elim H₁ (take d, assume H₃ : b = a * d, dvd.elim H₂ (take e, assume H₄ : c = b * e, dvd.intro (show a * (d * e) = c, by rewrite [-mul.assoc, -H₃, H₄]))) theorem eq_zero_of_zero_dvd {a : A} (H : 0 ∣ a) : a = 0 := dvd.elim H (take c, assume H' : a = 0 * c, H' ⬝ !zero_mul) theorem dvd_zero [simp] : a ∣ 0 := dvd.intro !mul_zero theorem one_dvd [simp] : 1 ∣ a := dvd.intro !one_mul theorem dvd_mul_right [simp] : a ∣ a * b := dvd.intro rfl theorem dvd_mul_left [simp] : a ∣ b * a := by simp theorem dvd_mul_of_dvd_left {a b : A} (H : a ∣ b) (c : A) : a ∣ b * c := dvd.elim H (take d, suppose b = a * d, dvd.intro (show a * (d * c) = b * c, by simp)) theorem dvd_mul_of_dvd_right {a b : A} (H : a ∣ b) (c : A) : a ∣ c * b := !mul.comm ▸ (dvd_mul_of_dvd_left H _) theorem mul_dvd_mul {a b c d : A} (dvd_ab : a ∣ b) (dvd_cd : c ∣ d) : a * c ∣ b * d := dvd.elim dvd_ab (take e, suppose b = a * e, dvd.elim dvd_cd (take f, suppose d = c * f, dvd.intro (show a * c * (e * f) = b * d, by simp))) theorem dvd_of_mul_right_dvd {a b c : A} (H : a * b ∣ c) : a ∣ c := dvd.elim H (take d, assume Habdc : c = a * b * d, dvd.intro (!mul.assoc⁻¹ ⬝ Habdc⁻¹)) theorem dvd_of_mul_left_dvd {a b c : A} (H : a * b ∣ c) : b ∣ c := dvd_of_mul_right_dvd (mul.comm a b ▸ H) theorem dvd_add {a b c : A} (Hab : a ∣ b) (Hac : a ∣ c) : a ∣ b + c := dvd.elim Hab (take d, suppose b = a * d, dvd.elim Hac (take e, suppose c = a * e, dvd.intro (show a * (d + e) = b + c, by rewrite [left_distrib]; substvars))) end comm_semiring /- ring -/ structure ring [class] (A : Type) extends add_comm_group A, monoid A, distrib A theorem ring.mul_zero [simp] [ring A] (a : A) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rewrite left_distrib, show a * 0 = 0, from (add.left_cancel this)⁻¹ theorem ring.zero_mul [simp] [ring A] (a : A) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add.left_cancel this)⁻¹ definition ring.to_semiring [trans_instance] [reducible] [s : ring A] : semiring A := ⦃ semiring, s, mul_zero := ring.mul_zero, zero_mul := ring.zero_mul ⦄ section variables [s : ring A] (a b c d e : A) include s theorem neg_mul_eq_neg_mul : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rewrite [-right_distrib, add.right_inv, zero_mul] end theorem neg_mul_eq_mul_neg : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rewrite [-left_distrib, add.right_inv, mul_zero] end theorem neg_mul_eq_neg_mul_symm [simp] : - a * b = - (a * b) := eq.symm !neg_mul_eq_neg_mul theorem mul_neg_eq_neg_mul_symm [simp] : a * - b = - (a * b) := eq.symm !neg_mul_eq_mul_neg theorem neg_mul_neg : -a * -b = a * b := by simp theorem neg_mul_comm : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul : -a = -1 * a := by simp theorem mul_sub_left_distrib : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib ... = a * b - a * c : by simp theorem mul_sub_right_distrib : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib ... = a * c - b * c : by simp -- TODO: can calc mode be improved to make this easier? -- TODO: there is also the other direction. It will be easier when we -- have the simplifier. theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by rewrite {b*e+_}add.comm ... ↔ a * e + c - b * e = d : iff.symm !sub_eq_iff_eq_add ... ↔ a * e - b * e + c = d : by rewrite sub_add_eq_add_sub ... ↔ (a - b) * e + c = d : by rewrite mul_sub_right_distrib theorem mul_add_eq_mul_add_of_sub_mul_add_eq : (a - b) * e + c = d → a * e + c = b * e + d := iff.mpr !mul_add_eq_mul_add_iff_sub_mul_add_eq theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := iff.mp !mul_add_eq_mul_add_iff_sub_mul_add_eq theorem mul_neg_one_eq_neg : a * (-1) = -a := have a + a * -1 = 0, from calc a + a * -1 = a * 1 + a * -1 : by simp ... = a * (1 + -1) : left_distrib ... = 0 : by simp, symm (neg_eq_of_add_eq_zero this) theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : A} (H : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := have a ≠ 0, from (suppose a = 0, have a * b = 0, by rewrite [this, zero_mul], absurd this H), have b ≠ 0, from (suppose b = 0, have a * b = 0, by rewrite [this, mul_zero], absurd this H), and.intro `a ≠ 0` `b ≠ 0` end structure comm_ring [class] (A : Type) extends ring A, comm_semigroup A definition comm_ring.to_comm_semiring [trans_instance] [reducible] [s : comm_ring A] : comm_semiring A := ⦃ comm_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul ⦄ section variables [s : comm_ring A] (a b c d e : A) include s local attribute left_distrib right_distrib [simp] theorem mul_self_sub_mul_self_eq : a * a - b * b = (a + b) * (a - b) := by simp theorem mul_self_sub_one_eq : a * a - 1 = (a + 1) * (a - 1) := by simp theorem add_mul_self_eq : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp ... = a*a + 2*a*b + b*b : by rewrite one_add_one_eq_two theorem dvd_neg_iff_dvd : (a ∣ -b) ↔ (a ∣ b) := iff.intro (suppose a ∣ -b, dvd.elim this (take c, suppose -b = a * c, dvd.intro (show a * -c = b, by rewrite [-neg_mul_eq_mul_neg, -this, neg_neg]))) (suppose a ∣ b, dvd.elim this (take c, suppose b = a * c, dvd.intro (show a * -c = -b, by rewrite [-neg_mul_eq_mul_neg, -this]))) theorem dvd_neg_of_dvd : (a ∣ b) → (a ∣ -b) := iff.mpr !dvd_neg_iff_dvd theorem dvd_of_dvd_neg : (a ∣ -b) → (a ∣ b) := iff.mp !dvd_neg_iff_dvd theorem neg_dvd_iff_dvd : (-a ∣ b) ↔ (a ∣ b) := iff.intro (suppose -a ∣ b, dvd.elim this (take c, suppose b = -a * c, dvd.intro (show a * -c = b, by rewrite [-neg_mul_comm, this]))) (suppose a ∣ b, dvd.elim this (take c, suppose b = a * c, dvd.intro (show -a * -c = b, by rewrite [neg_mul_neg, this]))) theorem neg_dvd_of_dvd : (a ∣ b) → (-a ∣ b) := iff.mpr !neg_dvd_iff_dvd theorem dvd_of_neg_dvd : (-a ∣ b) → (a ∣ b) := iff.mp !neg_dvd_iff_dvd theorem dvd_sub (H₁ : (a ∣ b)) (H₂ : (a ∣ c)) : (a ∣ b - c) := dvd_add H₁ (!dvd_neg_of_dvd H₂) end /- integral domains -/ structure no_zero_divisors [class] (A : Type) extends has_mul A, has_zero A := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀a b, mul a b = zero → a = zero ∨ b = zero) theorem eq_zero_or_eq_zero_of_mul_eq_zero {A : Type} [no_zero_divisors A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := !no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero H theorem eq_zero_of_mul_self_eq_zero {A : Type} [no_zero_divisors A] {a : A} (H : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero H) (assume H', H') (assume H', H') structure integral_domain [class] (A : Type) extends comm_ring A, no_zero_divisors A, zero_ne_one_class A section variables [s : integral_domain A] (a b c d e : A) include s theorem mul_ne_zero {a b : A} (H1 : a ≠ 0) (H2 : b ≠ 0) : a * b ≠ 0 := suppose a * b = 0, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume H3, H1 H3) (assume H4, H2 H4) theorem eq_of_mul_eq_mul_right {a b c : A} (Ha : a ≠ 0) (H : b * a = c * a) : b = c := have b * a - c * a = 0, from iff.mp !eq_iff_sub_eq_zero H, have (b - c) * a = 0, using this, by rewrite [mul_sub_right_distrib, this], have b - c = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha, iff.elim_right !eq_iff_sub_eq_zero this theorem eq_of_mul_eq_mul_left {a b c : A} (Ha : a ≠ 0) (H : a * b = a * c) : b = c := have a * b - a * c = 0, from iff.mp !eq_iff_sub_eq_zero H, have a * (b - c) = 0, using this, by rewrite [mul_sub_left_distrib, this], have b - c = 0, from or_resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero this) Ha, iff.elim_right !eq_iff_sub_eq_zero this -- TODO: do we want the iff versions? theorem eq_zero_of_mul_eq_self_right {a b : A} (H₁ : b ≠ 1) (H₂ : a * b = a) : a = 0 := have b - 1 ≠ 0, from suppose b - 1 = 0, H₁ (!zero_add ▸ eq_add_of_sub_eq this), have a * b - a = 0, by simp, have a * (b - 1) = 0, by+ rewrite [mul_sub_left_distrib, mul_one]; apply this, show a = 0, from or_resolve_left (eq_zero_or_eq_zero_of_mul_eq_zero this) `b - 1 ≠ 0` theorem eq_zero_of_mul_eq_self_left {a b : A} (H₁ : b ≠ 1) (H₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right H₁ (!mul.comm ▸ H₂) theorem mul_self_eq_mul_self_iff (a b : A) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul.comm, -mul_self_sub_mul_self_eq, this, sub_self], assert a - b = 0 ∨ a + b = 0, from !eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) theorem mul_self_eq_one_iff (a : A) : a * a = 1 ↔ a = 1 ∨ a = -1 := assert a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rewrite mul_one at this; exact this -- TODO: c - b * c → c = 0 ∨ b = 1 and variants theorem dvd_of_mul_dvd_mul_left {a b c : A} (Ha : a ≠ 0) (Hdvd : (a * b ∣ a * c)) : (b ∣ c) := dvd.elim Hdvd (take d, suppose a * c = a * b * d, have b * d = c, from eq_of_mul_eq_mul_left Ha (mul.assoc a b d ▸ this⁻¹), dvd.intro this) theorem dvd_of_mul_dvd_mul_right {a b c : A} (Ha : a ≠ 0) (Hdvd : (b * a ∣ c * a)) : (b ∣ c) := dvd.elim Hdvd (take d, suppose c * a = b * a * d, have b * d * a = c * a, from by rewrite [mul.right_comm, -this], have b * d = c, from eq_of_mul_eq_mul_right Ha this, dvd.intro this) end namespace norm_num local attribute bit0 bit1 add1 [reducible] local attribute right_distrib left_distrib [simp] theorem mul_zero [mul_zero_class A] (a : A) : a * zero = zero := by simp theorem zero_mul [mul_zero_class A] (a : A) : zero * a = zero := by simp theorem mul_one [monoid A] (a : A) : a * one = a := by simp theorem mul_bit0 [distrib A] (a b : A) : a * (bit0 b) = bit0 (a * b) := by simp theorem mul_bit0_helper [distrib A] (a b t : A) (H : a * b = t) : a * (bit0 b) = bit0 t := by rewrite -H; simp theorem mul_bit1 [semiring A] (a b : A) : a * (bit1 b) = bit0 (a * b) + a := by simp theorem mul_bit1_helper [semiring A] (a b s t : A) (Hs : a * b = s) (Ht : bit0 s + a = t) : a * (bit1 b) = t := by simp theorem subst_into_prod [has_mul A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by simp theorem mk_cong (op : A → A) (a b : A) (H : a = b) : op a = op b := by simp theorem neg_add_neg_eq_of_add_add_eq_zero [add_comm_group A] (a b c : A) (H : c + a + b = 0) : -a + -b = c := begin apply add_neg_eq_of_eq_add, apply neg_eq_of_add_eq_zero, simp end theorem neg_add_neg_helper [add_comm_group A] (a b c : A) (H : a + b = c) : -a + -b = -c := begin apply iff.mp !neg_eq_neg_iff_eq, simp end theorem neg_add_pos_eq_of_eq_add [add_comm_group A] (a b c : A) (H : b = c + a) : -a + b = c := begin apply neg_add_eq_of_eq_add, simp end theorem neg_add_pos_helper1 [add_comm_group A] (a b c : A) (H : b + c = a) : -a + b = -c := begin apply neg_add_eq_of_eq_add, apply eq_add_neg_of_add_eq H end theorem neg_add_pos_helper2 [add_comm_group A] (a b c : A) (H : a + c = b) : -a + b = c := begin apply neg_add_eq_of_eq_add, rewrite H end theorem pos_add_neg_helper [add_comm_group A] (a b c : A) (H : b + a = c) : a + b = c := by simp theorem sub_eq_add_neg_helper [add_comm_group A] (t₁ t₂ e w₁ w₂: A) (H₁ : t₁ = w₁) (H₂ : t₂ = w₂) (H : w₁ + -w₂ = e) : t₁ - t₂ = e := by simp theorem pos_add_pos_helper [add_comm_group A] (a b c h₁ h₂ : A) (H₁ : a = h₁) (H₂ : b = h₂) (H : h₁ + h₂ = c) : a + b = c := by simp theorem subst_into_subtr [add_group A] (l r t : A) (prt : l + -r = t) : l - r = t := by simp theorem neg_neg_helper [add_group A] (a b : A) (H : a = -b) : -a = b := by simp theorem neg_mul_neg_helper [ring A] (a b c : A) (H : a * b = c) : (-a) * (-b) = c := by simp theorem neg_mul_pos_helper [ring A] (a b c : A) (H : a * b = c) : (-a) * b = -c := by simp theorem pos_mul_neg_helper [ring A] (a b c : A) (H : a * b = c) : a * (-b) = -c := by simp end norm_num attribute [simp] zero_mul mul_zero at simplifier.unit attribute [simp] neg_mul_eq_neg_mul_symm mul_neg_eq_neg_mul_symm at simplifier.neg attribute [simp] left_distrib right_distrib at simplifier.distrib
1d848768c5c771e42d8f0b9caf7bbf98ff9f2bf6
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/algebra/ordered.lean
8f27db8ee0bfcadedb7e0ab734f56d0039de20b1
[ "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
61,055
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 order.liminf_limsup import data.set.intervals import topology.algebra.group import topology.constructions /-! # Theory of ordered topology ## Main definitions `ordered_topology` and `orderable_topology` TODO expand ## Main statements This file contains the proofs of the following facts: * all intervals `I??` are connected, * Intermediate Value Theorem, both for connected sets and `Icc` intervals, * Extreme Value Theorem: a continuous function on a compact set takes its maximum value. TODO expand -/ open classical set lattice filter topological_space open_locale topological_space classical universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- (Partially) ordered topology Also called: partially ordered spaces (pospaces). Usually ordered topology is used for a topology on linear ordered spaces, where the open intervals are open sets. This is a generalization as for each linear order where open interals are open sets, the order relation is closed. -/ class ordered_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed (λp:α×α, p.1 ≤ p.2)) instance : Π [topological_space α], topological_space (order_dual α) := id section ordered_topology section preorder variables [topological_space α] [preorder α] [t : ordered_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_Iic {a : α} : is_closed (Iic a) := is_closed_le' a lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id lemma is_closed_Ici {a : α} : is_closed (Ici a) := is_closed_ge' a instance : ordered_topology (order_dual α) := ⟨continuous_swap _ (@ordered_topology.is_closed_le' α _ _ _)⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter is_closed_Ici is_closed_Iic lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥) (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : {b | f b ≤ g b} ∈ b) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from mem_of_closed_of_tendsto hb this t.is_closed_le' h lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (𝓝 a)) (h : f ⁻¹' {c | c ≤ b} ∈ x) : a ≤ b := le_of_tendsto_of_tendsto nt lim tendsto_const_nhds h lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (𝓝 a)) (h : f ⁻¹' {c | b ≤ c} ∈ x) : b ≤ a := le_of_tendsto_of_tendsto nt tendsto_const_nhds lim h @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := closure_eq_iff_is_closed.mpr $ is_closed_le hf hg lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b < g b} ⊆ {b | f b ≤ g b} := by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) } end preorder section partial_order variables [topological_space α] [partial_order α] [t : ordered_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) @[priority 100] -- see Note [lower instance priority] instance ordered_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [ordered_topology α] lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf lemma is_open_Iio {a : α} : is_open (Iio a) := is_open_lt continuous_id continuous_const lemma is_open_Ioi {a : α} : is_open (Ioi a) := is_open_lt continuous_const continuous_id lemma is_open_Ioo {a b : α} : is_open (Ioo a b) := is_open_inter is_open_Ioi is_open_Iio lemma is_connected.forall_Icc_subset {s : set α} (hs : is_connected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := begin assume x hx, obtain ⟨y, hy, hy'⟩ : (s ∩ ((Iic x) ∩ (Ici x))).nonempty, from is_connected_closed_iff.1 hs (Iic x) (Ici x) is_closed_Iic is_closed_Ici (λ y _, le_total y x) ⟨a, ha, hx.1⟩ ⟨b, hb, hx.2⟩, exact le_antisymm hy'.1 hy'.2 ▸ hy end /-- Intermediate Value Theorem for continuous functions on connected sets. -/ lemma is_connected.intermediate_value {γ : Type*} [topological_space γ] {s : set γ} (hs : is_connected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α} (hf : continuous_on f s) : Icc (f a) (f b) ⊆ f '' s := (hs.image f hf).forall_Icc_subset (mem_image_of_mem f ha) (mem_image_of_mem f hb) /-- Intermediate Value Theorem for continuous functions on connected spaces. -/ lemma intermediate_value_univ {γ : Type*} [topological_space γ] [H : connected_space γ] (a b : γ) {f : γ → α} (hf : continuous f) : Icc (f a) (f b) ⊆ range f := @image_univ _ _ f ▸ H.is_connected_univ.intermediate_value trivial trivial hf.continuous_on end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [t : ordered_topology α] {f g : β → α} include t section variables [topological_space β] (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := begin rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg], rintros b ⟨hb₁, hb₂⟩, refine le_antisymm hb₁ (closure_lt_subset_le hg hf _), convert hb₂ using 2, simp only [not_le.symm], refl end lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous.max : continuous (λb, max (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, g b = f b, from assume b hb, (frontier_le_subset_eq hf hg hb).symm, continuous_if this hg hf lemma continuous.min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg end lemma tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (max a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_fst.max continuous_snd) _ end (hf.prod_mk hg) lemma tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (min a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_fst.min continuous_snd) _ end (hf.prod_mk hg) end decidable_linear_order end ordered_topology /-- Topologies generated by the open intervals. This is restricted to linear orders. Only then it is guaranteed that they are also a ordered topology. -/ class orderable_topology (α : Type*) [t : topological_space α] [partial_order α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a}) section orderable_topology instance {α : Type*} [topological_space α] [partial_order α] [orderable_topology α] : orderable_topology (order_dual α) := ⟨by convert @orderable_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : orderable_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : {b | a < b} ∈ 𝓝 b := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : {b | a ≤ b} ∈ 𝓝 b := (𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : {a | a < b} ∈ 𝓝 a := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : {a | a ≤ b} ∈ 𝓝 a := (𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_orderable (a : α) : 𝓝 a = (⨅b ∈ Iio a, principal (Ioi b)) ⊓ (⨅b ∈ Ioi a, principal (Iio b)) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_orderable {f : β → α} {a : α} {x : filter β} : tendsto f x (𝓝 a) ↔ (∀a'<a, {b | a' < f b} ∈ x) ∧ (∀a'>a, {b | a' > f b} ∈ x) := by simp [nhds_eq_orderable a, tendsto_inf, tendsto_infi, tendsto_principal] /-- Also known as squeeze or sandwich theorem. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : {b | g b ≤ f b} ∈ b) (hfh : {b | f b ≤ h b} ∈ b) : tendsto f b (𝓝 a) := tendsto_orderable.2 ⟨assume a' h', have {b : β | a' < g b} ∈ b, from (tendsto_orderable.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have {b : β | h b < a'} ∈ b, from (tendsto_orderable.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ lemma nhds_orderable_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : 𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal (Ioo l u)) := let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in calc 𝓝 a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) : nhds_eq_orderable a ... = (⨅b<a, principal {c | b < c} ⊓ (⨅b>a, principal {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, principal {c | c < u} ⊓ principal {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_orderable_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → {b | l < f b ∧ f b < u } ∈ x) : tendsto f x (𝓝 a) := by rw [nhds_orderable_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_orderable_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @orderable_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_orderable (f a)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_orderable_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @orderable_topology _ (induced f ta) _ := induced_orderable_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) lemma nhds_top_orderable [topological_space α] [order_top α] [orderable_topology α] : 𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), principal (Ioi l)) := by simp [nhds_eq_orderable (⊤:α)] lemma nhds_bot_orderable [topological_space α] [order_bot α] [orderable_topology α] : 𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), principal (Iio l)) := by simp [nhds_eq_orderable (⊥:α)] section linear_order variables [topological_space α] [linear_order α] [t : orderable_topology α] include t lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) : ∃ l' ∈ Ico l a, Ioc l' a ⊆ s := begin rw [nhds_eq_orderable a] at hs, rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩, -- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁` suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁, { have A : principal (Iic a) ≤ ⨅ b ∈ Ioi a, principal (Iio b), from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb), have B : t₁ ∩ Iic a ⊆ s, from subset.trans (inter_subset_inter_right _ (A ht₂)) hts, from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) }, clear hts ht₂ t₂, -- Now we find `l` such that `(l', ∞) ⊆ t₁` letI := classical.DLO α, rw [mem_binfi, mem_bUnion_iff] at ht₁, { rcases ht₁ with ⟨b, hb, hb'⟩, exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩, λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ }, { intros b hb b' hb', simp only [mem_Iio] at hb hb', use [max b b', max_lt hb hb'], simp [le_refl] }, exact ⟨l, hl⟩ end lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) : ∃ u' ∈ Ioc a u, Ico a u' ⊆ s := begin convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu, ext, rw [dual_Ico, dual_Ioc] end lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) : ∃ l < a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩ lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) : ∃ u (_ : a < u), Ico a u ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩ lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ 𝓝 a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have 𝓝 a = (⨅p : {l // l < a} × {u // a < u}, principal (Ioo p.1.val p.2.val)), by simp [nhds_orderable_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete a₁ a₂ with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end @[priority 100] -- see Note [lower instance priority] instance orderable_topology.to_ordered_topology : ordered_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } lemma orderable_topology.t2_space : t2_space α := by apply_instance @[priority 100] -- see Note [lower instance priority] instance orderable_topology.regular_space : regular_space α := { regular := assume s a hs ha, have hs' : -s ∈ 𝓝 a, from mem_nhds_sets hs ha, have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝 a ⊓ principal t = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in match dense_or_discrete l a with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝 a ⊓ principal t = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in match dense_or_discrete a u with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [←sup_principal, inf_sup_left, ht₁a, ht₂a, bot_sup_eq]⟩, ..orderable_topology.t2_space } /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`, provided `a` is neither a bottom element nor a top element. -/ lemma mem_nhds_iff_exists_Ioo_subset' {a l' u' : α} {s : set α} (hl' : l' < a) (hu' : a < u') : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := begin split, { assume h, rcases exists_Ico_subset_of_mem_nhds' h hu' with ⟨u, au, hu⟩, rcases exists_Ioc_subset_of_mem_nhds' h hl' with ⟨l, la, hl⟩, refine ⟨l, u, ⟨la.2, au.1⟩, λx hx, _⟩, cases le_total a x with hax hax, { exact hu ⟨hax, hx.2⟩ }, { exact hl ⟨hx.1, hax⟩ } }, { rintros ⟨l, u, ha, h⟩, apply mem_sets_of_superset (mem_nhds_sets is_open_Ioo ha) h } end /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`. -/ lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := let ⟨l', hl'⟩ := no_bot a in let ⟨u', hu'⟩ := no_top a in mem_nhds_iff_exists_Ioo_subset' hl' hu' /-! ### Neighborhoods to the left and to the right Limits to the left and to the right of real functions are defined in terms of neighborhoods to the left and to the right, either open or closed, i.e., members of `nhds_within a (Ioi a)` and `nhds_wihin a (Ici a)` on the right, and similarly on the left. Such neighborhoods can be characterized as the sets containing suitable intervals to the right or to the left of `a`. We give now these characterizations. -/ /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ nhds_within a (Ioi a) ↔ ∃u, a < u ∧ Ioo a u ⊆ s := begin split, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds va ⟨u', hu'⟩ with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨_, hx.1⟩, exact hu ⟨le_of_lt hx.1, hx.2⟩ }, { rintros ⟨u, au, hu⟩, rw mem_nhds_within_iff_exists_mem_nhds_inter, refine ⟨Iio u, mem_nhds_sets is_open_Iio au, _⟩, rwa [inter_comm, Ioi_inter_Iio] } end /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} : s ∈ nhds_within a (Ioi a) ↔ ∃u, a < u ∧ Ioo a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu' /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ nhds_within a (Ioi a) ↔ ∃u, a < u ∧ Ioc a u ⊆ s := begin rw mem_nhds_within_Ioi_iff_exists_Ioo_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ } end /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ nhds_within a (Iio a) ↔ ∃l, l < a ∧ Ioo l a ⊆ s := begin split, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ioc_subset_of_mem_nhds va ⟨l', hl'⟩ with ⟨l, la, hl⟩, refine ⟨l, la, λx hx, _⟩, refine hv ⟨_, hx.2⟩, exact hl ⟨hx.1, le_of_lt hx.2⟩ }, { rintros ⟨l, la, ha⟩, rw mem_nhds_within_iff_exists_mem_nhds_inter, refine ⟨Ioi l, mem_nhds_sets is_open_Ioi la, _⟩, rwa [Ioi_inter_Iio] } end /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} : s ∈ nhds_within a (Iio a) ↔ ∃l, l < a ∧ Ioo l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ nhds_within a (Iio a) ↔ ∃l, l < a ∧ Ico l a ⊆ s := begin rw mem_nhds_within_Iio_iff_exists_Ioo_subset, split, { rintros ⟨l, la, as⟩, rcases dense la with ⟨v, hv⟩, refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, }, { rintros ⟨l, la, as⟩, exact ⟨l, la, subset.trans Ioo_subset_Ico_self as⟩ } end /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ nhds_within a (Ici a) ↔ ∃u, a < u ∧ Ico a u ⊆ s := begin split, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds va ⟨u', hu'⟩ with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨_, hx.1⟩, exact hu hx }, { rintros ⟨u, au, hu⟩, rw mem_nhds_within_iff_exists_mem_nhds_inter, refine ⟨Iio u, mem_nhds_sets is_open_Iio au, _⟩, rwa [inter_comm, Ici_inter_Iio] } end /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} : s ∈ nhds_within a (Ici a) ↔ ∃u, a < u ∧ Ico a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu' /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ nhds_within a (Ici a) ↔ ∃u, a < u ∧ Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ nhds_within a (Iic a) ↔ ∃l, l < a ∧ Ioc l a ⊆ s := begin split, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ioc_subset_of_mem_nhds va ⟨l', hl'⟩ with ⟨l, la, hl⟩, refine ⟨l, la, λx hx, _⟩, refine hv ⟨_, hx.2⟩, exact hl hx }, { rintros ⟨l, la, ha⟩, rw mem_nhds_within_iff_exists_mem_nhds_inter, refine ⟨Ioi l, mem_nhds_sets is_open_Ioi la, _⟩, rwa [Ioi_inter_Iic] } end /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} : s ∈ nhds_within a (Iic a) ↔ ∃l, l < a ∧ Ioc l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ nhds_within a (Iic a) ↔ ∃l, l < a ∧ Icc l a ⊆ s := begin rw mem_nhds_within_Iic_iff_exists_Ioc_subset, split, { rintros ⟨l, la, as⟩, rcases dense la with ⟨v, hv⟩, refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, }, { rintros ⟨l, la, as⟩, exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ } end end linear_order lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_comm_group α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg) $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : mono_image $ image_closure_subset_closure_image continuous_neg ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [orderable_topology α] [orderable_topology β] lemma nhds_principal_ne_bot_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : 𝓝 a ⊓ principal s ≠ ⊥ := let ⟨a', ha'⟩ := exists_mem_of_ne_empty hs in forall_sets_neq_empty_iff_neq_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ne_empty_iff_exists_mem.mpr ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := exists_Ioc_subset_of_mem_nhds ht₁ ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ ⟨‹l < a'›, ha.left ha'⟩, ne_empty_iff_exists_mem.mpr ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma nhds_principal_ne_bot_of_is_glb : ∀ {a : α} {s : set α}, is_glb s a → s ≠ ∅ → 𝓝 a ⊓ principal s ≠ ⊥ := @nhds_principal_ne_bot_of_is_lub (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) (hfa : f ⊓ 𝓝 a ≠ ⊥) : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := inhabited_of_mem_sets hfa this in have b < b, from lt_of_lt_of_le hxb $ hb hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → f ⊓ 𝓝 a ≠ ⊥ → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s ≠ ∅) (hb : tendsto f (𝓝 a ⊓ principal s) (𝓝 b)) : is_lub (f '' s) b := have hnbot : (𝓝 a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have {x | x < f a'} ∈ 𝓝 b, from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left ha') h.symm, have {x | a' < x} ∈ 𝓝 a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ 𝓝 a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ 𝓝 a ⊓ principal s, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', le_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' $ mem_image_of_mem _ hx) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s ≠ ∅ → tendsto f (𝓝 a ⊓ principal s) (𝓝 b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s ≠ ∅ → tendsto f (𝓝 a ⊓ principal s) (𝓝 b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s ≠ ∅ → tendsto f (𝓝 a ⊓ principal s) (𝓝 b) → is_lub (f '' s) b := @is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_lub ha hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) (sc : is_closed s) : a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_glb ha hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) (sc : is_closed s) : a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma bdd_below_of_compact {α : Type u} [topological_space α] [linear_order α] [ordered_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _ with ⟨t, st, ft, ht⟩, { refine H ((bdd_below_finite ft).imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma bdd_above_of_compact {α : Type u} [topological_space α] [linear_order α] [orderable_topology α] : Π [nonempty α] {s : set α}, compact s → bdd_above s := @bdd_below_of_compact (order_dual α) _ _ _ end order_topology section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [orderable_topology α] [densely_ordered α] /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top element. -/ lemma closure_Ioi' {a b : α} (hab : a < b) : closure (Ioi a) = Ici a := begin apply subset.antisymm, { rw ← closure_eq_iff_is_closed.2 is_closed_Ici, exact closure_mono Ioi_subset_Ici_self, apply_instance }, { assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_glb is_glb_Ioi (ne_empty_of_mem hab) }, { exact subset_closure (lt_of_le_of_ne hx (ne.symm h)) } } end /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/ lemma closure_Ioi (a : α) [no_top_order α] : closure (Ioi a) = Ici a := let ⟨b, hb⟩ := no_top a in closure_Ioi' hb /-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom element. -/ lemma closure_Iio' {a b : α} (hab : b < a) : closure (Iio a) = Iic a := begin apply subset.antisymm, { rw ← closure_eq_iff_is_closed.2 is_closed_Iic, exact closure_mono Iio_subset_Iic_self, apply_instance }, { assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_lub is_lub_Iio (ne_empty_of_mem hab) }, { apply subset_closure, by simpa [h] using lt_or_eq_of_le hx } } end /-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/ lemma closure_Iio (a : α) [no_bot_order α] : closure (Iio a) = Iic a := let ⟨b, hb⟩ := no_bot a in closure_Iio' hb /-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/ lemma closure_Ioo {a b : α} (hab : a < b) : closure (Ioo a b) = Icc a b := begin apply subset.antisymm, { rw ← closure_eq_iff_is_closed.2 is_closed_Icc, exact closure_mono Ioo_subset_Icc_self, apply_instance }, { have ne_empty : Ioo a b ≠ ∅, by simpa [Ioo_eq_empty_iff], assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_glb (is_glb_Ioo hab) ne_empty }, by_cases h' : x = b, { rw h', refine mem_closure_of_is_lub (is_lub_Ioo hab) ne_empty }, exact subset_closure ⟨lt_of_le_of_ne hx.1 (ne.symm h), by simpa [h'] using lt_or_eq_of_le hx.2⟩ } end /-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/ lemma closure_Ioc {a b : α} (hab : a < b) : closure (Ioc a b) = Icc a b := begin apply subset.antisymm, { rw ← closure_eq_iff_is_closed.2 is_closed_Icc, exact closure_mono Ioc_subset_Icc_self, apply_instance }, { apply subset.trans _ (closure_mono Ioo_subset_Ioc_self), rw closure_Ioo hab } end /-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/ lemma closure_Ico {a b : α} (hab : a < b) : closure (Ico a b) = Icc a b := begin apply subset.antisymm, { rw ← closure_eq_iff_is_closed.2 is_closed_Icc, exact closure_mono Ico_subset_Icc_self, apply_instance }, { apply subset.trans _ (closure_mono Ioo_subset_Ico_self), rw closure_Ioo hab } end end decidable_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] [complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Sup s ∈ closure s := mem_closure_of_is_lub is_lub_Sup hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Inf s ∈ closure s := mem_closure_of_is_glb is_glb_Inf hs lemma Sup_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed is_lub_Sup hs hc lemma Inf_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed is_glb_Inf hs hc /-- A continuous monotone function sends supremum to supremum for nonempty sets. -/ lemma Sup_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_iff_Sup_eq.1 (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Cf xy) is_lub_Sup hs $ tendsto_le_left inf_le_left (Mf.tendsto _))).symm /-- A continuous monotone function sending bot to bot sends supremum to supremum. -/ lemma Sup_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (fbot : f ⊥ = ⊥) {s : set α} : f (Sup s) = Sup (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Sup_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed supremum to indexed supremum. -/ lemma supr_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (supr g) = supr (f ∘ g) := by rw [supr, Sup_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum for nonempty sets. -/ lemma Inf_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Inf s) = Inf (f '' s) := (is_glb_iff_Inf_eq.1 (is_glb_of_is_glb_of_tendsto (λ x hx y hy xy, Cf xy) is_glb_Inf hs $ tendsto_le_left inf_le_left (Mf.tendsto _))).symm /-- A continuous monotone function sending top to top sends infimum to infimum. -/ lemma Inf_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (ftop : f ⊤ = ⊤) {s : set α} : f (Inf s) = Inf (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Inf_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed infimum to indexed infimum. -/ lemma infi_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (infi g) = infi (f ∘ g) := by rw [infi, Inf_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] [conditionally_complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma cSup_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma cSup_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma cInf_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- A continuous monotone function sends supremum to supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma cSup_of_cSup_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine (is_lub_iff_eq_of_is_lub _).1 (is_lub_cSup (mt image_eq_empty.1 ne) (bdd_above_of_bdd_above_of_monotone Cf H)), refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Cf xy) (is_lub_cSup ne H) ne _, exact tendsto_le_left inf_le_left (Mf.tendsto _) end /-- A continuous monotone function sends indexed supremum to indexed supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma csupr_of_csupr_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_above (range g)) : f (supr g) = supr (f ∘ g) := by rw [supr, cSup_of_cSup_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cInf_of_cInf_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := begin refine (is_glb_iff_eq_of_is_glb _).1 (is_glb_cInf (mt image_eq_empty.1 ne) (bdd_below_of_bdd_below_of_monotone Cf H)), refine is_glb_of_is_glb_of_tendsto (λx hx y hy xy, Cf xy) (is_glb_cInf ne H) ne _, exact tendsto_le_left inf_le_left (Mf.tendsto _) end /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cinfi_of_cinfi_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_below (range g)) : f (infi g) = infi (f ∘ g) := by rw [infi, cInf_of_cInf_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl section densely_ordered variables [densely_ordered α] {a b : α} lemma is_connected_Icc : is_connected (Icc a b) := is_connected_closed_iff.2 begin rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩, wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s], -- `c = Sup (Icc x y ∩ s)` belongs to `Icc a b`, `s`, and `t`. -- First two statements follow from general properties of `cSup` let S := Icc x y ∩ s, have xS : x ∈ S, from ⟨left_mem_Icc.2 hxy, hx.2⟩, have Sne : S ≠ ∅, from ne_empty_iff_nonempty.2 ⟨x, xS⟩, have Sbd : bdd_above S, from ⟨y, λ z hz, hz.1.2⟩, let c := Sup S, have c_mem : c ∈ S, from cSup_mem_of_is_closed Sne (is_closed_inter is_closed_Icc hs) Sbd, have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2, have Sab : S ⊆ Icc a b := subset.trans (inter_subset_left _ _) xyab, refine ⟨c, Sab c_mem, c_mem.2, _⟩, -- Now we need to prove `c ∈ t`; we deduce it from `Ioc c y ⊆ (s ∪ t) \ s ⊆ t` cases eq_or_lt_of_le c_mem.1.2 with hcy hcy, { exact hcy.symm ▸ hy.2 }, suffices : Icc c y ⊆ t, from this (left_mem_Icc.2 (le_of_lt hcy)), rw [← closure_Ioc hcy, closure_subset_iff_subset_of_is_closed ht], intros z hz, have z_mem : z ∈ Icc x y, from Icc_subset_Icc_left c_mem.1.1 (Ioc_subset_Icc_self hz), suffices : z ∈ t \ s, from and.left this, rw [← union_diff_left], exact ⟨hab $ xyab z_mem, λ zs, not_lt_of_le (le_cSup Sbd ⟨z_mem, zs⟩) hz.1⟩ end lemma is_connected_iff_forall_Icc_subset {s : set α} : is_connected s ↔ ∀ x y ∈ s, x ≤ y → Icc x y ⊆ s := ⟨λ h x y hx hy hxy, h.forall_Icc_subset hx hy, λ h, is_connected_of_forall_pair $ λ x y hx hy, ⟨Icc (min x y) (max x y), h (min x y) (max x y) ((min_choice x y).elim (λ h', by rwa h') (λ h', by rwa h')) ((max_choice x y).elim (λ h', by rwa h') (λ h', by rwa h')) min_le_max, ⟨min_le_left x y, le_max_left x y⟩, ⟨min_le_right x y, le_max_right x y⟩, is_connected_Icc⟩⟩ lemma is_connected_Ici : is_connected (Ici a) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ici_iff hxy).2 hx lemma is_connected_Iic : is_connected (Iic a) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Iic_iff hxy).2 hy lemma is_connected_Iio : is_connected (Iio a) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Iio_iff hxy).2 hy lemma is_connected_Ioi : is_connected (Ioi a) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ioi_iff hxy).2 hx lemma is_connected_Ioo : is_connected (Ioo a b) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ioo_iff hxy).2 ⟨hx.1, hy.2⟩ lemma is_connected_Ioc : is_connected (Ioc a b) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ioc_iff hxy).2 ⟨hx.1, hy.2⟩ lemma is_connected_Ico : is_connected (Ico a b) := is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, (Icc_subset_Ico_iff hxy).2 ⟨hx.1, hy.2⟩ @[priority 100] instance ordered_connected_space : connected_space α := ⟨is_connected_iff_forall_Icc_subset.2 $ λ x y hx hy hxy, subset_univ _⟩ /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/ lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) : Icc (f a) (f b) ⊆ f '' (Icc a b) := is_connected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/ lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) : Icc (f b) (f a) ⊆ f '' (Icc a b) := is_connected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf end densely_ordered /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma compact.exists_forall_le {α : Type u} [topological_space α] {s : set α} (hs : compact s) (ne_s : s ≠ ∅) (f : α → β) (hf : continuous_on f s) : ∃x∈s, ∀y∈s, f x ≤ f y := begin have C : compact (f '' s) := hs.image_of_continuous_on hf, haveI := has_Inf_to_nonempty β, have B : bdd_below (f '' s) := bdd_below_of_compact C, have : Inf (f '' s) ∈ f '' s := cInf_mem_of_is_closed (mt image_eq_empty.1 ne_s) (closed_of_compact _ C) B, rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩, exact ⟨x, xs, λ y hy, hx.symm ▸ cInf_le B ⟨_, hy, rfl⟩⟩ end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma compact.exists_forall_ge {α : Type u} [topological_space α]: ∀ {s : set α}, compact s → s ≠ ∅ → ∀ {f : α → β}, continuous_on f s → ∃x∈s, ∀y∈s, f y ≤ f x := @compact.exists_forall_le (order_dual β) _ _ _ _ _ end conditionally_complete_linear_order section liminf_limsup section ordered_topology variables [semilattice_sup α] [topological_space α] [orderable_topology α] lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, show {x : α | x ≤ a} ∈ 𝓝 a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma is_bounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u := is_bounded_of_le h (is_bounded_le_nhds a) lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_le_nhds a) lemma is_cobounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_le_of_tendsto h) end ordered_topology section ordered_topology variables [semilattice_inf α] [topological_space α] [orderable_topology α] lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) := match forall_le_or_exists_lt_inf a with | or.inl h := ⟨a, show {x : α | a ≤ x} ∈ 𝓝 a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, le_mem_nhds hb⟩ end lemma is_bounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u := is_bounded_of_le h (is_bounded_ge_nhds a) lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_ge_nhds a) lemma is_cobounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_ge_of_tendsto h) end ordered_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : {a | a < b} ∈ f := let ⟨c, (h : {a : α | a ≤ c} ∈ f), hcb⟩ := exists_lt_of_cInf_lt (ne_empty_iff_exists_mem.2 h) l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → f.Liminf > b → {a | a > b} ∈ f := @lt_mem_sets_of_Limsup_lt (order_dual α) _ variables [topological_space α] [orderable_topology α] /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ 𝓝 a := tendsto_orderable.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a := cInf_intro (ne_empty_iff_exists_mem.2 $ is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a), have hb_le : is_bounded (≤) f, from is_bounded_of_le h (is_bounded_le_nhds a), le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hf hb_le hb_ge ... ≤ (𝓝 a).Limsup : Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) (is_cobounded_of_is_bounded hf hb_le)) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α}, f ≠ ⊥ → f ≤ 𝓝 a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (h : liminf f u = a ∧ limsup f u = a) : tendsto u f (𝓝 a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot h.2 h.1 /-- If a function has a limit, then its limsup coincides with its limit-/ theorem limsup_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (𝓝 a)) : limsup f u = a := Limsup_eq_of_le_nhds (map_ne_bot hf) h /-- If a function has a limit, then its liminf coincides with its limit-/ theorem liminf_eq_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (𝓝 a)) : liminf f u = a := Liminf_eq_of_le_nhds (map_ne_bot hf) h end complete_linear_order end liminf_limsup end orderable_topology lemma orderable_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_comm_group α] [topological_space α] (h_nhds : ∀a:α, 𝓝 a = (⨅r>0, principal {b | abs (a - b) < r})) : orderable_topology α := orderable_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a + -b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, -sub_eq_add_neg, (sub_eq_add_neg _ _).symm, sub_lt, lt_sub_iff_add_lt, and_comm, sub_lt_iff_lt_add']), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_orderable.2 $ and.intro (assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩) (assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha)) lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 (⨅i, f i)) := @tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_supr_nat f hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 a) → infi f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_infi_nat f hf)
b0aaadfa22b071ec4bc7dfc8417c66f2d424d358
fef48cac17c73db8662678da38fd75888db97560
/src/for_mathlib/order.lean
7d68b6d226f9a7faeac462690637d03fb13f81f6
[]
no_license
kbuzzard/lean-squares-in-fibonacci
6c0d924f799d6751e19798bb2530ee602ec7087e
8cea20e5ce88ab7d17b020932d84d316532a84a8
refs/heads/master
1,584,524,504,815
1,582,387,156,000
1,582,387,156,000
134,576,655
3
1
null
1,541,538,497,000
1,527,083,406,000
Lean
UTF-8
Lean
false
false
5,446
lean
import data.nat.prime import data.pnat.basic import for_mathlib.exactly_divides open nat namespace order section raw_order variables (p : ℕ) (hp : p > 1) protected def order_core : Π (n : ℕ), n > 0 → {r // p^r ∣∣ n} | 0 := λ n_pos, absurd n_pos dec_trivial | n@(k+1) := λ n_pos, have n / p < n, from div_lt_self n_pos hp, if h : p ∣ n then have p * (n / p) = n, from nat.mul_div_cancel' h, let ⟨s, hs⟩ := order_core (n / p) (pos_of_mul_pos_left (this.symm ▸ n_pos : 0 < p * (n / p)) dec_trivial) in ⟨succ s, this ▸ (exactly_divides_succ (hp.trans dec_trivial)).mp hs⟩ else ⟨0, (exactly_divides_zero (hp.trans dec_trivial)).mp h⟩ def order (n : ℕ) (n_pos : n > 0) : ℕ := (order.order_core p hp n n_pos).val lemma exactly_divides_order (n : ℕ) (n_pos : n > 0) : p^(order p hp n n_pos) ∣∣ n := (order.order_core p hp n n_pos).property end raw_order /- XXX comments -/ instance : has_dvd ℕ+ := ⟨λ a b, a.val ∣ b.val⟩ def 𝓟 := {p : ℕ // prime p} notation `PP` := 𝓟 def 𝓟.gt_one (p : 𝓟) : p.val > 1 := p.property.one_lt def 𝓟.pos (p : 𝓟) : p.val > 0 := p.property.pos instance : has_coe 𝓟 ℕ+ := ⟨λ p, ⟨p.val, p.pos⟩⟩ def ord (p : 𝓟) (n : ℕ+) : ℕ := order p p.gt_one n n.property def exactly_divides_ord {p : 𝓟} {n : ℕ+} : p^(ord p n) ∣∣ n := exactly_divides_order p p.gt_one n n.property def exactly_divides_iff_ord {p : 𝓟} {r : ℕ} {n : ℕ+} : ord p n = r ↔ p^r ∣∣ n := iff.intro (λ e, e ▸ exactly_divides_ord) (exactly_divides_unique exactly_divides_ord) variable {p : 𝓟} -- Recursion (though we prove them in a round-about fashion) lemma ord_not_div {n : ℕ+} : ¬(↑p ∣ n) ↔ ord p n = 0 := (exactly_divides_zero p.pos).trans exactly_divides_iff_ord.symm lemma ord_div {n : ℕ+} : ord p (p * n) = succ (ord p n) := exactly_divides_iff_ord.mpr ((exactly_divides_succ p.pos).mp exactly_divides_ord) -- Multiplicative lemma ord_one : ord p 1 = 0 := exactly_divides_iff_ord.mpr (exactly_divides_one p.property) lemma ord_mul (a b : ℕ+) : ord p (a * b) = ord p a + ord p b := exactly_divides_iff_ord.mpr (exactly_divides_mul p.property exactly_divides_ord exactly_divides_ord) lemma ord_ppow {k : ℕ} {a : ℕ+} : ord p (a ^ k) = k * ord p a := begin apply exactly_divides_iff_ord.mpr, convert (exactly_divides_pow p.property exactly_divides_ord), simp, end lemma ord_pow {k : ℕ} {a : ℕ+} : ord p (a^k) = k * ord p a := ord_ppow -- Gcd /- def pgcd (a b : ℕ+) : ℕ+ := ⟨gcd a b, gcd_pos_of_pos_left b a.pos⟩ --set_option pp.notation false @[simp] lemma pgcd_coe_something (a b : ℕ) : pgcd a b = gcd a b := begin unfold pgcd, --rw pnat.coe_nat_coe a, -- I am so rubbish at coe sorry end --#print notation ℕ∞ lemma ord_pgcd {a b : ℕ+} : ord p (pgcd a b) = min (ord p a) (ord p b) := exactly_divides_iff_ord.mpr (exactly_divides_gcd exactly_divides_ord exactly_divides_ord) lemma ord_gcd {a b : ℕ+} : ord p (gcd a b) = min (ord p a) (ord p b) := have pgcd a b = gcd a b, from (pnat.coe_nat_coe _).symm, this ▸ ord_pgcd instance pnat.has_le : has_le (ℕ+) := ⟨λ a b, a.1 ≤ b.1⟩ -- Addition -- ord_mul : ∀ {p : PP} (a b : ℕ+), ord p (a * b) = ord p a + ord p b lemma ord_le_mul_right (a b : ℕ+) : ord p a ≤ ord p (a * b) := begin have H : ∀ a b c : ℕ+, a = b + c → b ≤ a := sorry, --refine H _ _ _ (ord_mul a b) -- error sorry end --set_option pp.all true --set_option pp.notation false lemma ord_add {a b : ℕ+} : ord p (a + b) ≥ min (ord p a) (ord p b) := begin --have H (a b : ℕ+) : gcd a b ∣ (a + b) := sorry, have H : ∀ (a b : ℕ+), gcd a b ∣ (a + b) := λ a b, (nat.dvd_add_iff_left (gcd_dvd_right _ _)).1 (gcd_dvd_left _ _), rw ←ord_gcd, have H3 : ord p (a + b) ≥ ord p (pgcd a b) := sorry, have H2 := H a b, suffices : H3 = (ord p (a + b) ≥ ord p ↑(gcd ↑a ↑b)), -- now need to uncast to use H2? cases H2 with d Hd, /- Hd : @eq.{1} nat (@has_add.add.{0} nat nat.has_add (@coe.{1 1} pnat nat (@coe_to_lift.{1 1} pnat nat (@coe_base.{1 1} pnat nat coe_pnat_nat)) a) (@coe.{1 1} pnat nat (@coe_to_lift.{1 1} pnat nat (@coe_base.{1 1} pnat nat coe_pnat_nat)) b)) (@has_mul.mul.{0} nat (@mul_zero_class.to_has_mul.{0} nat (@semiring.to_mul_zero_class.{0} nat (@comm_semiring.to_semiring.{0} nat nat.comm_semiring))) (nat.gcd (@coe.{1 1} pnat nat (@coe_to_lift.{1 1} pnat nat (@coe_base.{1 1} pnat nat coe_pnat_nat)) a) (@coe.{1 1} pnat nat (@coe_to_lift.{1 1} pnat nat (@coe_base.{1 1} pnat nat coe_pnat_nat)) b)) d) ⊢ @ge.{0} nat nat.has_le (order.ord p (@has_add.add.{0} pnat pnat.has_add a b)) (order.ord p (@coe.{1 1} nat pnat (@coe_to_lift.{1 1} nat pnat (@coe_base.{1 1} nat pnat coe_nat_pnat)) (nat.gcd (@coe.{1 1} pnat nat (@coe_to_lift.{1 1} pnat nat (@coe_base.{1 1} pnat nat coe_pnat_nat)) a) (@coe.{1 1} pnat nat (@coe_to_lift.{1 1} pnat nat (@coe_base.{1 1} pnat nat coe_pnat_nat)) b)))) -/ change a + b = _ at Hd, --have H2 : ord p (gcd a b) ≥ min (ord p a) (ord p b), -- it's ord_gcd sorry, end #exit begin intros a b, refine (nat.dvd_add_iff_left _).1 _, exact gcd_dvd_right _ _, exact gcd_dvd_left _ _ -- end, sorry end #check @nat.dvd_add_iff_left -/ end order
fce64952f9ff9211dd2088aeaaa08b1443bdc82c
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.27.lean
5be80356bca02bd5583964e16f8d88e3166eb4d2
[]
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
363
lean
import standard -- BEGIN variables p q : Prop example : p ∧ q ↔ q ∧ p := begin apply iff.intro, begin intro H, have Hp : p, from and.left H, have Hq : q, from and.right H, apply and.intro, repeat assumption end, begin intro H, have Hp : p, begin apply and.right, apply H end, have Hq : q, by apply and.left; exact H, apply (and.intro Hp Hq) end end -- END
46ecc2c259c7e72e8604eab0af7c026c40f2476f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/root.lean
9eacc12c4b8367db63468534c3b53f8ee50588a8
[ "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
208
lean
def x := 10 namespace Foo def x := true #check x #check _root_.x theorem ex1 : x = true := rfl theorem ex2 : _root_.x = 10 := rfl end Foo theorem ex3 : x = 10 := rfl theorem ex4 : _root_.x = 10 := rfl
ff0d964f9a75387d3d411736f5e2fda5165257d0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/BuiltinTerm.lean
31516619b0f188811f4378864202541989e84122
[ "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
14,556
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Open import Lean.Elab.SetOption import Lean.Elab.Eval namespace Lean.Elab.Term open Meta @[builtin_term_elab «prop»] def elabProp : TermElab := fun _ _ => return mkSort levelZero private def elabOptLevel (stx : Syntax) : TermElabM Level := if stx.isNone then pure levelZero else elabLevel stx[0] @[builtin_term_elab «sort»] def elabSort : TermElab := fun stx _ => return mkSort (← elabOptLevel stx[1]) @[builtin_term_elab «type»] def elabTypeStx : TermElab := fun stx _ => return mkSort (mkLevelSucc (← elabOptLevel stx[1])) /-! the method `resolveName` adds a completion point for it using the given expected type. Thus, we propagate the expected type if `stx[0]` is an identifier. It doesn't "hurt" if the identifier can be resolved because the expected type is not used in this case. Recall that if the name resolution fails a synthetic sorry is returned.-/ @[builtin_term_elab «pipeCompletion»] def elabPipeCompletion : TermElab := fun stx expectedType? => do let e ← elabTerm stx[0] none unless e.isSorry do addDotCompletionInfo stx e expectedType? throwErrorAt stx[1] "invalid field notation, identifier or numeral expected" @[builtin_term_elab «completion»] def elabCompletion : TermElab := fun stx expectedType? => do /- `ident.` is ambiguous in Lean, we may try to be completing a declaration name or access a "field". -/ if stx[0].isIdent then /- If we can elaborate the identifier successfully, we assume it is a dot-completion. Otherwise, we treat it as identifier completion with a dangling `.`. Recall that the server falls back to identifier completion when dot-completion fails. -/ let s ← saveState try let e ← elabTerm stx[0] none addDotCompletionInfo stx e expectedType? catch _ => s.restore addCompletionInfo <| CompletionInfo.id stx stx[0].getId (danglingDot := true) (← getLCtx) expectedType? throwErrorAt stx[1] "invalid field notation, identifier or numeral expected" else elabPipeCompletion stx expectedType? @[builtin_term_elab «hole»] def elabHole : TermElab := fun stx expectedType? => do let kind := if (← read).inPattern || !(← read).holesAsSyntheticOpaque then MetavarKind.natural else MetavarKind.syntheticOpaque let mvar ← mkFreshExprMVar expectedType? kind registerMVarErrorHoleInfo mvar.mvarId! stx pure mvar @[builtin_term_elab «syntheticHole»] def elabSyntheticHole : TermElab := fun stx expectedType? => do let arg := stx[1] let userName := if arg.isIdent then arg.getId else Name.anonymous let mkNewHole : Unit → TermElabM Expr := fun _ => do let kind := if (← read).inPattern then MetavarKind.natural else MetavarKind.syntheticOpaque let mvar ← mkFreshExprMVar expectedType? kind userName registerMVarErrorHoleInfo mvar.mvarId! stx return mvar if userName.isAnonymous || (← read).inPattern then mkNewHole () else match (← getMCtx).findUserName? userName with | none => mkNewHole () | some mvarId => let mvar := mkMVar mvarId let mvarDecl ← getMVarDecl mvarId let lctx ← getLCtx if mvarDecl.lctx.isSubPrefixOf lctx then return mvar else match (← getExprMVarAssignment? mvarId) with | some val => let val ← instantiateMVars val if (← MetavarContext.isWellFormed lctx val) then return val else withLCtx mvarDecl.lctx mvarDecl.localInstances do throwError "synthetic hole has already been defined and assigned to value incompatible with the current context{indentExpr val}" | none => if (← mvarId.isDelayedAssigned) then -- We can try to improve this case if needed. throwError "synthetic hole has already beend defined and delayed assigned with an incompatible local context" else if lctx.isSubPrefixOf mvarDecl.lctx then let mvarNew ← mkNewHole () mvarId.assign mvarNew return mvarNew else throwError "synthetic hole has already been defined with an incompatible local context" @[builtin_term_elab «letMVar»] def elabLetMVar : TermElab := fun stx expectedType? => do match stx with | `(let_mvar% ? $n := $e; $b) => match (← getMCtx).findUserName? n.getId with | some _ => throwError "invalid 'let_mvar%', metavariable '?{n.getId}' has already been used" | none => let e ← elabTerm e none let mvar ← mkFreshExprMVar (← inferType e) MetavarKind.syntheticOpaque n.getId mvar.mvarId!.assign e -- We use `mkSaveInfoAnnotation` to make sure the info trees for `e` are saved even if `b` is a metavariable. return mkSaveInfoAnnotation (← elabTerm b expectedType?) | _ => throwUnsupportedSyntax private def getMVarFromUserName (ident : Syntax) : MetaM Expr := do match (← getMCtx).findUserName? ident.getId with | none => throwError "unknown metavariable '?{ident.getId}'" | some mvarId => instantiateMVars (mkMVar mvarId) @[builtin_term_elab «waitIfTypeMVar»] def elabWaitIfTypeMVar : TermElab := fun stx expectedType? => do match stx with | `(wait_if_type_mvar% ? $n; $b) => tryPostponeIfMVar (← inferType (← getMVarFromUserName n)) elabTerm b expectedType? | _ => throwUnsupportedSyntax @[builtin_term_elab «waitIfTypeContainsMVar»] def elabWaitIfTypeContainsMVar : TermElab := fun stx expectedType? => do match stx with | `(wait_if_type_contains_mvar% ? $n; $b) => if (← instantiateMVars (← inferType (← getMVarFromUserName n))).hasExprMVar then tryPostpone elabTerm b expectedType? | _ => throwUnsupportedSyntax @[builtin_term_elab «waitIfContainsMVar»] def elabWaitIfContainsMVar : TermElab := fun stx expectedType? => do match stx with | `(wait_if_contains_mvar% ? $n; $b) => if (← getMVarFromUserName n).hasExprMVar then tryPostpone elabTerm b expectedType? | _ => throwUnsupportedSyntax private def mkTacticMVar (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque let mvarId := mvar.mvarId! let ref ← getRef registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic tacticCode (← saveContext) return mvar @[builtin_term_elab byTactic] def elabByTactic : TermElab := fun stx expectedType? => do match expectedType? with | some expectedType => mkTacticMVar expectedType stx | none => tryPostpone throwError ("invalid 'by' tactic, expected type has not been provided") @[builtin_term_elab noImplicitLambda] def elabNoImplicitLambda : TermElab := fun stx expectedType? => elabTerm stx[1] (mkNoImplicitLambdaAnnotation <$> expectedType?) @[builtin_term_elab Lean.Parser.Term.cdot] def elabBadCDot : TermElab := fun _ _ => throwError "invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`)" @[builtin_term_elab str] def elabStrLit : TermElab := fun stx _ => do match stx.isStrLit? with | some val => pure $ mkStrLit val | none => throwIllFormedSyntax private def mkFreshTypeMVarFor (expectedType? : Option Expr) : TermElabM Expr := do let typeMVar ← mkFreshTypeMVar MetavarKind.synthetic match expectedType? with | some expectedType => discard <| isDefEq expectedType typeMVar | _ => pure () return typeMVar @[builtin_term_elab num] def elabNumLit : TermElab := fun stx expectedType? => do let val ← match stx.isNatLit? with | some val => pure val | none => throwIllFormedSyntax let typeMVar ← mkFreshTypeMVarFor expectedType? let u ← getDecLevel typeMVar let mvar ← mkInstMVar (mkApp2 (Lean.mkConst ``OfNat [u]) typeMVar (mkRawNatLit val)) let r := mkApp3 (Lean.mkConst ``OfNat.ofNat [u]) typeMVar (mkRawNatLit val) mvar registerMVarErrorImplicitArgInfo mvar.mvarId! stx r return r @[builtin_term_elab rawNatLit] def elabRawNatLit : TermElab := fun stx _ => do match stx[1].isNatLit? with | some val => return mkRawNatLit val | none => throwIllFormedSyntax @[builtin_term_elab scientific] def elabScientificLit : TermElab := fun stx expectedType? => do match stx.isScientificLit? with | none => throwIllFormedSyntax | some (m, sign, e) => let typeMVar ← mkFreshTypeMVarFor expectedType? let u ← getDecLevel typeMVar let mvar ← mkInstMVar (mkApp (Lean.mkConst ``OfScientific [u]) typeMVar) let r := mkApp5 (Lean.mkConst ``OfScientific.ofScientific [u]) typeMVar mvar (mkRawNatLit m) (toExpr sign) (mkRawNatLit e) registerMVarErrorImplicitArgInfo mvar.mvarId! stx r return r @[builtin_term_elab char] def elabCharLit : TermElab := fun stx _ => do match stx.isCharLit? with | some val => return mkApp (Lean.mkConst ``Char.ofNat) (mkRawNatLit val.toNat) | none => throwIllFormedSyntax @[builtin_term_elab quotedName] def elabQuotedName : TermElab := fun stx _ => match stx[0].isNameLit? with | some val => pure $ toExpr val | none => throwIllFormedSyntax @[builtin_term_elab doubleQuotedName] def elabDoubleQuotedName : TermElab := fun stx _ => return toExpr (← resolveGlobalConstNoOverloadWithInfo stx[2]) @[builtin_term_elab declName] def elabDeclName : TermElab := adaptExpander fun _ => do let some declName ← getDeclName? | throwError "invalid `decl_name%` macro, the declaration name is not available" return (quote declName : Term) @[builtin_term_elab Parser.Term.withDeclName] def elabWithDeclName : TermElab := fun stx expectedType? => do let id := stx[2].getId let id := if stx[1].isNone then id else (← getCurrNamespace) ++ id let e := stx[3] withMacroExpansion stx e <| withDeclName id <| elabTerm e expectedType? @[builtin_term_elab typeOf] def elabTypeOf : TermElab := fun stx _ => do inferType (← elabTerm stx[1] none) /-- Recall that `mkTermInfo` does not create an `ofTermInfo` node in the info tree if `e` corresponds to a hole that is going to be filled "later" by executing a tactic or resuming elaboration. This behavior is problematic for auxiliary elaboration steps that are "almost" no-ops. For example, consider the elaborator for ``` ensure_type_of% s msg e ``` It elaborates `s`, infers its type `t`, and then elaborates `e` ensuring the resulting type is `t`. If the elaboration of `e` is postponed, then the result is just a metavariable, and an `ofTermInfo` would not be created. This happens because `ensure_type_of%` is almost a no-op. The elaboration of `s` does not directly contribute to the final result, just its type. To make sure, we don't miss any information in the `InfoTree`, we can just create a "silent" annotation to force `mTermInfo` to create a node for the `ensure_type_of% s msg e` even if `e` has been postponed. Another possible solution is to elaborate `ensure_type_of% s msg e` as `ensureType s e` where `ensureType` has type ``` ensureType (s e : α) := e ``` We decided to use the silent notation because `ensure_type_of%` is heavily used in the `Do` elaborator, and the extra overhead could be significant. -/ private def mkSilentAnnotationIfHole (e : Expr) : TermElabM Expr := do if (← isTacticOrPostponedHole? e).isSome then return mkAnnotation `_silent e else return e @[builtin_term_elab ensureTypeOf] def elabEnsureTypeOf : TermElab := fun stx _ => match stx[2].isStrLit? with | none => throwIllFormedSyntax | some msg => do let refTerm ← elabTerm stx[1] none let refTermType ← inferType refTerm -- See comment at `mkSilentAnnotationIfHole` mkSilentAnnotationIfHole (← elabTermEnsuringType stx[3] refTermType (errorMsgHeader? := msg)) @[builtin_term_elab ensureExpectedType] def elabEnsureExpectedType : TermElab := fun stx expectedType? => match stx[1].isStrLit? with | none => throwIllFormedSyntax | some msg => elabTermEnsuringType stx[2] expectedType? (errorMsgHeader? := msg) @[builtin_term_elab clear] def elabClear : TermElab := fun stx expectedType? => do let some (.fvar fvarId) ← isLocalIdent? stx[1] | throwErrorAt stx[1] "not in scope" let body := stx[3] let canClear ← id do if let some expectedType := expectedType? then if ← dependsOn expectedType fvarId then return false for ldecl in ← getLCtx do if ldecl.fvarId != fvarId then if ← localDeclDependsOn ldecl fvarId then return false return true if canClear then let lctx := (← getLCtx).erase fvarId let localInsts := (← getLocalInstances).filter (·.fvar.fvarId! != fvarId) withLCtx lctx localInsts do elabTerm body expectedType? else elabTerm body expectedType? @[builtin_term_elab «open»] def elabOpen : TermElab := fun stx expectedType? => do let `(open $decl in $e) := stx | throwUnsupportedSyntax try pushScope let openDecls ← elabOpenDecl decl withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do elabTerm e expectedType? finally popScope @[builtin_term_elab «set_option»] def elabSetOption : TermElab := fun stx expectedType? => do let options ← Elab.elabSetOption stx[1] stx[2] withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do elabTerm stx[4] expectedType? @[builtin_term_elab withAnnotateTerm] def elabWithAnnotateTerm : TermElab := fun stx expectedType? => do match stx with | `(with_annotate_term $stx $e) => withInfoContext' stx (elabTerm e expectedType?) (mkTermInfo .anonymous (expectedType? := expectedType?) stx) | _ => throwUnsupportedSyntax private unsafe def evalFilePathUnsafe (stx : Syntax) : TermElabM System.FilePath := evalTerm System.FilePath (Lean.mkConst ``System.FilePath) stx @[implemented_by evalFilePathUnsafe] private opaque evalFilePath (stx : Syntax) : TermElabM System.FilePath @[builtin_term_elab includeStr] def elabIncludeStr : TermElab | `(include_str $path:term), _ => do let path ← evalFilePath path let ctx ← readThe Lean.Core.Context let srcPath := System.FilePath.mk ctx.fileName let some srcDir := srcPath.parent | throwError "cannot compute parent directory of '{srcPath}'" let path := srcDir / path mkStrLit <$> IO.FS.readFile path | _, _ => throwUnsupportedSyntax end Lean.Elab.Term
9ab7edf2ddba29b059a57d3d5da230b5363f32e9
367134ba5a65885e863bdc4507601606690974c1
/src/topology/metric_space/gromov_hausdorff_realized.lean
eb020c3383ddf79a36a14780b6f7b0c67b726f52
[ "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
26,204
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance noncomputable theory open_locale classical topological_space nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.to_fun ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
faae9f8438f7f07691dcedb8720cc9ea78ee33c5
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/HNN_normalize_better.lean
db523518c1ba35b5dc911e9f4b3dad3f66815bc1
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
17,036
lean
import initial import P import data.list.min_max /-! # HNN normalization for the group_thingy tactic This file implements the HNN normalization process and proof certificate generation for the `group_thingy` tactic. ## Main definitions This file contains the definition `HNN_normalize`, which is the only definition in this file used outside of this file. ## Implementation notes Both `HNN_normalize_core` and `reduce_mul` use an ad-hoc implementation of the binary coproduct of `P (free_group (ι × C∞))` and `C∞` as a `list (P (free_group (ι × C∞)) × C∞)`. The representation is in reverse, i.e. the list `[(p, a), (q, b)]` represents the word `b * q * a * p` in the coproduct. The word returned will be reduced in the sense that the only occurence of `1` will be either `prod.fst` of the first element of the list, or `prod.snd` of the final element. -/ variables {ι : Type} [decidable_eq ι] (r : free_group ι) (T : set ι) [decidable_pred T] open free_group P semidirect_product multiplicative /-- `mul_subscript` is the action of `C∞` on `free_group (ι × C∞)`. `mul_subscript n (of (i, m)) = of (i, n * m)` -/ def mul_subscript : C∞ →* free_group (ι × C∞) ≃* free_group (ι × C∞) := { to_fun := λ n, free_group.equiv (equiv.prod_congr (equiv.refl _) (equiv.mul_left n)), map_one' := mul_equiv.to_monoid_hom_injective (free_group.hom_ext (by simp)), map_mul' := λ _ _, mul_equiv.to_monoid_hom_injective (free_group.hom_ext (by simp [mul_assoc])) } /-- `remove_subscript t (of (i, n)) = (of t)^n * of i * (of t)^(-n)` -/ def remove_subscript (t : ι) : free_group (ι × C∞) →* free_group ι := free_group.lift' (λ g, (mul_aut.conj (of' t g.2)).to_monoid_hom.comp (of' g.1)) /-- `add_subscript t` is a one sided inverse to `semidirect_product.inl ∘ remove_subscript t` -/ def add_subscript (t : ι) : free_group ι →* free_group (ι × C∞) ⋊[mul_subscript] C∞ := free_group.lift' (λ j, if t = j then semidirect_product.inr else semidirect_product.inl.comp (of' (j, 1))) /-- `max_subscript x w`, returns the largest `k` such that the letter `(x, k)` appears in `w`, or `none` if there is no such occurence -/ @[inline] def max_subscript (x : ι) (w : free_group (ι × C∞)) : option C∞ := (w.to_list.filter_map (λ i : Σ i : ι × C∞, C∞, if i.1.1 = x then some i.1.2 else none)).maximum /-- `min_subscript x w`, returns the smallext `k` such that the letter `(x, k)` appears in `w`, or `none` if there is no such occurence -/ @[inline] def min_subscript (x : ι) (w : free_group (ι × C∞)) : option C∞ := (w.to_list.filter_map (λ i : Σ i : ι × C∞, C∞, if i.1.1 = x then some i.1.2 else none)).minimum /-- If `p` is a certificate that `a` and `b` are equal, then `remove_subscript t (conj_P t k p)`, will return a certificate that `t^k * remove_subscript t a * t^(-k)` is congruent to `t^k * remove_subscript t b * t^(-k)` -/ def conj_P (t : ι) (k : C∞) (p : P (free_group (ι × C∞))) : P (free_group (ι × C∞)) := ⟨mul_free (of' (t, 1) k) p.left, mul_subscript k p.right⟩ -- /-- `reduce_mul (p, n) l`, returns `l * n * p` if `l`is thought -- of as an element of the binary coproduct of `P (free_group (ι × C∞))` and `C∞`. -/ -- def reduce_mul : P (free_group (ι × C∞)) × C∞ → -- list (P (free_group (ι × C∞)) × C∞) → -- list (P (free_group (ι × C∞)) × C∞) -- | p [] := [p] -- | (p, n) ((q, m)::l) := -- if n = 1 -- then (q * p, m) :: l -- else (p, n) :: (q, m) :: l /-- `HNN_normalize_core` returns a normalized word in the `HNN` extension. It is returned as a `list (P (free_group (ι × C∞)) × C∞)` which can be thought of as an element of the binary conproduct of `P (free_group (ι × C∞))` and `C∞`. The representation is in reverse, i.e. the list `[(p, a), (q, b)]` represents the word `b * q * a * p` in the coproduct. The word returned will be reduced in the sense that the only occurence of `1` will be either `prod.fst` of the first element of the list, or `prod.snd` of the final element. The function takes an already HNN normalized word `l₁` in the coproduct as a `list (P (free_group (ι × C∞)) × C∞)`, and an unnormalized word `l₂` in `free_group ι`, as a `list (Σ i : ι, C∞)`. The function effectively returns the product `l₁ * l₂` as an HNN normalized word in the coproduct. -/ -- @[inline] meta def HNN_normalize_core -- (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : -- list (P (free_group (ι × C∞)) × C∞) → -- list (Σ i : ι, C∞) → -- list (P (free_group (ι × C∞)) × C∞) -- | p [] := p -- | [] (i::l) := -- if i.1 = t -- then HNN_normalize_core [(1, i.2)] l -- else HNN_normalize_core [(inr (of_list [⟨(i.1, 1), i.2⟩]), 1)] l -- | ((p, n) :: l₁) (i::l₂) := -- if i.1 = t -- then if 1 ≤ i.2 -- then match hs r' {s | s ≠ (x, a)} p.right with -- | none := HNN_normalize_core ((1, i.2) :: (p, n) :: l₁) l₂ -- | some q := -- -- k is the minimum amount I can subtract from the subscripts -- -- and stay between a and b -- let k : C∞ := match min_subscript x q.right with -- | some m := if n < 1 then max (max (i.2⁻¹) (a * m⁻¹)) n else max (i.2⁻¹) (a * m⁻¹) -- | none := if n < 1 then max i.2⁻¹ n else i.2⁻¹ -- end in -- HNN_normalize_core -- (reduce_mul ((conj_P t k (P.trans p q)), n * k⁻¹) l₁) --BUG when |k| > |n| -- (let m := i.2 * k in -- if m = 1 then l₂ else ⟨t, m⟩ :: l₂) -- end -- else match hs r' {s | s ≠ (x, b)} p.right with -- | none := HNN_normalize_core ((1, i.2) :: (p, n) :: l₁) l₂ -- | some q := -- -- k is the maximum amount I can subtract from the subscripts -- -- and stay between a and b -- let k : C∞ := match max_subscript x q.right with -- | some m := if 1 < n then min (min (i.2⁻¹) (b * m⁻¹)) n else min (i.2⁻¹) (b * m⁻¹) -- | none := if 1 < n then max i.2⁻¹ n else i.2⁻¹ -- end in -- HNN_normalize_core -- (reduce_mul ((conj_P t k (P.trans p q)), n * k⁻¹) l₁) -- (let m := i.2 * k in -- if m = 1 then l₂ else ⟨t, m⟩ :: l₂) -- end -- else HNN_normalize_core ((⟨p.left, p.right * of' (i.1, 1) i.2⟩, n) :: l₁) l₂ def HNN_normalize_single_pos (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : C∞ × P (free_group (ι × C∞)) → option (C∞ × P (free_group (ι × C∞)) × C∞) | (n, p) := match hs r' {s | s ≠ (x, b)} p.right with | none := none | some q := -- k is the maximum amount I can subtract from the subscripts -- and stay between a and b let k : C∞ := match max_subscript x q.right with | some m := min n (b * m⁻¹) | none := n end in let m := n * k⁻¹ in some (m, conj_P t k (p.trans q), k) end def HNN_normalize_single_neg (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : C∞ × P (free_group (ι × C∞)) → option (C∞ × P (free_group (ι × C∞)) × C∞) | (n, p) := match hs r' {s | s ≠ (x, a)} p.right with | none := none | some q := -- k is the minimum amount I can subtract from the subscripts -- and stay between a and b let k : C∞ := match min_subscript x q.right with | some m := max n (a * m⁻¹) | none := n end in let m := n * k⁻¹ in some (m, conj_P t k (p.trans q), k) end def HNN_normalize_single (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : C∞ × P (free_group (ι × C∞)) → option (C∞ × P (free_group (ι × C∞)) × C∞) | (n, p) := if 1 ≤ n then HNN_normalize_single_pos t x r' a b hs (n, p) else HNN_normalize_single_neg t x r' a b hs (n, p) -- @[inline] meta def HNN_normalize'_core -- (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : -- list (C∞ × P (free_group (ι × C∞))) → -- P (free_group (ι × C∞)) → C∞ → -- list (Σ i : ι, C∞) → -- list (C∞ × P (free_group (ι × C∞))) -- | [] q m [] := [(m, q)] -- | [] q m (i::l₂) := -- if i.1 = t -- then HNN_normalize'_core [] q (m * i.2) l₂ -- else if m = 1 -- then HNN_normalize'_core [] (q * inr (of_list [⟨(i.1, 1), i.2⟩])) 1 l₂ -- else HNN_normalize'_core [(m, q)] (inr (of_list [⟨(i.1, 1), i.2⟩])) 1 l₂ -- | ((n, p)::l₁) q m [] := -- match HNN_normalize'_single t x r' a b hs (n, q) with -- | none := (m, q)::(n, p)::l₁ -- | some (n', q') := -- if n' = 1 -- then HNN_normalize'_core l₁ (p * q') (n * m) [] -- else HNN_normalize'_core ((n', p)::l₁) q' (n * n'⁻¹ * m) [] -- end -- | ((n, p)::l₁) q m (i::l₂) := -- if m = 1 -- then if i.1 = t -- then HNN_normalize'_core ((n, p)::l₁) q i.2 l₂ -- else HNN_normalize'_core ((n, p)::l₁) (q * inr (of_list [⟨(i.1, 1), i.2⟩])) 1 l₂ -- else -- match HNN_normalize'_single t x r' a b hs (n, q) with -- | none := HNN_normalize'_core ((m, q)::(n,p)::l₁) 1 1 (i::l₂) -- | some (n', q') := -- if n' = 1 -- then HNN_normalize'_core l₁ (p * q') (n * m) (i::l₂) -- else HNN_normalize'_core ((n', p)::l₁) q' (n * n'⁻¹ * m) (i::l₂) -- end -- @[inline] meta def HNN_normalize' (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) -- (w : free_group ι) : option (C∞ × P (free_group (ι × C∞))) := -- match HNN_normalize'_core t x r' a b hs [] 1 1 w.to_list with -- | [] := some 1 -- | [(n, p)] := some (n, p) -- | (a::b::l) := none -- end -- /-- Given a word `w` in `free_group ι`, `HNN_normalize` checks whether it -- can be written in the form `t^n * g`, with `g` a `t`-free word in the -- HNN extension. If it cannot be written in this form `HNN_normalize` returns `none`, -- if it can then `HNN_normalize` returns this pair, along with a proof. More precisely, -- it returns a pair `(p, n)` where `p` is a certificate that `t^(-n) * w` is equal -- to a `t`-free term. -/ -- @[inline] meta def HNN_normalize (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) -- (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) -- (w : free_group ι) : option (P (free_group (ι × C∞)) × C∞) := -- match HNN_normalize_core t x r' a b hs [] w.to_list with -- | [] := some 1 -- | [a] := some a -- | (a::b::l) := none -- end /-- `reduce_mul (p, n) l`, returns `l * n * p` if `l`is thought of as an element of the binary coproduct of `P (free_group (ι × C∞))` and `C∞`. -/ def reduce_mul_reversed : list (C∞ × P (free_group (ι × C∞)) × C∞) → C∞ × P (free_group (ι × C∞)) → list (C∞ × P (free_group (ι × C∞)) × C∞) | [] p := [(p.1, p.2, p.1)] | ((m, q, s)::l) (n, p) := if n = 1 then (m, q * p, s) :: l else (n, p, n * s) :: (m, q, s) :: l -- def reduce_mul : -- C∞ × P (free_group (ι × C∞)) → -- list (C∞ × P (free_group (ι × C∞)) × C∞) → -- list (C∞ × P (free_group (ι × C∞)) × C∞) -- | p [] := [(p.1, p.2, p.1)] -- | (n, p) ((m, q, s)::l) := -- if m = 1 -- then (m, p * q, s) :: l -- else (n, p, n * s) :: (m, q, s) :: l meta def HNN_normalize_initial_core (t x : ι) (a b : C∞) : list (C∞ × P (free_group (ι × C∞)) × C∞) → --reversed and HNN normalized C∞ → P (free_group (ι × C∞)) → list (Σ i : ι, C∞) → list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ --reversed | l₁ n p [] := match HNN_normalize_single t x 1 a b (λ _ T _ w, by exactI guard (mem_closure_var T w) >> return (inr w)) (n, p) with | none := (reduce_mul_reversed l₁ (n, p), 1) | some (n', q', m) := (reduce_mul_reversed l₁ (n', q'), m) end | l₁ n₁ p (⟨i, n₂⟩::l₂) := if i = t then match HNN_normalize_single t x 1 a b (λ _ T _ w, by exactI guard (mem_closure_var T w) >> return (inr w)) (n₁, p) with | none := HNN_normalize_initial_core (reduce_mul_reversed l₁ (n₁, p)) n₂ 1 l₂ | some (n₁', q', m) := HNN_normalize_initial_core (reduce_mul_reversed l₁ (n₁', p)) (m * n₂) 1 l₂ end else HNN_normalize_initial_core l₁ n₁ (p * inr (of_list [⟨(i, 1), n₂⟩])) l₂ meta def HNN_normalize_initial (t x : ι) (a b : C∞) (w : free_group ι) : list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ --normal := (HNN_normalize_initial_core t x a b [] 1 1 w.to_list).map list.reverse id def reduce_mul_long : list (C∞ × P (free_group (ι × C∞)) × C∞) → --reversed list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ → --normal list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ --normal | [] l₂ := l₂ | l₁ ([], n) := (l₁.reverse, n) | ((n₁, p₁, s₁)::l₁) (((n₂, p₂, s₂)::l₂), n) := if n₂ = 1 then (l₁.reverse_core ((n₁, p₁ * p₂, s₂)::l₂), n) else (l₁.reverse_core ((n₁, p₁, s₁)::(n₂, p₂, s₂)::l₂), n) @[inline] def normalized_mul : C∞ → P (free_group (ι × C∞)) → C∞ → list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ → --normal list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ --normal | m p n ([], d) := ([(m, p, m)], n * d) | m p n (((k, q, s)::l), d) := if n * k = 1 then ((m, p * q, s)::l, d) else ((m, p, s * (n * k)⁻¹) :: (n * k, q, s) :: l, d) @[inline] def reduce_mul_middle : list (C∞ × P (free_group (ι × C∞)) × C∞) → --reversed C∞ → P (free_group (ι × C∞)) → C∞ → list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ → -- normal order list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ -- normal order | [] m p n l := normalized_mul m p n l | ((k, q, s)::l₁) m p n ([], d) := if m = 1 then (l₁.reverse_core [(k, q * p, s)], n * d) else (l₁.reverse_core [(k, q, s), (m, p, s * m)], n * d) | ((k₁, q₁, s₁)::l₁) m p n (((k₂, q₂, s₂)::l₂), d) := reduce_mul_long l₁ (normalized_mul m p n (((k₂, q₂, s₂)::l₂), d)) def find_peak_pos (l : list (C∞ × P (free_group (ι × C∞)) × C∞)) : ℕ × C∞ × P (free_group (ι × C∞)) × C∞ := l.foldl_with_index (λ i y p, if p.2.2 > y.2.2.2 then (i, p.1, p.2.1, p.2.2) else y) (0, 1, 1, 1) def find_peak_neg (l : list (C∞ × P (free_group (ι × C∞)) × C∞)) : ℕ × C∞ × P (free_group (ι × C∞)) × C∞ := l.foldl_with_index (λ i y p, if p.2.2 < y.2.2.2 then (i, p.1, p.2.1, p.2.2) else y) (0, 1, 1, 1) meta def HNN_normalize_core (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) : list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ → --normal option (list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞) --normal | ([], d) := some ([], d) | ((μ::l), d) := if μ.1 ≥ 1 then let (i, n, p, s) := find_peak_pos (μ::l) in do (m, q, k) ← HNN_normalize_single_pos t x r' a b hs (n, p), HNN_normalize_core (reduce_mul_middle ((μ::l).take i).reverse m q k ((μ::l).drop (i+1), d)) else let (i, n, p, s) := find_peak_neg (μ::l) in do (m, q, k) ← HNN_normalize_single_neg t x r' a b hs (n, p), HNN_normalize_core (reduce_mul_middle ((μ::l).take i).reverse m q k ((μ::l).drop (i+1), d)) meta def HNN_normalize (t x : ι) (r' : free_group (ι × C∞)) (a b : C∞) (hs : Π (r : free_group (ι × C∞)) (T : set (ι × C∞)) [decidable_pred T], solver r T) (w : free_group ι) : option (P (free_group (ι × C∞)) × C∞) := let w' : list (C∞ × P (free_group (ι × C∞)) × C∞) × C∞ := HNN_normalize_initial t x a b w in do l ← HNN_normalize_core t x r' a b hs w', match l with | ([], d) := some (1, d) | ([(n, p, s)], d) := guard (n = 1) >> return (p, d) | _ := none end
dc366c3798607fd1683a266ebe2c3f3d68ea6339
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/card_measurable_space.lean
2c83c4b6d4f3db8139e2a73842081177554f786f
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,540
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Violeta Hernández Palacios -/ import measure_theory.measurable_space_def import set_theory.cardinal.cofinality import set_theory.cardinal.continuum /-! # Cardinal of sigma-algebras If a sigma-algebra is generated by a set of sets `s`, then the cardinality of the sigma-algebra is bounded by `(max (#s) 2) ^ ω`. This is stated in `measurable_space.cardinal_generate_measurable_le` and `measurable_space.cardinal_measurable_set_le`. In particular, if `#s ≤ 𝔠`, then the generated sigma-algebra has cardinality at most `𝔠`, see `measurable_space.cardinal_measurable_set_le_continuum`. For the proof, we rely on an explicit inductive construction of the sigma-algebra generated by `s` (instead of the inductive predicate `generate_measurable`). This transfinite inductive construction is parameterized by an ordinal `< ω₁`, and the cardinality bound is preserved along each step of the construction. We show in `measurable_space.generate_measurable_eq_rec` that this indeed generates this sigma-algebra. -/ universe u variables {α : Type u} open_locale cardinal open cardinal set local notation `ω₁` := (aleph 1 : cardinal.{u}).ord.out.α namespace measurable_space /-- Transfinite induction construction of the sigma-algebra generated by a set of sets `s`. At each step, we add all elements of `s`, the empty set, the complements of already constructed sets, and countable unions of already constructed sets. We index this construction by an ordinal `< ω₁`, as this will be enough to generate all sets in the sigma-algebra. This construction is very similar to that of the Borel hierarchy. -/ def generate_measurable_rec (s : set (set α)) : ω₁ → set (set α) | i := let S := ⋃ j : {j // j < i}, generate_measurable_rec j.1 in s ∪ {∅} ∪ compl '' S ∪ set.range (λ (f : ℕ → S), ⋃ n, (f n).1) using_well_founded {dec_tac := `[exact j.2]} theorem self_subset_generate_measurable_rec (s : set (set α)) (i : ω₁) : s ⊆ generate_measurable_rec s i := begin unfold generate_measurable_rec, apply_rules [subset_union_of_subset_left], exact subset_rfl end theorem empty_mem_generate_measurable_rec (s : set (set α)) (i : ω₁) : ∅ ∈ generate_measurable_rec s i := begin unfold generate_measurable_rec, exact mem_union_left _ (mem_union_left _ (mem_union_right _ (mem_singleton ∅))) end theorem compl_mem_generate_measurable_rec {s : set (set α)} {i j : ω₁} (h : j < i) {t : set α} (ht : t ∈ generate_measurable_rec s j) : tᶜ ∈ generate_measurable_rec s i := begin unfold generate_measurable_rec, exact mem_union_left _ (mem_union_right _ ⟨t, mem_Union.2 ⟨⟨j, h⟩, ht⟩, rfl⟩) end theorem Union_mem_generate_measurable_rec {s : set (set α)} {i : ω₁} {f : ℕ → set α} (hf : ∀ n, ∃ j < i, f n ∈ generate_measurable_rec s j) : (⋃ n, f n) ∈ generate_measurable_rec s i := begin unfold generate_measurable_rec, exact mem_union_right _ ⟨λ n, ⟨f n, let ⟨j, hj, hf⟩ := hf n in mem_Union.2 ⟨⟨j, hj⟩, hf⟩⟩, rfl⟩ end theorem generate_measurable_rec_subset (s : set (set α)) {i j : ω₁} (h : i ≤ j) : generate_measurable_rec s i ⊆ generate_measurable_rec s j := λ x hx, begin rcases eq_or_lt_of_le h with rfl | h, { exact hx }, { convert Union_mem_generate_measurable_rec (λ n, ⟨i, h, hx⟩), exact (Union_const x).symm } end /-- At each step of the inductive construction, the cardinality bound `≤ (max (#s) 2) ^ ω` holds. -/ lemma cardinal_generate_measurable_rec_le (s : set (set α)) (i : ω₁) : #(generate_measurable_rec s i) ≤ (max (#s) 2) ^ omega.{u} := begin apply (aleph 1).ord.out.wo.wf.induction i, assume i IH, have A := omega_le_aleph 1, have B : aleph 1 ≤ (max (#s) 2) ^ omega.{u} := aleph_one_le_continuum.trans (power_le_power_right (le_max_right _ _)), have C : ω ≤ (max (#s) 2) ^ omega.{u} := A.trans B, have J : #(⋃ (j : {j // j < i}), generate_measurable_rec s j.1) ≤ (max (#s) 2) ^ omega.{u}, { apply (mk_Union_le _).trans, have D : cardinal.sup.{u u} (λ (j : {j // j < i}), #(generate_measurable_rec s j.1)) ≤ _ := cardinal.sup_le (λ ⟨j, hj⟩, IH j hj), apply (mul_le_mul' ((mk_subtype_le _).trans (aleph 1).mk_ord_out.le) D).trans, rw mul_eq_max A C, exact max_le B le_rfl }, rw [generate_measurable_rec], apply_rules [(mk_union_le _ _).trans, add_le_of_le C, mk_image_le.trans], { exact (le_max_left _ _).trans (self_le_power _ one_lt_omega.le) }, { rw [mk_singleton], exact one_lt_omega.le.trans C }, { apply mk_range_le.trans, simp only [mk_pi, subtype.val_eq_coe, prod_const, lift_uzero, mk_denumerable, lift_omega], have := @power_le_power_right _ _ ω J, rwa [← power_mul, omega_mul_omega] at this } end /-- `generate_measurable_rec s` generates precisely the smallest sigma-algebra containing `s`. -/ theorem generate_measurable_eq_rec (s : set (set α)) : {t | generate_measurable s t} = ⋃ i, generate_measurable_rec s i := begin ext t, refine ⟨λ ht, _, λ ht, _⟩, { inhabit ω₁, induction ht with u hu u hu IH f hf IH, { exact mem_Union.2 ⟨default, self_subset_generate_measurable_rec s _ hu⟩ }, { exact mem_Union.2 ⟨default, empty_mem_generate_measurable_rec s _⟩ }, { rcases mem_Union.1 IH with ⟨i, hi⟩, obtain ⟨j, hj⟩ := exists_gt i, exact mem_Union.2 ⟨j, compl_mem_generate_measurable_rec hj hi⟩ }, { have : ∀ n, ∃ i, f n ∈ generate_measurable_rec s i := λ n, by simpa using IH n, choose I hI using this, refine mem_Union.2 ⟨ordinal.enum (<) (ordinal.lsub (λ n, ordinal.typein.{u} (<) (I n))) _, Union_mem_generate_measurable_rec (λ n, ⟨I n, _, hI n⟩)⟩, { rw ordinal.type_lt, refine ordinal.lsub_lt_ord_lift _ (λ i, ordinal.typein_lt_self _), rw [mk_denumerable, lift_omega, is_regular_aleph_one.2], exact omega_lt_aleph_one }, { rw [←ordinal.typein_lt_typein (<), ordinal.typein_enum], apply ordinal.lt_lsub (λ n : ℕ, _) } } }, { rcases ht with ⟨t, ⟨i, rfl⟩, hx⟩, revert t, apply (aleph 1).ord.out.wo.wf.induction i, intros j H t ht, unfold generate_measurable_rec at ht, rcases ht with (((h | h) | ⟨u, ⟨-, ⟨⟨k, hk⟩, rfl⟩, hu⟩, rfl⟩) | ⟨f, rfl⟩), { exact generate_measurable.basic t h }, { convert generate_measurable.empty }, { exact generate_measurable.compl u (H k hk u hu) }, { apply generate_measurable.union _ (λ n, _), obtain ⟨-, ⟨⟨k, hk⟩, rfl⟩, hf⟩ := (f n).prop, exact H k hk _ hf } } end /-- If a sigma-algebra is generated by a set of sets `s`, then the sigma-algebra has cardinality at most `(max (#s) 2) ^ ω`. -/ theorem cardinal_generate_measurable_le (s : set (set α)) : #{t | generate_measurable s t} ≤ (max (#s) 2) ^ omega.{u} := begin rw generate_measurable_eq_rec, apply (mk_Union_le _).trans, rw (aleph 1).mk_ord_out, refine le_trans (mul_le_mul' aleph_one_le_continuum (cardinal.sup_le (λ i, cardinal_generate_measurable_rec_le s i))) _, have := power_le_power_right (le_max_right (#s) 2), rw mul_eq_max omega_le_continuum (omega_le_continuum.trans this), exact max_le this le_rfl end /-- If a sigma-algebra is generated by a set of sets `s`, then the sigma algebra has cardinality at most `(max (#s) 2) ^ ω`. -/ theorem cardinal_measurable_set_le (s : set (set α)) : #{t | @measurable_set α (generate_from s) t} ≤ (max (#s) 2) ^ omega.{u} := cardinal_generate_measurable_le s /-- If a sigma-algebra is generated by a set of sets `s` with cardinality at most the continuum, then the sigma algebra has the same cardinality bound. -/ theorem cardinal_generate_measurable_le_continuum {s : set (set α)} (hs : #s ≤ 𝔠) : #{t | generate_measurable s t} ≤ 𝔠 := (cardinal_generate_measurable_le s).trans begin rw ←continuum_power_omega, exact_mod_cast power_le_power_right (max_le hs (nat_lt_continuum 2).le) end /-- If a sigma-algebra is generated by a set of sets `s` with cardinality at most the continuum, then the sigma algebra has the same cardinality bound. -/ theorem cardinal_measurable_set_le_continuum {s : set (set α)} : #s ≤ 𝔠 → #{t | @measurable_set α (generate_from s) t} ≤ 𝔠 := cardinal_generate_measurable_le_continuum end measurable_space
ccaf2a2d2ef548ace8322d5fad936922cc54a17a
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/category_theory/limits/over.lean
0c619b3321816974a74181b3ee49d5da72adca0c
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
10,724
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.comma import category_theory.limits.connected import category_theory.limits.creates import category_theory.limits.limits import category_theory.limits.preserves import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.binary_products universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variable {X : C} namespace category_theory.functor @[simps] def to_cocone (F : J ⥤ over X) : cocone (F ⋙ over.forget) := { X := X, ι := { app := λ j, (F.obj j).hom } } @[simps] def to_cone (F : J ⥤ under X) : cone (F ⋙ under.forget) := { X := X, π := { app := λ j, (F.obj j).hom } } end category_theory.functor namespace category_theory.over @[simps] def colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : cocone F := { X := mk $ colimit.desc (F ⋙ forget) F.to_cocone, ι := { app := λ j, hom_mk $ colimit.ι (F ⋙ forget) j, naturality' := begin intros j j' f, have := colimit.w (F ⋙ forget) f, tidy end } } def forget_colimit_is_colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : is_colimit (forget.map_cocone (colimit F)) := is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ forget)) (cocones.ext (iso.refl _) (by tidy)) instance : reflects_colimits (forget : over X ⥤ C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ F, by constructor; exactI λ t ht, { desc := λ s, hom_mk (ht.desc (forget.map_cocone s)) begin apply ht.hom_ext, intro j, rw [←category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.ι.app j), -- TODO: How to write (s.ι.app j).w? exact (w (t.ι.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac (forget.map_cocone s) j -- TODO: Ask Simon about multiple ext lemmas for defeq types (comma_morphism & over.category.hom) end, uniq' := begin intros s m w, ext1 j, exact ht.uniq (forget.map_cocone s) m.left (λ j, congr_arg comma_morphism.left (w j)) end } } } instance has_colimit {F : J ⥤ over X} [has_colimit (F ⋙ forget)] : has_colimit F := { cocone := colimit F, is_colimit := reflects_colimit.reflects (forget_colimit_is_colimit F) } instance has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := { has_colimit := λ F, by apply_instance } instance has_colimits [has_colimits.{v} C] : has_colimits.{v} (over X) := { has_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_colimits [has_colimits.{v} C] {X : C} : preserves_colimits (forget : over X ⥤ C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (forget_colimit_is_colimit F) } } /-- Given the appropriate pullback in C, construct a product in the over category -/ def over_product_of_pullbacks (B : C) (F : discrete walking_pair ⥤ over B) [q : has_limit (cospan (F.obj walking_pair.left).hom (F.obj walking_pair.right).hom)] : has_limit F := { cone := begin refine ⟨_, _⟩, exact @over.mk _ _ B (pullback (F.obj walking_pair.left).hom (F.obj walking_pair.right).hom) (pullback.fst ≫ (F.obj walking_pair.left).hom), apply nat_trans.of_homs, intro i, cases i, apply over.hom_mk _ _, apply pullback.fst, dsimp, refl, apply over.hom_mk _ _, apply pullback.snd, exact pullback.condition.symm end, is_limit := { lift := λ s, begin apply over.hom_mk _ _, apply pullback.lift _ _ _, exact (s.π.app walking_pair.left).left, exact (s.π.app walking_pair.right).left, erw over.w (s.π.app walking_pair.left), erw over.w (s.π.app walking_pair.right), refl, dsimp, erw ← category.assoc, simp, end, fac' := λ s j, begin ext, cases j; simp [nat_trans.of_homs] end, uniq' := λ s m j, begin ext, { erw ← j walking_pair.left, simp }, { erw ← j walking_pair.right, simp } end } } /-- Construct terminal object in the over category. -/ instance (B : C) : has_terminal.{v} (over B) := { has_limits_of_shape := { has_limit := λ F, { cone := { X := over.mk (𝟙 _), π := { app := λ p, pempty.elim p } }, is_limit := { lift := λ s, over.hom_mk _, fac' := λ _ j, j.elim, uniq' := λ s m _, begin ext, rw over.hom_mk_left, have := m.w, dsimp at this, rwa [category.comp_id, category.comp_id] at this end } } } } namespace creates_connected /-- (Impl) Given a diagram in the over category, produce a natural transformation from the diagram legs to the specific object. -/ def nat_trans_in_over {B : C} (F : J ⥤ over B) : F ⋙ forget ⟶ (category_theory.functor.const J).obj B := { app := λ j, (F.obj j).hom } local attribute [tidy] tactic.case_bash /-- (Impl) Given a cone in the base category, raise it to a cone in the over category. Note this is where the connected assumption is used. -/ @[simps] def raise_cone [connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget)) : cone F := { X := over.mk (c.π.app (default J) ≫ (F.obj (default J)).hom), π := { app := λ j, over.hom_mk (c.π.app j) (nat_trans_from_connected (c.π ≫ nat_trans_in_over F) j) } } lemma raised_cone_lowers_to_original [connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget)) (t : is_limit c) : forget.map_cone (raise_cone c) = c := by tidy /-- (Impl) Show that the raised cone is a limit. -/ def raised_cone_is_limit [connected J] {B : C} {F : J ⥤ over B} {c : cone (F ⋙ forget)} (t : is_limit c) : is_limit (raise_cone c) := { lift := λ s, over.hom_mk (t.lift (forget.map_cone s)) (by { dsimp, simp }), uniq' := λ s m K, by { ext1, apply t.hom_ext, intro j, simp [← K j] } } end creates_connected /-- The forgetful functor from the over category creates any connected limit. -/ instance forget_creates_connected_limits [connected J] {B : C} : creates_limits_of_shape J (forget : over B ⥤ C) := { creates_limit := λ K, creates_limit_of_reflects_iso (λ c t, { lifted_cone := creates_connected.raise_cone c, valid_lift := eq_to_iso (creates_connected.raised_cone_lowers_to_original c t), makes_limit := creates_connected.raised_cone_is_limit t } ) } /-- The over category has any connected limit which the original category has. -/ instance has_connected_limits {B : C} [connected J] [has_limits_of_shape J C] : has_limits_of_shape J (over B) := { has_limit := λ F, has_limit_of_created F (forget : over B ⥤ C) } /-- Make sure we can derive pullbacks in `over B`. -/ example {B : C} [has_pullbacks.{v} C] : has_pullbacks.{v} (over B) := { has_limits_of_shape := infer_instance } /-- Make sure we can derive equalizers in `over B`. -/ example {B : C} [has_equalizers.{v} C] : has_equalizers.{v} (over B) := { has_limits_of_shape := infer_instance } /-- Given pullbacks in C, we have binary products in any over category -/ instance over_has_prods_of_pullback [has_pullbacks.{v} C] (B : C) : has_binary_products.{v} (over B) := {has_limits_of_shape := {has_limit := λ F, over_product_of_pullbacks B F}} /-! A collection of lemmas to decompose products in the over category -/ @[simp] lemma over_prod_pair_left [has_pullbacks.{v} C] {B : C} (f g : over B) : (f ⨯ g).left = pullback f.hom g.hom := rfl @[simp] lemma over_prod_pair_hom [has_pullbacks.{v} C] {B : C} (f g : over B) : (f ⨯ g).hom = pullback.fst ≫ f.hom := rfl @[simp] lemma over_prod_fst_left [has_pullbacks.{v} C] {B : C} (f g : over B) : (limits.prod.fst : f ⨯ g ⟶ f).left = pullback.fst := rfl @[simp] lemma over_prod_snd_left [has_pullbacks.{v} C] {B : C} (f g : over B) : (limits.prod.snd : f ⨯ g ⟶ g).left = pullback.snd := rfl lemma over_prod_map_left [has_pullbacks.{v} C] {B : C} (f g h k : over B) (α : f ⟶ g) (β : h ⟶ k) : (limits.prod.map α β).left = pullback.lift (pullback.fst ≫ α.left) (pullback.snd ≫ β.left) (by { simp only [category.assoc], convert pullback.condition; apply over.w }) := rfl end category_theory.over namespace category_theory.under @[simps] def limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : cone F := { X := mk $ limit.lift (F ⋙ forget) F.to_cone, π := { app := λ j, hom_mk $ limit.π (F ⋙ forget) j, naturality' := begin intros j j' f, have := (limit.w (F ⋙ forget) f).symm, tidy end } } def forget_limit_is_limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : is_limit (forget.map_cone (limit F)) := is_limit.of_iso_limit (limit.is_limit (F ⋙ forget)) (cones.ext (iso.refl _) (by tidy)) instance : reflects_limits (forget : under X ⥤ C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ F, by constructor; exactI λ t ht, { lift := λ s, hom_mk (ht.lift (forget.map_cone s)) begin apply ht.hom_ext, intro j, rw [category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.π.app j), exact (w (t.π.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac (forget.map_cone s) j end, uniq' := begin intros s m w, ext1 j, exact ht.uniq (forget.map_cone s) m.right (λ j, congr_arg comma_morphism.right (w j)) end } } } instance has_limit {F : J ⥤ under X} [has_limit (F ⋙ forget)] : has_limit F := { cone := limit F, is_limit := reflects_limit.reflects (forget_limit_is_limit F) } instance has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (under X) := { has_limit := λ F, by apply_instance } instance has_limits [has_limits.{v} C] : has_limits.{v} (under X) := { has_limits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_limits [has_limits.{v} C] {X : C} : preserves_limits (forget : under X ⥤ C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (forget_limit_is_limit F) } } end category_theory.under
928b582dd86cb509aec45ab5116adb4efc496b52
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/floor_ring.lean
048182131d8f21907ed47d9400242bf4a6c73728
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
9,572
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import algebra.order.floor import topology.algebra.ordered.basic /-! # Topological facts about `int.floor`, `int.ceil` and `int.fract` This file proves statements about limits and continuity of functions involving `floor`, `ceil` and `fract`. ## Main declarations * `tendsto_floor_at_top`, `tendsto_floor_at_bot`, `tendsto_ceil_at_top`, `tendsto_ceil_at_bot`: `int.floor` and `int.ceil` tend to +-∞ in +-∞. * `continuous_on_floor`: `int.floor` is continuous on `Ico n (n + 1)`, because constant. * `continuous_on_ceil`: `int.ceil` is continuous on `Ioc n (n + 1)`, because constant. * `continuous_on_fract`: `int.fract` is continuous on `Ico n (n + 1)`. * `continuous_on.comp_fract`: Precomposing a continuous function satisfying `f 0 = f 1` with `int.fract` yields another continuous function. -/ open filter function int set open_locale topological_space variables {α β γ : Type*} [linear_ordered_ring α] [floor_ring α] lemma tendsto_floor_at_top : tendsto (floor : α → ℤ) at_top at_top := floor_mono.tendsto_at_top_at_top $ λ b, ⟨(b + 1 : ℤ), by { rw floor_coe, exact (lt_add_one _).le }⟩ lemma tendsto_floor_at_bot : tendsto (floor : α → ℤ) at_bot at_bot := floor_mono.tendsto_at_bot_at_bot $ λ b, ⟨b, (floor_coe _).le⟩ lemma tendsto_ceil_at_top : tendsto (ceil : α → ℤ) at_top at_top := ceil_mono.tendsto_at_top_at_top $ λ b, ⟨b, (ceil_coe _).ge⟩ lemma tendsto_ceil_at_bot : tendsto (ceil : α → ℤ) at_bot at_bot := ceil_mono.tendsto_at_bot_at_bot $ λ b, ⟨(b - 1 : ℤ), by { rw ceil_coe, exact (sub_one_lt _).le }⟩ variables [topological_space α] lemma continuous_on_floor (n : ℤ) : continuous_on (λ x, floor x : α → α) (Ico n (n+1) : set α) := (continuous_on_congr $ floor_eq_on_Ico' n).mpr continuous_on_const lemma continuous_on_ceil (n : ℤ) : continuous_on (λ x, ceil x : α → α) (Ioc (n-1) n : set α) := (continuous_on_congr $ ceil_eq_on_Ioc' n).mpr continuous_on_const lemma tendsto_floor_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[≥] n) (𝓝 n) := begin rw ← nhds_within_Ico_eq_nhds_within_Ici (lt_add_one (n : α)), simpa only [floor_coe] using (continuous_on_floor n _ (left_mem_Ico.mpr $ lt_add_one (_ : α))).tendsto end lemma tendsto_ceil_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[≤] n) (𝓝 n) := begin rw ← nhds_within_Ioc_eq_nhds_within_Iic (sub_one_lt (n : α)), simpa only [ceil_coe] using (continuous_on_ceil _ _ (right_mem_Ioc.mpr $ sub_one_lt (_ : α))).tendsto end lemma tendsto_floor_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[≥] n) (𝓝[≥] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_floor_right' _) begin refine (eventually_nhds_within_of_forall $ λ x (hx : (n : α) ≤ x), _), change _ ≤ _, norm_cast, convert ← floor_mono hx, rw floor_eq_iff, exact ⟨le_rfl, lt_add_one _⟩ end lemma tendsto_ceil_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[≤] n) (𝓝[≤] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_ceil_left' _) begin refine (eventually_nhds_within_of_forall $ λ x (hx : x ≤ (n : α)), _), change _ ≤ _, norm_cast, convert ← ceil_mono hx, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_rfl⟩ end lemma tendsto_floor_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[<] n) (𝓝[≤] (n-1)) := begin rw ← nhds_within_Ico_eq_nhds_within_Iio (sub_one_lt (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (floor_eq_on_Ico' (n-1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Iic.mpr $ le_rfl))); norm_cast <|> apply_instance, ring end lemma tendsto_ceil_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[>] n) (𝓝[≥] (n+1)) := begin rw ← nhds_within_Ioc_eq_nhds_within_Ioi (lt_add_one (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (ceil_eq_on_Ioc' (n+1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Ici.mpr $ le_rfl))); norm_cast <|> apply_instance, ring end lemma tendsto_floor_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[<] n) (𝓝 (n-1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_floor_left n), end lemma tendsto_ceil_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[>] n) (𝓝 (n+1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_ceil_right n), end lemma continuous_on_fract [topological_add_group α] (n : ℤ) : continuous_on (fract : α → α) (Ico n (n+1) : set α) := continuous_on_id.sub (continuous_on_floor n) lemma tendsto_fract_left' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[<] n) (𝓝 1) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_left' n); [{norm_cast, ring}, apply_instance, apply_instance] end lemma tendsto_fract_left [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[<] n) (𝓝[<] 1) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_left' _) (eventually_of_forall fract_lt_one) lemma tendsto_fract_right' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[≥] n) (𝓝 0) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_right' n); [exact (sub_self _).symm, apply_instance, apply_instance] end lemma tendsto_fract_right [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[≥] n) (𝓝[≥] 0) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_right' _) (eventually_of_forall fract_nonneg) local notation `I` := (Icc 0 1 : set α) variables [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ] /-- Do not use this, use `continuous_on.comp_fract` instead. -/ lemma continuous_on.comp_fract' {f : β → α → γ} (h : continuous_on (uncurry f) $ (univ : set β) ×ˢ I) (hf : ∀ s, f s 0 = f s 1) : continuous (λ st : β × α, f st.1 $ fract st.2) := begin change continuous ((uncurry f) ∘ (prod.map id (fract))), rw continuous_iff_continuous_at, rintro ⟨s, t⟩, by_cases ht : t = floor t, { rw ht, rw ← continuous_within_at_univ, have : (univ : set (β × α)) ⊆ ((univ : set β) ×ˢ Iio ↑⌊t⌋) ∪ ((univ : set β) ×ˢ Ici ↑⌊t⌋), { rintros p -, rw ← prod_union, exact ⟨trivial, lt_or_le p.2 _⟩ }, refine continuous_within_at.mono _ this, refine continuous_within_at.union _ _, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], have : (uncurry f) (s, 0) = (uncurry f) (s, (1 : α)), by simp [uncurry, hf], rw this, refine (h _ ⟨true.intro, by exact_mod_cast right_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ], rw nhds_within_Icc_eq_nhds_within_Iic (@zero_lt_one α _ _), exact tendsto_id.prod_map (tendsto_nhds_within_mono_right Iio_subset_Iic_self $ tendsto_fract_left _) }, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], refine (h _ ⟨true.intro, by exact_mod_cast left_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ, nhds_within_Icc_eq_nhds_within_Ici (@zero_lt_one α _ _)], exact tendsto_id.prod_map (tendsto_fract_right _) } }, { have : t ∈ Ioo (floor t : α) ((floor t : α) + 1), from ⟨lt_of_le_of_ne (floor_le t) (ne.symm ht), lt_floor_add_one _⟩, apply (h ((prod.map _ fract) _) ⟨trivial, ⟨fract_nonneg _, (fract_lt_one _).le⟩⟩).tendsto.comp, simp only [nhds_prod_eq, nhds_within_prod_eq, nhds_within_univ, id.def, prod.map_mk], exact continuous_at_id.tendsto.prod_map (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (((continuous_on_fract _ _ (Ioo_subset_Ico_self this)).mono Ioo_subset_Ico_self).continuous_at (Ioo_mem_nhds this.1 this.2)) (eventually_of_forall (λ x, ⟨fract_nonneg _, (fract_lt_one _).le⟩)) ) } end lemma continuous_on.comp_fract {s : β → α} {f : β → α → γ} (h : continuous_on (uncurry f) $ (univ : set β) ×ˢ (Icc 0 1 : set α)) (hs : continuous s) (hf : ∀ s, f s 0 = f s 1) : continuous (λ x : β, f x $ int.fract (s x)) := (h.comp_fract' hf).comp (continuous_id.prod_mk hs) /-- A special case of `continuous_on.comp_fract`. -/ lemma continuous_on.comp_fract'' {f : α → β} (h : continuous_on f I) (hf : f 0 = f 1) : continuous (f ∘ fract) := continuous_on.comp_fract (h.comp continuous_on_snd $ λ x hx, (mem_prod.mp hx).2) continuous_id (λ _, hf)
c674185792821490a09531129e1063382f2646e6
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Tactic/NoMatch.lean
a14ba2968803b17545aaec85731b57f280a07518
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
2,243
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.Tactic.OpenPrivate import Lean /- This adds support for the alternative syntax `match x with.` instead of `nomatch x`. It is more powerful because it supports pattern matching on multiple discriminants, like regular `match`, and simply has no alternatives in the match. Along the same lines, `fun.` is a nullary pattern matching function; it is equivalent to `fun x y z => match x, y, z with.` where all variables are introduced in order to find an impossible pattern. The `match x with.` and `intro.` tactics do the same thing but in tactic mode. -/ namespace Lean syntax:lead (name := Parser.Term.noMatch) "match " matchDiscr,* " with" "." : term syntax:lead (name := Parser.Tactic.introNoMatch) "intro" "." : tactic namespace Elab.Term open private elabMatchCore in elabMatch.elabMatchDefault in open private elabMatchAux waitExpectedTypeAndDiscrs in elabMatchCore in @[termElab Parser.Term.noMatch] def elabNoMatch' : TermElab | stx@`(match $discrs,* with.), expectedType? => do let discrs := discrs.getElems if let some i ← discrs.findIdxM? fun discr => return (← isAtomicDiscr? discr).isNone then let discr := discrs[i][1] let discrs := discrs.set! i (← `(x)) return ← elabTerm (← `(let x := $discr; match $discrs,* with.)) expectedType? let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? elabMatchAux none discrs #[] mkNullNode expectedType | _, _ => throwUnsupportedSyntax elab tk:"fun" "." : term <= expectedType => Meta.forallTelescopeReducing expectedType fun args _ => do let mut discrs := #[] let mut binders := #[] for _ in args do let n ← mkFreshIdent tk binders := binders.push n discrs := discrs.push $ mkNode ``Lean.Parser.Term.matchDiscr #[mkNullNode, n] elabTerm (← `(@fun $binders* => match $discrs,* with.)) (some expectedType) macro tk:"λ" "." : term => `(fun%$tk .) end Elab.Term macro "match " discrs:matchDiscr,* " with" "." : tactic => `(tactic| exact match $discrs,* with.) macro "intro" "." : tactic => `(tactic| exact fun.) end Lean
b40e116212100bc415e27cf1356e41470e76f934
8ac070e5078ade6d9ca9577e76883158ced4a937
/Numbers.lean
d869ff466f31ad15c57eb0527533aecc1d98f3a5
[]
no_license
kbuzzard/Numbers
2e5cff4c0102e242e30edf47c7d2547c053500f6
c0166915ee06e901bd46c9168a158c4d139211af
refs/heads/master
1,679,975,844,345
1,617,144,136,000
1,617,144,136,000
353,096,483
2
0
null
null
null
null
UTF-8
Lean
false
false
52
lean
def main : IO Unit := IO.println "Hello, world!"
4dcb9e8b99dc8c7af68c3640692ade58bd1e75a7
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/System/ST.lean
a57aa293f87d912538fd5cc5020eebccbcfd0bed
[ "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
4,413
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 -/ prelude import Init.Classical import Init.Control.EState import Init.Control.Reader def EST (ε : Type) (σ : Type) : Type → Type := EStateM ε σ abbrev ST (σ : Type) := EST Empty σ instance (ε σ : Type) : Monad (EST ε σ) := inferInstanceAs (Monad (EStateM _ _)) instance (ε σ : Type) : MonadExceptOf ε (EST ε σ) := inferInstanceAs (MonadExceptOf ε (EStateM _ _)) instance {ε σ : Type} {α : Type} [Inhabited ε] : Inhabited (EST ε σ α) := inferInstanceAs (Inhabited (EStateM _ _ _)) instance (σ : Type) : Monad (ST σ) := inferInstanceAs (Monad (EST _ _)) -- Auxiliary class for inferring the "state" of `EST` and `ST` monads class STWorld (σ : outParam Type) (m : Type → Type) instance {σ m n} [MonadLift m n] [STWorld σ m] : STWorld σ n := ⟨⟩ instance {ε σ} : STWorld σ (EST ε σ) := ⟨⟩ @[noinline, nospecialize] def runEST {ε α : Type} (x : forall (σ : Type), EST ε σ α) : Except ε α := match x Unit () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error ex _ => Except.error ex @[noinline, nospecialize] def runST {α : Type} (x : forall (σ : Type), ST σ α) : α := match x Unit () with | EStateM.Result.ok a _ => a | EStateM.Result.error ex _ => nomatch ex instance {ε σ} : MonadLift (ST σ) (EST ε σ) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ namespace ST /- References -/ constant RefPointed : PointedType.{0} structure Ref (σ : Type) (α : Type) : Type where ref : RefPointed.type h : Nonempty α instance {σ α} [Inhabited α] : Inhabited (Ref σ α) where default := { ref := RefPointed.val, h := Nonempty.intro arbitrary } namespace Prim /- Auxiliary definition for showing that `ST σ α` is inhabited when we have a `Ref σ α` -/ private noncomputable def inhabitedFromRef {σ α} (r : Ref σ α) : ST σ α := let inh : Inhabited α := Classical.inhabited_of_nonempty r.h pure arbitrary @[extern "lean_st_mk_ref"] constant mkRef {σ α} (a : α) : ST σ (Ref σ α) := pure { ref := RefPointed.val, h := Nonempty.intro a } @[extern "lean_st_ref_get"] constant Ref.get {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_set"] constant Ref.set {σ α} (r : @& Ref σ α) (a : α) : ST σ Unit @[extern "lean_st_ref_swap"] constant Ref.swap {σ α} (r : @& Ref σ α) (a : α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_take"] unsafe constant Ref.take {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_ptr_eq"] constant Ref.ptrEq {σ α} (r1 r2 : @& Ref σ α) : ST σ Bool @[inline] unsafe def Ref.modifyUnsafe {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.take r Ref.set r (f v) @[inline] unsafe def Ref.modifyGetUnsafe {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.take r let (b, a) := f v Ref.set r a pure b @[implementedBy Ref.modifyUnsafe] def Ref.modify {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.get r Ref.set r (f v) @[implementedBy Ref.modifyGetUnsafe] def Ref.modifyGet {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.get r let (b, a) := f v Ref.set r a pure b end Prim section variable {σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST σ) m] @[inline] def mkRef {α : Type} (a : α) : m (Ref σ α) := liftM <| Prim.mkRef a @[inline] def Ref.get {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.get r @[inline] def Ref.set {α : Type} (r : Ref σ α) (a : α) : m Unit := liftM <| Prim.Ref.set r a @[inline] def Ref.swap {α : Type} (r : Ref σ α) (a : α) : m α := liftM <| Prim.Ref.swap r a @[inline] unsafe def Ref.take {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.take r @[inline] def Ref.ptrEq {α : Type} (r1 r2 : Ref σ α) : m Bool := liftM <| Prim.Ref.ptrEq r1 r2 @[inline] def Ref.modify {α : Type} (r : Ref σ α) (f : α → α) : m Unit := liftM <| Prim.Ref.modify r f @[inline] def Ref.modifyGet {α : Type} {β : Type} (r : Ref σ α) (f : α → β × α) : m β := liftM <| Prim.Ref.modifyGet r f end end ST
856a7f504698dc7187ce7e7b05cdd756c3630e58
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/dual.lean
e461e8bb549acac229e96a3340764099355233ef
[ "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
24,875
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Fabian Glöckle -/ import linear_algebra.finite_dimensional import linear_algebra.projection /-! # Dual vector spaces The dual space of an R-module M is the R-module of linear maps `M → R`. ## Main definitions * `dual R M` defines the dual space of M over R. * Given a basis for an `R`-module `M`, `basis.to_dual` produces a map from `M` to `dual R M`. * Given families of vectors `e` and `ε`, `dual_pair e ε` states that these families have the characteristic properties of a basis and a dual. * `dual_annihilator W` is the submodule of `dual R M` where every element annihilates `W`. ## Main results * `to_dual_equiv` : the linear equivalence between the dual module and primal module, given a finite basis. * `dual_pair.basis` and `dual_pair.eq_dual`: if `e` and `ε` form a dual pair, `e` is a basis and `ε` is its dual basis. * `quot_equiv_annihilator`: the quotient by a subspace is isomorphic to its dual annihilator. ## Notation We sometimes use `V'` as local notation for `dual K V`. ## TODO Erdös-Kaplansky theorem about the dimension of a dual vector space in case of infinite dimension. -/ noncomputable theory namespace module variables (R : Type*) (M : Type*) variables [comm_semiring R] [add_comm_monoid M] [module R M] /-- The dual space of an R-module M is the R-module of linear maps `M → R`. -/ @[derive [add_comm_monoid, module R]] def dual := M →ₗ[R] R instance {S : Type*} [comm_ring S] {N : Type*} [add_comm_group N] [module S N] : add_comm_group (dual S N) := by {unfold dual, apply_instance} namespace dual instance : inhabited (dual R M) := by dunfold dual; apply_instance instance : has_coe_to_fun (dual R M) (λ _, M → R) := ⟨linear_map.to_fun⟩ /-- Maps a module M to the dual of the dual of M. See `module.erange_coe` and `module.eval_equiv`. -/ def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.flip linear_map.id @[simp] lemma eval_apply (v : M) (a : dual R M) : eval R M v a = a v := begin dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply] end variables {R M} {M' : Type*} [add_comm_monoid M'] [module R M'] /-- The transposition of linear maps, as a linear map from `M →ₗ[R] M'` to `dual R M' →ₗ[R] dual R M`. -/ def transpose : (M →ₗ[R] M') →ₗ[R] (dual R M' →ₗ[R] dual R M) := (linear_map.llcomp R M M' R).flip lemma transpose_apply (u : M →ₗ[R] M') (l : dual R M') : transpose u l = l.comp u := rfl variables {M'' : Type*} [add_comm_monoid M''] [module R M''] lemma transpose_comp (u : M' →ₗ[R] M'') (v : M →ₗ[R] M') : transpose (u.comp v) = (transpose v).comp (transpose u) := rfl end dual end module namespace basis universes u v w open module module.dual submodule linear_map cardinal function variables {R M K V ι : Type*} section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] [decidable_eq ι] variables (b : basis ι R M) /-- The linear map from a vector space equipped with basis to its dual vector space, taking basis elements to corresponding dual basis elements. -/ def to_dual : M →ₗ[R] module.dual R M := b.constr ℕ $ λ v, b.constr ℕ $ λ w, if w = v then (1 : R) else 0 lemma to_dual_apply (i j : ι) : b.to_dual (b i) (b j) = if i = j then 1 else 0 := by { erw [constr_basis b, constr_basis b], ac_refl } @[simp] lemma to_dual_total_left (f : ι →₀ R) (i : ι) : b.to_dual (finsupp.total ι M R b f) (b i) = f i := begin rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum, linear_map.sum_apply], simp_rw [linear_map.map_smul, linear_map.smul_apply, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq'], split_ifs with h, { refl }, { rw finsupp.not_mem_support_iff.mp h } end @[simp] lemma to_dual_total_right (f : ι →₀ R) (i : ι) : b.to_dual (b i) (finsupp.total ι M R b f) = f i := begin rw [finsupp.total_apply, finsupp.sum, linear_map.map_sum], simp_rw [linear_map.map_smul, to_dual_apply, smul_eq_mul, mul_boole, finset.sum_ite_eq], split_ifs with h, { refl }, { rw finsupp.not_mem_support_iff.mp h } end lemma to_dual_apply_left (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i := by rw [← b.to_dual_total_left, b.total_repr] lemma to_dual_apply_right (i : ι) (m : M) : b.to_dual (b i) m = b.repr m i := by rw [← b.to_dual_total_right, b.total_repr] lemma coe_to_dual_self (i : ι) : b.to_dual (b i) = b.coord i := by { ext, apply to_dual_apply_right } /-- `h.to_dual_flip v` is the linear map sending `w` to `h.to_dual w v`. -/ def to_dual_flip (m : M) : (M →ₗ[R] R) := b.to_dual.flip m lemma to_dual_flip_apply (m₁ m₂ : M) : b.to_dual_flip m₁ m₂ = b.to_dual m₂ m₁ := rfl lemma to_dual_eq_repr (m : M) (i : ι) : b.to_dual m (b i) = b.repr m i := b.to_dual_apply_left m i lemma to_dual_eq_equiv_fun [fintype ι] (m : M) (i : ι) : b.to_dual m (b i) = b.equiv_fun m i := by rw [b.equiv_fun_apply, to_dual_eq_repr] lemma to_dual_inj (m : M) (a : b.to_dual m = 0) : m = 0 := begin rw [← mem_bot R, ← b.repr.ker, mem_ker, linear_equiv.coe_coe], apply finsupp.ext, intro b, rw [← to_dual_eq_repr, a], refl end theorem to_dual_ker : b.to_dual.ker = ⊥ := ker_eq_bot'.mpr b.to_dual_inj theorem to_dual_range [fin : fintype ι] : b.to_dual.range = ⊤ := begin rw eq_top_iff', intro f, rw linear_map.mem_range, let lin_comb : ι →₀ R := finsupp.on_finset fin.elems (λ i, f.to_fun (b i)) _, { use finsupp.total ι M R b lin_comb, apply b.ext, { intros i, rw [b.to_dual_eq_repr _ i, repr_total b], { refl } } }, { intros a _, apply fin.complete } end end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [decidable_eq ι] variables (b : basis ι R M) /-- A vector space is linearly equivalent to its dual space. -/ @[simps] def to_dual_equiv [fintype ι] : M ≃ₗ[R] (dual R M) := linear_equiv.of_bijective b.to_dual (ker_eq_bot.mp b.to_dual_ker) (range_eq_top.mp b.to_dual_range) /-- Maps a basis for `V` to a basis for the dual space. -/ def dual_basis [fintype ι] : basis ι R (dual R M) := b.map b.to_dual_equiv -- We use `j = i` to match `basis.repr_self` lemma dual_basis_apply_self [fintype ι] (i j : ι) : b.dual_basis i (b j) = if j = i then 1 else 0 := by { convert b.to_dual_apply i j using 2, rw @eq_comm _ j i } lemma total_dual_basis [fintype ι] (f : ι →₀ R) (i : ι) : finsupp.total ι (dual R M) R b.dual_basis f (b i) = f i := begin rw [finsupp.total_apply, finsupp.sum_fintype, linear_map.sum_apply], { simp_rw [linear_map.smul_apply, smul_eq_mul, dual_basis_apply_self, mul_boole, finset.sum_ite_eq, if_pos (finset.mem_univ i)] }, { intro, rw zero_smul }, end lemma dual_basis_repr [fintype ι] (l : dual R M) (i : ι) : b.dual_basis.repr l i = l (b i) := by rw [← total_dual_basis b, basis.total_repr b.dual_basis l] lemma dual_basis_equiv_fun [fintype ι] (l : dual R M) (i : ι) : b.dual_basis.equiv_fun l i = l (b i) := by rw [basis.equiv_fun_apply, dual_basis_repr] lemma dual_basis_apply [fintype ι] (i : ι) (m : M) : b.dual_basis i m = b.repr m i := b.to_dual_apply_right i m @[simp] lemma coe_dual_basis [fintype ι] : ⇑b.dual_basis = b.coord := by { ext i x, apply dual_basis_apply } @[simp] lemma to_dual_to_dual [fintype ι] : b.dual_basis.to_dual.comp b.to_dual = dual.eval R M := begin refine b.ext (λ i, b.dual_basis.ext (λ j, _)), rw [linear_map.comp_apply, to_dual_apply_left, coe_to_dual_self, ← coe_dual_basis, dual.eval_apply, basis.repr_self, finsupp.single_apply, dual_basis_apply_self] end theorem eval_ker {ι : Type*} (b : basis ι R M) : (dual.eval R M).ker = ⊥ := begin rw ker_eq_bot', intros m hm, simp_rw [linear_map.ext_iff, dual.eval_apply, zero_apply] at hm, exact (basis.forall_coord_eq_zero_iff _).mp (λ i, hm (b.coord i)) end lemma eval_range {ι : Type*} [fintype ι] (b : basis ι R M) : (eval R M).range = ⊤ := begin classical, rw [← b.to_dual_to_dual, range_comp, b.to_dual_range, map_top, to_dual_range _], apply_instance end /-- A module with a basis is linearly equivalent to the dual of its dual space. -/ def eval_equiv {ι : Type*} [fintype ι] (b : basis ι R M) : M ≃ₗ[R] dual R (dual R M) := linear_equiv.of_bijective (eval R M) (ker_eq_bot.mp b.eval_ker) (range_eq_top.mp b.eval_range) @[simp] lemma eval_equiv_to_linear_map {ι : Type*} [fintype ι] (b : basis ι R M) : (b.eval_equiv).to_linear_map = dual.eval R M := rfl end comm_ring /-- `simp` normal form version of `total_dual_basis` -/ @[simp] lemma total_coord [comm_ring R] [add_comm_group M] [module R M] [fintype ι] (b : basis ι R M) (f : ι →₀ R) (i : ι) : finsupp.total ι (dual R M) R b.coord f (b i) = f i := by { haveI := classical.dec_eq ι, rw [← coe_dual_basis, total_dual_basis] } -- TODO(jmc): generalize to rings, once `module.rank` is generalized theorem dual_dim_eq [field K] [add_comm_group V] [module K V] [fintype ι] (b : basis ι K V) : cardinal.lift (module.rank K V) = module.rank K (dual K V) := begin classical, have := linear_equiv.lift_dim_eq b.to_dual_equiv, simp only [cardinal.lift_umax] at this, rw [this, ← cardinal.lift_umax], apply cardinal.lift_id, end end basis namespace module variables {K V : Type*} variables [field K] [add_comm_group V] [module K V] open module module.dual submodule linear_map cardinal basis finite_dimensional theorem eval_ker : (eval K V).ker = ⊥ := by { classical, exact (basis.of_vector_space K V).eval_ker } -- TODO(jmc): generalize to rings, once `module.rank` is generalized theorem dual_dim_eq [finite_dimensional K V] : cardinal.lift (module.rank K V) = module.rank K (dual K V) := (basis.of_vector_space K V).dual_dim_eq lemma erange_coe [finite_dimensional K V] : (eval K V).range = ⊤ := begin letI : is_noetherian K V := is_noetherian.iff_fg.2 infer_instance, exact (basis.of_vector_space K V).eval_range end variables (K V) /-- A vector space is linearly equivalent to the dual of its dual space. -/ def eval_equiv [finite_dimensional K V] : V ≃ₗ[K] dual K (dual K V) := linear_equiv.of_bijective (eval K V) (ker_eq_bot.mp eval_ker) (range_eq_top.mp erange_coe) variables {K V} @[simp] lemma eval_equiv_to_linear_map [finite_dimensional K V] : (eval_equiv K V).to_linear_map = dual.eval K V := rfl end module section dual_pair open module variables {R M ι : Type*} variables [comm_ring R] [add_comm_group M] [module R M] [decidable_eq ι] /-- `e` and `ε` have characteristic properties of a basis and its dual -/ @[nolint has_inhabited_instance] structure dual_pair (e : ι → M) (ε : ι → (dual R M)) := (eval : ∀ i j : ι, ε i (e j) = if i = j then 1 else 0) (total : ∀ {m : M}, (∀ i, ε i m = 0) → m = 0) [finite : ∀ m : M, fintype {i | ε i m ≠ 0}] end dual_pair namespace dual_pair open module module.dual linear_map function variables {R M ι : Type*} variables [comm_ring R] [add_comm_group M] [module R M] variables {e : ι → M} {ε : ι → dual R M} /-- The coefficients of `v` on the basis `e` -/ def coeffs [decidable_eq ι] (h : dual_pair e ε) (m : M) : ι →₀ R := { to_fun := λ i, ε i m, support := by { haveI := h.finite m, exact {i : ι | ε i m ≠ 0}.to_finset }, mem_support_to_fun := by {intro i, rw set.mem_to_finset, exact iff.rfl } } @[simp] lemma coeffs_apply [decidable_eq ι] (h : dual_pair e ε) (m : M) (i : ι) : h.coeffs m i = ε i m := rfl /-- linear combinations of elements of `e`. This is a convenient abbreviation for `finsupp.total _ M R e l` -/ def lc {ι} (e : ι → M) (l : ι →₀ R) : M := l.sum (λ (i : ι) (a : R), a • (e i)) lemma lc_def (e : ι → M) (l : ι →₀ R) : lc e l = finsupp.total _ _ _ e l := rfl variables [decidable_eq ι] (h : dual_pair e ε) include h lemma dual_lc (l : ι →₀ R) (i : ι) : ε i (dual_pair.lc e l) = l i := begin erw linear_map.map_sum, simp only [h.eval, map_smul, smul_eq_mul], rw finset.sum_eq_single i, { simp }, { intros q q_in q_ne, simp [q_ne.symm] }, { intro p_not_in, simp [finsupp.not_mem_support_iff.1 p_not_in] }, end @[simp] lemma coeffs_lc (l : ι →₀ R) : h.coeffs (dual_pair.lc e l) = l := by { ext i, rw [h.coeffs_apply, h.dual_lc] } /-- For any m : M n, \sum_{p ∈ Q n} (ε p m) • e p = m -/ @[simp] lemma lc_coeffs (m : M) : dual_pair.lc e (h.coeffs m) = m := begin refine eq_of_sub_eq_zero (h.total _), intros i, simp [-sub_eq_add_neg, linear_map.map_sub, h.dual_lc, sub_eq_zero] end /-- `(h : dual_pair e ε).basis` shows the family of vectors `e` forms a basis. -/ @[simps] def basis : basis ι R M := basis.of_repr { to_fun := coeffs h, inv_fun := lc e, left_inv := lc_coeffs h, right_inv := coeffs_lc h, map_add' := λ v w, by { ext i, exact (ε i).map_add v w }, map_smul' := λ c v, by { ext i, exact (ε i).map_smul c v } } @[simp] lemma coe_basis : ⇑h.basis = e := by { ext i, rw basis.apply_eq_iff, ext j, rw [h.basis_repr_apply, coeffs_apply, h.eval, finsupp.single_apply], convert if_congr eq_comm rfl rfl } -- `convert` to get rid of a `decidable_eq` mismatch lemma mem_of_mem_span {H : set ι} {x : M} (hmem : x ∈ submodule.span R (e '' H)) : ∀ i : ι, ε i x ≠ 0 → i ∈ H := begin intros i hi, rcases (finsupp.mem_span_image_iff_total _).mp hmem with ⟨l, supp_l, rfl⟩, apply not_imp_comm.mp ((finsupp.mem_supported' _ _).mp supp_l i), rwa [← lc_def, h.dual_lc] at hi end lemma coe_dual_basis [fintype ι] : ⇑h.basis.dual_basis = ε := funext (λ i, h.basis.ext (λ j, by rw [h.basis.dual_basis_apply_self, h.coe_basis, h.eval, if_congr eq_comm rfl rfl])) end dual_pair namespace submodule universes u v w variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variable {W : submodule R M} /-- The `dual_restrict` of a submodule `W` of `M` is the linear map from the dual of `M` to the dual of `W` such that the domain of each linear map is restricted to `W`. -/ def dual_restrict (W : submodule R M) : module.dual R M →ₗ[R] module.dual R W := linear_map.dom_restrict' W @[simp] lemma dual_restrict_apply (W : submodule R M) (φ : module.dual R M) (x : W) : W.dual_restrict φ x = φ (x : M) := rfl /-- The `dual_annihilator` of a submodule `W` is the set of linear maps `φ` such that `φ w = 0` for all `w ∈ W`. -/ def dual_annihilator {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] (W : submodule R M) : submodule R $ module.dual R M := W.dual_restrict.ker @[simp] lemma mem_dual_annihilator (φ : module.dual R M) : φ ∈ W.dual_annihilator ↔ ∀ w ∈ W, φ w = 0 := begin refine linear_map.mem_ker.trans _, simp_rw [linear_map.ext_iff, dual_restrict_apply], exact ⟨λ h w hw, h ⟨w, hw⟩, λ h w, h w.1 w.2⟩ end lemma dual_restrict_ker_eq_dual_annihilator (W : submodule R M) : W.dual_restrict.ker = W.dual_annihilator := rfl lemma dual_annihilator_sup_eq_inf_dual_annihilator (U V : submodule R M) : (U ⊔ V).dual_annihilator = U.dual_annihilator ⊓ V.dual_annihilator := begin ext φ, rw [mem_inf, mem_dual_annihilator, mem_dual_annihilator, mem_dual_annihilator], split; intro h, { refine ⟨_, _⟩; intros x hx, exact h x (mem_sup.2 ⟨x, hx, 0, zero_mem _, add_zero _⟩), exact h x (mem_sup.2 ⟨0, zero_mem _, x, hx, zero_add _⟩) }, { simp_rw mem_sup, rintro _ ⟨x, hx, y, hy, rfl⟩, rw [linear_map.map_add, h.1 _ hx, h.2 _ hy, add_zero] } end /-- The pullback of a submodule in the dual space along the evaluation map. -/ def dual_annihilator_comap (Φ : submodule R (module.dual R M)) : submodule R M := Φ.dual_annihilator.comap (module.dual.eval R M) lemma mem_dual_annihilator_comap_iff {Φ : submodule R (module.dual R M)} (x : M) : x ∈ Φ.dual_annihilator_comap ↔ ∀ φ ∈ Φ, (φ x : R) = 0 := by simp_rw [dual_annihilator_comap, mem_comap, mem_dual_annihilator, module.dual.eval_apply] end submodule namespace subspace open submodule linear_map universes u v w -- We work in vector spaces because `exists_is_compl` only hold for vector spaces variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [module K V] /-- Given a subspace `W` of `V` and an element of its dual `φ`, `dual_lift W φ` is the natural extension of `φ` to an element of the dual of `V`. That is, `dual_lift W φ` sends `w ∈ W` to `φ x` and `x` in the complement of `W` to `0`. -/ noncomputable def dual_lift (W : subspace K V) : module.dual K W →ₗ[K] module.dual K V := let h := classical.indefinite_description _ W.exists_is_compl in (linear_map.of_is_compl_prod h.2).comp (linear_map.inl _ _ _) variable {W : subspace K V} @[simp] lemma dual_lift_of_subtype {φ : module.dual K W} (w : W) : W.dual_lift φ (w : V) = φ w := by { erw of_is_compl_left_apply _ w, refl } lemma dual_lift_of_mem {φ : module.dual K W} {w : V} (hw : w ∈ W) : W.dual_lift φ w = φ ⟨w, hw⟩ := dual_lift_of_subtype ⟨w, hw⟩ @[simp] lemma dual_restrict_comp_dual_lift (W : subspace K V) : W.dual_restrict.comp W.dual_lift = 1 := by { ext φ x, simp } lemma dual_restrict_left_inverse (W : subspace K V) : function.left_inverse W.dual_restrict W.dual_lift := λ x, show W.dual_restrict.comp W.dual_lift x = x, by { rw [dual_restrict_comp_dual_lift], refl } lemma dual_lift_right_inverse (W : subspace K V) : function.right_inverse W.dual_lift W.dual_restrict := W.dual_restrict_left_inverse lemma dual_restrict_surjective : function.surjective W.dual_restrict := W.dual_lift_right_inverse.surjective lemma dual_lift_injective : function.injective W.dual_lift := W.dual_restrict_left_inverse.injective /-- The quotient by the `dual_annihilator` of a subspace is isomorphic to the dual of that subspace. -/ noncomputable def quot_annihilator_equiv (W : subspace K V) : W.dual_annihilator.quotient ≃ₗ[K] module.dual K W := (quot_equiv_of_eq _ _ W.dual_restrict_ker_eq_dual_annihilator).symm.trans $ W.dual_restrict.quot_ker_equiv_of_surjective dual_restrict_surjective /-- The natural isomorphism forom the dual of a subspace `W` to `W.dual_lift.range`. -/ noncomputable def dual_equiv_dual (W : subspace K V) : module.dual K W ≃ₗ[K] W.dual_lift.range := linear_equiv.of_injective _ dual_lift_injective lemma dual_equiv_dual_def (W : subspace K V) : W.dual_equiv_dual.to_linear_map = W.dual_lift.range_restrict := rfl @[simp] lemma dual_equiv_dual_apply (φ : module.dual K W) : W.dual_equiv_dual φ = ⟨W.dual_lift φ, mem_range.2 ⟨φ, rfl⟩⟩ := rfl section open_locale classical open finite_dimensional variables {V₁ : Type*} [add_comm_group V₁] [module K V₁] instance [H : finite_dimensional K V] : finite_dimensional K (module.dual K V) := linear_equiv.finite_dimensional (basis.of_vector_space K V).to_dual_equiv variables [finite_dimensional K V] [finite_dimensional K V₁] @[simp] lemma dual_finrank_eq : finrank K (module.dual K V) = finrank K V := linear_equiv.finrank_eq (basis.of_vector_space K V).to_dual_equiv.symm /-- The quotient by the dual is isomorphic to its dual annihilator. -/ noncomputable def quot_dual_equiv_annihilator (W : subspace K V) : W.dual_lift.range.quotient ≃ₗ[K] W.dual_annihilator := linear_equiv.quot_equiv_of_quot_equiv $ linear_equiv.trans W.quot_annihilator_equiv W.dual_equiv_dual /-- The quotient by a subspace is isomorphic to its dual annihilator. -/ noncomputable def quot_equiv_annihilator (W : subspace K V) : W.quotient ≃ₗ[K] W.dual_annihilator := begin refine _ ≪≫ₗ W.quot_dual_equiv_annihilator, refine linear_equiv.quot_equiv_of_equiv _ (basis.of_vector_space K V).to_dual_equiv, exact (basis.of_vector_space K W).to_dual_equiv.trans W.dual_equiv_dual end open finite_dimensional @[simp] lemma finrank_dual_annihilator_comap_eq {Φ : subspace K (module.dual K V)} : finrank K Φ.dual_annihilator_comap = finrank K Φ.dual_annihilator := begin rw [submodule.dual_annihilator_comap, ← module.eval_equiv_to_linear_map], exact linear_equiv.finrank_eq (linear_equiv.of_submodule' _ _), end lemma finrank_add_finrank_dual_annihilator_comap_eq (W : subspace K (module.dual K V)) : finrank K W + finrank K W.dual_annihilator_comap = finrank K V := begin rw [finrank_dual_annihilator_comap_eq, W.quot_equiv_annihilator.finrank_eq.symm, add_comm, submodule.finrank_quotient_add_finrank, subspace.dual_finrank_eq], end end end subspace variables {R : Type*} [comm_ring R] {M₁ : Type*} {M₂ : Type*} variables [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] open module /-- Given a linear map `f : M₁ →ₗ[R] M₂`, `f.dual_map` is the linear map between the dual of `M₂` and `M₁` such that it maps the functional `φ` to `φ ∘ f`. -/ def linear_map.dual_map (f : M₁ →ₗ[R] M₂) : dual R M₂ →ₗ[R] dual R M₁ := linear_map.lcomp R R f @[simp] lemma linear_map.dual_map_apply (f : M₁ →ₗ[R] M₂) (g : dual R M₂) (x : M₁) : f.dual_map g x = g (f x) := linear_map.lcomp_apply f g x @[simp] lemma linear_map.dual_map_id : (linear_map.id : M₁ →ₗ[R] M₁).dual_map = linear_map.id := by { ext, refl } lemma linear_map.dual_map_comp_dual_map {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M₁ →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : f.dual_map.comp g.dual_map = (g.comp f).dual_map := rfl /-- The `linear_equiv` version of `linear_map.dual_map`. -/ def linear_equiv.dual_map (f : M₁ ≃ₗ[R] M₂) : dual R M₂ ≃ₗ[R] dual R M₁ := { inv_fun := f.symm.to_linear_map.dual_map, left_inv := begin intro φ, ext x, simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map, linear_map.to_fun_eq_coe, linear_equiv.apply_symm_apply] end, right_inv := begin intro φ, ext x, simp only [linear_map.dual_map_apply, linear_equiv.coe_to_linear_map, linear_map.to_fun_eq_coe, linear_equiv.symm_apply_apply] end, .. f.to_linear_map.dual_map } @[simp] lemma linear_equiv.dual_map_apply (f : M₁ ≃ₗ[R] M₂) (g : dual R M₂) (x : M₁) : f.dual_map g x = g (f x) := linear_map.lcomp_apply f g x @[simp] lemma linear_equiv.dual_map_refl : (linear_equiv.refl R M₁).dual_map = linear_equiv.refl R (dual R M₁) := by { ext, refl } @[simp] lemma linear_equiv.dual_map_symm {f : M₁ ≃ₗ[R] M₂} : (linear_equiv.dual_map f).symm = linear_equiv.dual_map f.symm := rfl lemma linear_equiv.dual_map_trans {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M₁ ≃ₗ[R] M₂) (g : M₂ ≃ₗ[R] M₃) : g.dual_map.trans f.dual_map = (f.trans g).dual_map := rfl namespace linear_map variable (f : M₁ →ₗ[R] M₂) lemma ker_dual_map_eq_dual_annihilator_range : f.dual_map.ker = f.range.dual_annihilator := begin ext φ, split; intro hφ, { rw mem_ker at hφ, rw submodule.mem_dual_annihilator, rintro y ⟨x, rfl⟩, rw [← dual_map_apply, hφ, zero_apply] }, { ext x, rw dual_map_apply, rw submodule.mem_dual_annihilator at hφ, exact hφ (f x) ⟨x, rfl⟩ } end lemma range_dual_map_le_dual_annihilator_ker : f.dual_map.range ≤ f.ker.dual_annihilator := begin rintro _ ⟨ψ, rfl⟩, simp_rw [submodule.mem_dual_annihilator, mem_ker], rintro x hx, rw [dual_map_apply, hx, map_zero] end section finite_dimensional variables {K : Type*} [field K] {V₁ : Type*} {V₂ : Type*} variables [add_comm_group V₁] [module K V₁] [add_comm_group V₂] [module K V₂] open finite_dimensional variable [finite_dimensional K V₂] @[simp] lemma finrank_range_dual_map_eq_finrank_range (f : V₁ →ₗ[K] V₂) : finrank K f.dual_map.range = finrank K f.range := begin have := submodule.finrank_quotient_add_finrank f.range, rw [(subspace.quot_equiv_annihilator f.range).finrank_eq, ← ker_dual_map_eq_dual_annihilator_range] at this, conv_rhs at this { rw ← subspace.dual_finrank_eq }, refine add_left_injective (finrank K f.dual_map.ker) _, change _ + _ = _ + _, rw [finrank_range_add_finrank_ker f.dual_map, add_comm, this], end lemma range_dual_map_eq_dual_annihilator_ker [finite_dimensional K V₁] (f : V₁ →ₗ[K] V₂) : f.dual_map.range = f.ker.dual_annihilator := begin refine eq_of_le_of_finrank_eq f.range_dual_map_le_dual_annihilator_ker _, have := submodule.finrank_quotient_add_finrank f.ker, rw (subspace.quot_equiv_annihilator f.ker).finrank_eq at this, refine add_left_injective (finrank K f.ker) _, simp_rw [this, finrank_range_dual_map_eq_finrank_range], exact finrank_range_add_finrank_ker f, end end finite_dimensional end linear_map
d35d09cea82347ccc3ccc2f4255a951202e1f591
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/pi.lean
a376ae0845e9ffeab095504a3f93a3d437d98bec
[]
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
2,043
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.cauchy import Mathlib.topology.uniform_space.separation import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Indexed product of uniform spaces -/ protected instance Pi.uniform_space {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] : uniform_space ((i : ι) → α i) := uniform_space.of_core_eq uniform_space.to_core Pi.topological_space sorry theorem Pi.uniformity {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] : uniformity ((i : ι) → α i) = infi fun (i : ι) => filter.comap (fun (a : ((i : ι) → α i) × ((i : ι) → α i)) => (prod.fst a i, prod.snd a i)) (uniformity (α i)) := infi_uniformity theorem Pi.uniform_continuous_proj {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] (i : ι) : uniform_continuous fun (a : (i : ι) → α i) => a i := eq.mpr (id (Eq._oldrec (Eq.refl (uniform_continuous fun (a : (i : ι) → α i) => a i)) (propext uniform_continuous_iff))) (infi_le (fun (j : ι) => uniform_space.comap (fun (a : (i : ι) → α i) => a j) (U j)) i) protected instance Pi.complete {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] [∀ (i : ι), complete_space (α i)] : complete_space ((i : ι) → α i) := sorry protected instance Pi.separated {ι : Type u_1} (α : ι → Type u) [U : (i : ι) → uniform_space (α i)] [∀ (i : ι), separated_space (α i)] : separated_space ((i : ι) → α i) := iff.mpr separated_def fun (x y : (i : ι) → α i) (H : ∀ (r : set (((i : ι) → α i) × ((i : ι) → α i))), r ∈ uniformity ((i : ι) → α i) → (x, y) ∈ r) => funext fun (i : ι) => uniform_space.eq_of_separated_of_uniform_continuous (Pi.uniform_continuous_proj α i) H
1e3654f8d7e950efe638949eaaec4ae47b69f252
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/spectrum_of_a_ring/spec_locally_ringed_space.lean
e3caf70efc1e8e2b4c0088c9e9d8c41fa42032c1
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
286
lean
import spectrum_of_a_ring.structure_sheaf import spectrum_of_a_ring.strucutre_sheaf_stalks universe u variables (R : Type u) [comm_ring R] def Spec.locally_ringed_space : locally_ringed_space (Spec R) := { O := structure_sheaf R, Hstalks := λ P, structure_sheaf.stalk_local P, }
92853c1bd52e585668fc596870c2933c978acb5a
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/super_examples.lean
ea4d2bc77b6b1fd017238797c90c309ff27a4351
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,933
lean
import tools.super open tactic constant nat_has_dvd : has_dvd nat attribute [instance] nat_has_dvd noncomputable def prime (n : ℕ) := ∀d, d ∣ n → d = 1 ∨ d = n axiom dvd_refl (m : ℕ) : m ∣ m axiom dvd_mul (m n k : ℕ) : m ∣ n → m ∣ (n*k) axiom nat_mul_cancel_one (m n : ℕ) : m = m * n → n = 1 example {m n : ℕ} : prime (m * n) → m = 1 ∨ n = 1 := by super with dvd_refl dvd_mul nat_mul_cancel_one example : nat.zero ≠ nat.succ nat.zero := by super example (x y : ℕ) : nat.succ x = nat.succ y → x = y := by super example (i) (a b c : i) : [a,b,c] = [b,c,a] -> a = b ∧ b = c := by super definition is_positive (n : ℕ) := n > 0 example (n : ℕ) : n > 0 ↔ is_positive n := by super example (m n : ℕ) : 0 + m = 0 + n → m = n := by super with nat.zero_add example : ∀x y : ℕ, x + y = y + x := begin intros, induction x, note h : nat.zero = 0 := rfl, super with nat.add_zero nat.zero_add, super with nat.add_succ nat.succ_add end example (i) [inhabited i] : nonempty i := by super example (i) [nonempty i] : ¬(inhabited i → false) := by super example : nonempty ℕ := by super example : ¬(inhabited ℕ → false) := by super example {a b} : ¬(b ∨ ¬a) ∨ (a → b) := by super example {a} : a ∨ ¬a := by super example {a} : (a ∧ a) ∨ (¬a ∧ ¬a) := by super example (i) (c : i) (p : i → Prop) (f : i → i) : p c → (∀x, p x → p (f x)) → p (f (f (f c))) := by super example (i) (p : i → Prop) : ∀x, p x → ∃x, p x := by super example (i) [nonempty i] (p : i → i → Prop) : (∀x y, p x y) → ∃x, ∀z, p x z := by super example (i) [nonempty i] (p : i → Prop) : (∀x, p x) → ¬¬∀x, p x := by super -- Requires non-empty domain. example {i} [nonempty i] (p : i → Prop) : (∀x y, p x ∨ p y) → ∃x y, p x ∧ p y := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p b → p a := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p a → p b := by super example (i) (a b : i) (p : i → Prop) (H : a = b) : p b = p a := by super example (i) (c : i) (p : i → Prop) (f g : i → i) : p c → (∀x, p x → p (f x)) → (∀x, p x → f x = g x) → f (f c) = g (g c) := by super example (i) (p q : i → i → Prop) (a b c d : i) : (∀x y z, p x y ∧ p y z → p x z) → (∀x y z, q x y ∧ q y z → q x z) → (∀x y, q x y → q y x) → (∀x y, p x y ∨ q x y) → p a b ∨ q c d := by super -- This example from Davis-Putnam actually requires a non-empty domain example (i) [nonempty i] (f g : i → i → Prop) : ∃x y, ∀z, (f x y → f y z ∧ f z z) ∧ (f x y ∧ g x y → g x z ∧ g z z) := by super example (person) [nonempty person] (drinks : person → Prop) : ∃canary, drinks canary → ∀other, drinks other := by super example {p q : ℕ → Prop} {r} : (∀x y, p x ∧ q y ∧ r) -> ∀x, (p x ∧ r ∧ q x) := by super
37b0fe55414f92f97c97d83515fb9cd37cf4c5bb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/preserves/limits.lean
6815e38e1b0d12672eccc1dd0dc2d6e79f26d771
[]
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
5,644
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.preserves.basic import Mathlib.PostPort universes v u₁ u₂ namespace Mathlib /-! # Isomorphisms about functors which preserve (co)limits If `G` preserves limits, and `C` and `D` have limits, then for any diagram `F : J ⥤ C` we have a canonical isomorphism `preserves_limit_iso : G.obj (limit F) ≅ limit (F ⋙ G)`. We also show that we can commute `is_limit.lift` of a preserved limit with `functor.map_cone`: `(preserves_limit.preserves t).lift (G.map_cone c₂) = G.map (t.lift c₂)`. The duals of these are also given. For functors which preserve (co)limits of specific shapes, see `preserves/shapes.lean`. -/ namespace category_theory @[simp] theorem preserves_lift_map_cone {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_limit F G] (c₁ : limits.cone F) (c₂ : limits.cone F) (t : limits.is_limit c₁) : limits.is_limit.lift (limits.preserves_limit.preserves t) (functor.map_cone G c₂) = functor.map G (limits.is_limit.lift t c₂) := sorry /-- If `G` preserves limits, we have an isomorphism from the image of the limit of a functor `F` to the limit of the functor `F ⋙ G`. -/ def preserves_limit_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_limit F G] [limits.has_limit F] [limits.has_limit (F ⋙ G)] : functor.obj G (limits.limit F) ≅ limits.limit (F ⋙ G) := limits.is_limit.cone_point_unique_up_to_iso (limits.preserves_limit.preserves (limits.limit.is_limit F)) (limits.limit.is_limit (F ⋙ G)) @[simp] theorem preserves_limits_iso_hom_π_assoc {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_limit F G] [limits.has_limit F] [limits.has_limit (F ⋙ G)] (j : J) {X' : D} (f' : functor.obj (F ⋙ G) j ⟶ X') : iso.hom (preserves_limit_iso G F) ≫ limits.limit.π (F ⋙ G) j ≫ f' = functor.map G (limits.limit.π F j) ≫ f' := sorry @[simp] theorem preserves_limits_iso_inv_π_assoc {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_limit F G] [limits.has_limit F] [limits.has_limit (F ⋙ G)] (j : J) {X' : D} (f' : functor.obj G (functor.obj F j) ⟶ X') : iso.inv (preserves_limit_iso G F) ≫ functor.map G (limits.limit.π F j) ≫ f' = limits.limit.π (F ⋙ G) j ≫ f' := sorry @[simp] theorem lift_comp_preserves_limits_iso_hom_assoc {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_limit F G] [limits.has_limit F] [limits.has_limit (F ⋙ G)] (t : limits.cone F) {X' : D} (f' : limits.limit (F ⋙ G) ⟶ X') : functor.map G (limits.limit.lift F t) ≫ iso.hom (preserves_limit_iso G F) ≫ f' = limits.limit.lift (F ⋙ G) (functor.map_cone G t) ≫ f' := sorry @[simp] theorem preserves_desc_map_cocone {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_colimit F G] (c₁ : limits.cocone F) (c₂ : limits.cocone F) (t : limits.is_colimit c₁) : limits.is_colimit.desc (limits.preserves_colimit.preserves t) (functor.map_cocone G c₂) = functor.map G (limits.is_colimit.desc t c₂) := sorry /-- If `G` preserves colimits, we have an isomorphism from the image of the colimit of a functor `F` to the colimit of the functor `F ⋙ G`. -/ -- TODO: think about swapping the order here def preserves_colimit_iso {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_colimit F G] [limits.has_colimit F] [limits.has_colimit (F ⋙ G)] : functor.obj G (limits.colimit F) ≅ limits.colimit (F ⋙ G) := limits.is_colimit.cocone_point_unique_up_to_iso (limits.preserves_colimit.preserves (limits.colimit.is_colimit F)) (limits.colimit.is_colimit (F ⋙ G)) @[simp] theorem ι_preserves_colimits_iso_inv_assoc {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_colimit F G] [limits.has_colimit F] [limits.has_colimit (F ⋙ G)] (j : J) {X' : D} (f' : functor.obj G (limits.colimit F) ⟶ X') : limits.colimit.ι (F ⋙ G) j ≫ iso.inv (preserves_colimit_iso G F) ≫ f' = functor.map G (limits.colimit.ι F j) ≫ f' := sorry @[simp] theorem ι_preserves_colimits_iso_hom_assoc {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_colimit F G] [limits.has_colimit F] [limits.has_colimit (F ⋙ G)] (j : J) {X' : D} (f' : limits.colimit (F ⋙ G) ⟶ X') : functor.map G (limits.colimit.ι F j) ≫ iso.hom (preserves_colimit_iso G F) ≫ f' = limits.colimit.ι (F ⋙ G) j ≫ f' := sorry @[simp] theorem preserves_colimits_iso_inv_comp_desc {C : Type u₁} [category C] {D : Type u₂} [category D] (G : C ⥤ D) {J : Type v} [small_category J] (F : J ⥤ C) [limits.preserves_colimit F G] [limits.has_colimit F] [limits.has_colimit (F ⋙ G)] (t : limits.cocone F) : iso.inv (preserves_colimit_iso G F) ≫ functor.map G (limits.colimit.desc F t) = limits.colimit.desc (F ⋙ G) (functor.map_cocone G t) := sorry
6b035c3c8543b0f631009207116bb5f2439d2fbb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finite/basic.lean
b92e642b7944df5bf4259caa278471250846f6e7
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,150
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.fintype.powerset import data.fintype.prod import data.fintype.sigma import data.fintype.sum import data.fintype.vector /-! # Finite types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove some theorems about `finite` and provide some instances. This typeclass is a `Prop`-valued counterpart of the typeclass `fintype`. See more details in the file where `finite` is defined. ## Main definitions * `fintype.finite`, `finite.of_fintype` creates a `finite` instance from a `fintype` instance. The former lemma takes `fintype α` as an explicit argument while the latter takes it as an instance argument. * `fintype.of_finite` noncomputably creates a `fintype` instance from a `finite` instance. ## Implementation notes There is an apparent duplication of many `fintype` instances in this module, however they follow a pattern: if a `fintype` instance depends on `decidable` instances or other `fintype` instances, then we need to "lower" the instance to be a `finite` instance by removing the `decidable` instances and switching the `fintype` instances to `finite` instances. These are precisely the ones that cannot be inferred using `finite.of_fintype`. (However, when using `open_locale classical` or the `classical` tactic the instances relying only on `decidable` instances will give `finite` instances.) In the future we might consider writing automation to create these "lowered" instances. ## Tags finiteness, finite types -/ noncomputable theory open_locale classical variables {α β γ : Type*} namespace finite @[priority 100] -- see Note [lower instance priority] instance of_subsingleton {α : Sort*} [subsingleton α] : finite α := of_injective (function.const α ()) $ function.injective_of_subsingleton _ @[nolint instance_priority] -- Higher priority for `Prop`s instance prop (p : Prop) : finite p := finite.of_subsingleton instance [finite α] [finite β] : finite (α × β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, apply_instance } instance {α β : Sort*} [finite α] [finite β] : finite (pprod α β) := of_equiv _ equiv.pprod_equiv_prod_plift.symm lemma prod_left (β) [finite (α × β)] [nonempty β] : finite α := of_surjective (prod.fst : α × β → α) prod.fst_surjective lemma prod_right (α) [finite (α × β)] [nonempty α] : finite β := of_surjective (prod.snd : α × β → β) prod.snd_surjective instance [finite α] [finite β] : finite (α ⊕ β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, apply_instance } lemma sum_left (β) [finite (α ⊕ β)] : finite α := of_injective (sum.inl : α → α ⊕ β) sum.inl_injective lemma sum_right (α) [finite (α ⊕ β)] : finite β := of_injective (sum.inr : β → α ⊕ β) sum.inr_injective instance {β : α → Type*} [finite α] [Π a, finite (β a)] : finite (Σ a, β a) := by { letI := fintype.of_finite α, letI := λ a, fintype.of_finite (β a), apply_instance } instance {ι : Sort*} {π : ι → Sort*} [finite ι] [Π i, finite (π i)] : finite (Σ' i, π i) := of_equiv _ (equiv.psigma_equiv_sigma_plift π).symm instance [finite α] : finite (set α) := by { casesI nonempty_fintype α, apply_instance } end finite /-- This instance also provides `[finite s]` for `s : set α`. -/ instance subtype.finite {α : Sort*} [finite α] {p : α → Prop} : finite {x // p x} := finite.of_injective coe subtype.coe_injective instance pi.finite {α : Sort*} {β : α → Sort*} [finite α] [∀ a, finite (β a)] : finite (Π a, β a) := begin haveI := fintype.of_finite (plift α), haveI := λ a, fintype.of_finite (plift (β a)), exact finite.of_equiv (Π (a : plift α), plift (β (equiv.plift a))) (equiv.Pi_congr equiv.plift (λ _, equiv.plift)), end instance vector.finite {α : Type*} [finite α] {n : ℕ} : finite (vector α n) := by { haveI := fintype.of_finite α, apply_instance } instance quot.finite {α : Sort*} [finite α] (r : α → α → Prop) : finite (quot r) := finite.of_surjective _ (surjective_quot_mk r) instance quotient.finite {α : Sort*} [finite α] (s : setoid α) : finite (quotient s) := quot.finite _ instance function.embedding.finite {α β : Sort*} [finite β] : finite (α ↪ β) := begin casesI is_empty_or_nonempty (α ↪ β) with _ h, { apply_instance, }, { refine h.elim (λ f, _), haveI : finite α := finite.of_injective _ f.injective, exact finite.of_injective _ fun_like.coe_injective }, end instance equiv.finite_right {α β : Sort*} [finite β] : finite (α ≃ β) := finite.of_injective equiv.to_embedding $ λ e₁ e₂ h, equiv.ext $ by convert fun_like.congr_fun h instance equiv.finite_left {α β : Sort*} [finite α] : finite (α ≃ β) := finite.of_equiv _ ⟨equiv.symm, equiv.symm, equiv.symm_symm, equiv.symm_symm⟩ instance [finite α] {n : ℕ} : finite (sym α n) := by { haveI := fintype.of_finite α, apply_instance }
d2fcc47aee76c83181560a0715a211d06d234ff5
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/integral/set_integral.lean
fc4be754323a52f339eb2c639b4f554b5cd925c8
[ "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
63,766
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.integral.integrable_on import measure_theory.integral.bochner import measure_theory.function.locally_integrable import order.filter.indicator_function import topology.metric_space.thickened_indicator import topology.continuous_function.compact /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We use the property `integrable_on f s μ := integrable f (μ.restrict s)`, defined in `measure_theory.integrable_on`. We also defined in that same file a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.small_sets`, i.e. for any `ε>0` there exists `t ∈ l` such that `‖∫ x in s, f x ∂μ - μ s • c‖ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation We provide the following notations for expressing the integral of a function on a set : * `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f` * `∫ a in s, f a` is `∫ a in s, f a ∂volume` Note that the set notations are defined in the file `measure_theory/integral/bochner`, but we reference them here because all theorems about set integrals are in this file. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topology interval big_operators filter ennreal nnreal measure_theory variables {α β E F : Type*} [measurable_space α] namespace measure_theory section normed_add_comm_group variables [normed_add_comm_group E] {f g : α → E} {s t : set α} {μ ν : measure α} {l l' : filter α} variables [complete_space E] [normed_space ℝ E] lemma set_integral_congr_ae₀ (hs : null_measurable_set s μ) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff'₀ hs).2 h) lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff' hs).2 h) lemma set_integral_congr₀ (hs : null_measurable_set s μ) (h : eq_on f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := set_integral_congr_ae₀ hs $ eventually_of_forall h lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := set_integral_congr_ae hs $ eventually_of_forall h lemma set_integral_congr_set_ae (hst : s =ᵐ[μ] t) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := by rw measure.restrict_congr_set hst lemma integral_union_ae (hst : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union₀ hst ht, integral_add_measure hfs hft] lemma integral_union (hst : disjoint s t) (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := integral_union_ae hst.ae_disjoint ht.null_measurable_set hfs hft lemma integral_diff (ht : measurable_set t) (hfs : integrable_on f s μ) (hts : t ⊆ s) : ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ - ∫ x in t, f x ∂μ := begin rw [eq_sub_iff_add_eq, ← integral_union, diff_union_of_subset hts], exacts [disjoint_sdiff_self_left, ht, hfs.mono_set (diff_subset _ _), hfs.mono_set hts] end lemma integral_inter_add_diff₀ (ht : null_measurable_set t μ) (hfs : integrable_on f s μ) : ∫ x in s ∩ t, f x ∂μ + ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ := begin rw [← measure.restrict_inter_add_diff₀ s ht, integral_add_measure], { exact integrable.mono_measure hfs (measure.restrict_mono (inter_subset_left _ _) le_rfl) }, { exact integrable.mono_measure hfs (measure.restrict_mono (diff_subset _ _) le_rfl) } end lemma integral_inter_add_diff (ht : measurable_set t) (hfs : integrable_on f s μ) : ∫ x in s ∩ t, f x ∂μ + ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ := integral_inter_add_diff₀ ht.null_measurable_set hfs lemma integral_finset_bUnion {ι : Type*} (t : finset ι) {s : ι → set α} (hs : ∀ i ∈ t, measurable_set (s i)) (h's : set.pairwise ↑t (disjoint on s)) (hf : ∀ i ∈ t, integrable_on f (s i) μ) : ∫ x in (⋃ i ∈ t, s i), f x ∂ μ = ∑ i in t, ∫ x in s i, f x ∂ μ := begin induction t using finset.induction_on with a t hat IH hs h's, { simp }, { simp only [finset.coe_insert, finset.forall_mem_insert, set.pairwise_insert, finset.set_bUnion_insert] at hs hf h's ⊢, rw [integral_union _ _ hf.1 (integrable_on_finset_Union.2 hf.2)], { rw [finset.sum_insert hat, IH hs.2 h's.1 hf.2] }, { simp only [disjoint_Union_right], exact (λ i hi, (h's.2 i hi (ne_of_mem_of_not_mem hi hat).symm).1) }, { exact finset.measurable_set_bUnion _ hs.2 } } end lemma integral_fintype_Union {ι : Type*} [fintype ι] {s : ι → set α} (hs : ∀ i, measurable_set (s i)) (h's : pairwise (disjoint on s)) (hf : ∀ i, integrable_on f (s i) μ) : ∫ x in (⋃ i, s i), f x ∂ μ = ∑ i, ∫ x in s i, f x ∂ μ := begin convert integral_finset_bUnion finset.univ (λ i hi, hs i) _ (λ i _, hf i), { simp }, { simp [pairwise_univ, h's] } end lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl₀ (hs : null_measurable_set s μ) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union_ae (@disjoint_compl_right (set α) _ _).ae_disjoint hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := integral_add_compl₀ hs.null_measurable_set hfi /-- For a function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hs : measurable_set s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := begin by_cases hfi : integrable_on f s μ, swap, { rwa [integral_undef, integral_undef], rwa integrable_indicator_iff hs }, calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.integrable_indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs)) (integral_congr_ae (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp end lemma set_integral_indicator (ht : measurable_set t) : ∫ x in s, t.indicator f x ∂μ = ∫ x in s ∩ t, f x ∂μ := by rw [integral_indicator ht, measure.restrict_restrict ht, set.inter_comm] lemma of_real_set_integral_one_of_measure_ne_top {α : Type*} {m : measurable_space α} {μ : measure α} {s : set α} (hs : μ s ≠ ∞) : ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = μ s := calc ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = ennreal.of_real (∫ x in s, ‖(1 : ℝ)‖ ∂μ) : by simp only [norm_one] ... = ∫⁻ x in s, 1 ∂μ : begin rw of_real_integral_norm_eq_lintegral_nnnorm (integrable_on_const.2 (or.inr hs.lt_top)), simp only [nnnorm_one, ennreal.coe_one], end ... = μ s : set_lintegral_one _ lemma of_real_set_integral_one {α : Type*} {m : measurable_space α} (μ : measure α) [is_finite_measure μ] (s : set α) : ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = μ s := of_real_set_integral_one_of_measure_ne_top (measure_ne_top μ s) lemma integral_piecewise [decidable_pred (∈ s)] (hs : measurable_set s) (hf : integrable_on f s μ) (hg : integrable_on g sᶜ μ) : ∫ x, s.piecewise f g x ∂μ = ∫ x in s, f x ∂μ + ∫ x in sᶜ, g x ∂μ := by rw [← set.indicator_add_compl_eq_piecewise, integral_add' (hf.integrable_indicator hs) (hg.integrable_indicator hs.compl), integral_indicator hs, integral_indicator hs.compl] lemma tendsto_set_integral_of_monotone {ι : Type*} [countable ι] [semilattice_sup ι] {s : ι → set α} (hsm : ∀ i, measurable_set (s i)) (h_mono : monotone s) (hfi : integrable_on f (⋃ n, s n) μ) : tendsto (λ i, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋃ n, s n), f a ∂μ)) := begin have hfi' : ∫⁻ x in ⋃ n, s n, ‖f x‖₊ ∂μ < ∞ := hfi.2, set S := ⋃ i, s i, have hSm : measurable_set S := measurable_set.Union hsm, have hsub : ∀ {i}, s i ⊆ S, from subset_Union s, rw [← with_density_apply _ hSm] at hfi', set ν := μ.with_density (λ x, ‖f x‖₊) with hν, refine metric.nhds_basis_closed_ball.tendsto_right_iff.2 (λ ε ε0, _), lift ε to ℝ≥0 using ε0.le, have : ∀ᶠ i in at_top, ν (s i) ∈ Icc (ν S - ε) (ν S + ε), from tendsto_measure_Union h_mono (ennreal.Icc_mem_nhds hfi'.ne (ennreal.coe_pos.2 ε0).ne'), refine this.mono (λ i hi, _), rw [mem_closed_ball_iff_norm', ← integral_diff (hsm i) hfi hsub, ← coe_nnnorm, nnreal.coe_le_coe, ← ennreal.coe_le_coe], refine (ennnorm_integral_le_lintegral_ennnorm _).trans _, rw [← with_density_apply _ (hSm.diff (hsm _)), ← hν, measure_diff hsub (hsm _)], exacts [tsub_le_iff_tsub_le.mp hi.1, (hi.2.trans_lt $ ennreal.add_lt_top.2 ⟨hfi', ennreal.coe_lt_top⟩).ne] end lemma has_sum_integral_Union_ae {ι : Type*} [countable ι] {s : ι → set α} (hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) (hfi : integrable_on f (⋃ i, s i) μ) : has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) := begin simp only [integrable_on, measure.restrict_Union_ae hd hm] at hfi ⊢, exact has_sum_integral_measure hfi end lemma has_sum_integral_Union {ι : Type*} [countable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (hfi : integrable_on f (⋃ i, s i) μ) : has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) := has_sum_integral_Union_ae (λ i, (hm i).null_measurable_set) (hd.mono (λ i j h, h.ae_disjoint)) hfi lemma integral_Union {ι : Type*} [countable ι] {s : ι → set α} (hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s)) (hfi : integrable_on f (⋃ i, s i) μ) : (∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ := (has_sum.tsum_eq (has_sum_integral_Union hm hd hfi)).symm lemma integral_Union_ae {ι : Type*} [countable ι] {s : ι → set α} (hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) (hfi : integrable_on f (⋃ i, s i) μ) : (∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ := (has_sum.tsum_eq (has_sum_integral_Union_ae hm hd hfi)).symm lemma set_integral_eq_zero_of_ae_eq_zero (ht_eq : ∀ᵐ x ∂μ, x ∈ t → f x = 0) : ∫ x in t, f x ∂μ = 0 := begin by_cases hf : ae_strongly_measurable f (μ.restrict t), swap, { rw integral_undef, contrapose! hf, exact hf.1 }, have : ∫ x in t, hf.mk f x ∂μ = 0, { refine integral_eq_zero_of_ae _, rw [eventually_eq, ae_restrict_iff (hf.strongly_measurable_mk.measurable_set_eq_fun strongly_measurable_zero)], filter_upwards [ae_imp_of_ae_restrict hf.ae_eq_mk, ht_eq] with x hx h'x h''x, rw ← hx h''x, exact h'x h''x }, rw ← this, exact integral_congr_ae hf.ae_eq_mk, end lemma set_integral_eq_zero_of_forall_eq_zero (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in t, f x ∂μ = 0 := set_integral_eq_zero_of_ae_eq_zero (eventually_of_forall ht_eq) lemma integral_union_eq_left_of_ae_aux (ht_eq : ∀ᵐ x ∂(μ.restrict t), f x = 0) (haux : strongly_measurable f) (H : integrable_on f (s ∪ t) μ) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := begin let k := f ⁻¹' {0}, have hk : measurable_set k, { borelize E, exact haux.measurable (measurable_set_singleton _) }, have h's : integrable_on f s μ := H.mono (subset_union_left _ _) le_rfl, have A : ∀ (u : set α), ∫ x in u ∩ k, f x ∂μ = 0 := λ u, set_integral_eq_zero_of_forall_eq_zero (λ x hx, hx.2), rw [← integral_inter_add_diff hk h's, ← integral_inter_add_diff hk H, A, A, zero_add, zero_add, union_diff_distrib, union_comm], apply set_integral_congr_set_ae, rw union_ae_eq_right, apply measure_mono_null (diff_subset _ _), rw measure_zero_iff_ae_nmem, filter_upwards [ae_imp_of_ae_restrict ht_eq] with x hx h'x using h'x.2 (hx h'x.1), end lemma integral_union_eq_left_of_ae (ht_eq : ∀ᵐ x ∂(μ.restrict t), f x = 0) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := begin have ht : integrable_on f t μ, { apply integrable_on_zero.congr_fun_ae, symmetry, exact ht_eq }, by_cases H : integrable_on f (s ∪ t) μ, swap, { rw [integral_undef H, integral_undef], simpa [integrable_on_union, ht] using H }, let f' := H.1.mk f, calc ∫ (x : α) in s ∪ t, f x ∂μ = ∫ (x : α) in s ∪ t, f' x ∂μ : integral_congr_ae H.1.ae_eq_mk ... = ∫ x in s, f' x ∂μ : begin apply integral_union_eq_left_of_ae_aux _ H.1.strongly_measurable_mk (H.congr_fun_ae H.1.ae_eq_mk), filter_upwards [ht_eq, ae_mono (measure.restrict_mono (subset_union_right s t) le_rfl) H.1.ae_eq_mk] with x hx h'x, rw [← h'x, hx] end ... = ∫ x in s, f x ∂μ : integral_congr_ae (ae_mono (measure.restrict_mono (subset_union_left s t) le_rfl) H.1.ae_eq_mk.symm) end lemma integral_union_eq_left_of_forall₀ {f : α → E} (ht : null_measurable_set t μ) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := integral_union_eq_left_of_ae ((ae_restrict_iff'₀ ht).2 (eventually_of_forall ht_eq)) lemma integral_union_eq_left_of_forall {f : α → E} (ht : measurable_set t) (ht_eq : ∀ x ∈ t, f x = 0) : ∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ := integral_union_eq_left_of_forall₀ ht.null_measurable_set ht_eq lemma set_integral_eq_of_subset_of_ae_diff_eq_zero_aux (hts : s ⊆ t) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0) (haux : strongly_measurable f) (h'aux : integrable_on f t μ) : ∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ := begin let k := f ⁻¹' {0}, have hk : measurable_set k, { borelize E, exact haux.measurable (measurable_set_singleton _) }, calc ∫ x in t, f x ∂μ = ∫ x in t ∩ k, f x ∂μ + ∫ x in t \ k, f x ∂μ : by rw integral_inter_add_diff hk h'aux ... = ∫ x in t \ k, f x ∂μ : by { rw [set_integral_eq_zero_of_forall_eq_zero (λ x hx, _), zero_add], exact hx.2 } ... = ∫ x in s \ k, f x ∂μ : begin apply set_integral_congr_set_ae, filter_upwards [h't] with x hx, change (x ∈ t \ k) = (x ∈ s \ k), simp only [mem_preimage, mem_singleton_iff, eq_iff_iff, and.congr_left_iff, mem_diff], assume h'x, by_cases xs : x ∈ s, { simp only [xs, hts xs] }, { simp only [xs, iff_false], assume xt, exact h'x (hx ⟨xt, xs⟩) } end ... = ∫ x in s ∩ k, f x ∂μ + ∫ x in s \ k, f x ∂μ : begin have : ∀ x ∈ s ∩ k, f x = 0 := λ x hx, hx.2, rw [set_integral_eq_zero_of_forall_eq_zero this, zero_add], end ... = ∫ x in s, f x ∂μ : by rw integral_inter_add_diff hk (h'aux.mono hts le_rfl) end /-- If a function vanishes almost everywhere on `t \ s` with `s ⊆ t`, then its integrals on `s` and `t` coincide if `t` is null-measurable. -/ lemma set_integral_eq_of_subset_of_ae_diff_eq_zero (ht : null_measurable_set t μ) (hts : s ⊆ t) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0) : ∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ := begin by_cases h : integrable_on f t μ, swap, { have : ¬(integrable_on f s μ) := λ H, h (H.of_ae_diff_eq_zero ht h't), rw [integral_undef h, integral_undef this] }, let f' := h.1.mk f, calc ∫ x in t, f x ∂μ = ∫ x in t, f' x ∂μ : integral_congr_ae h.1.ae_eq_mk ... = ∫ x in s, f' x ∂μ : begin apply set_integral_eq_of_subset_of_ae_diff_eq_zero_aux hts _ h.1.strongly_measurable_mk (h.congr h.1.ae_eq_mk), filter_upwards [h't, ae_imp_of_ae_restrict h.1.ae_eq_mk] with x hx h'x h''x, rw [← h'x h''x.1, hx h''x] end ... = ∫ x in s, f x ∂μ : begin apply integral_congr_ae, apply ae_restrict_of_ae_restrict_of_subset hts, exact h.1.ae_eq_mk.symm end end /-- If a function vanishes on `t \ s` with `s ⊆ t`, then its integrals on `s` and `t` coincide if `t` is measurable. -/ lemma set_integral_eq_of_subset_of_forall_diff_eq_zero (ht : measurable_set t) (hts : s ⊆ t) (h't : ∀ x ∈ t \ s, f x = 0) : ∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ := set_integral_eq_of_subset_of_ae_diff_eq_zero ht.null_measurable_set hts (eventually_of_forall (λ x hx, h't x hx)) /-- If a function vanishes almost everywhere on `sᶜ`, then its integral on `s` coincides with its integral on the whole space. -/ lemma set_integral_eq_integral_of_ae_compl_eq_zero (h : ∀ᵐ x ∂μ, x ∉ s → f x = 0) : ∫ x in s, f x ∂μ = ∫ x, f x ∂μ := begin conv_rhs { rw ← integral_univ }, symmetry, apply set_integral_eq_of_subset_of_ae_diff_eq_zero null_measurable_set_univ (subset_univ _), filter_upwards [h] with x hx h'x using hx h'x.2, end /-- If a function vanishes on `sᶜ`, then its integral on `s` coincides with its integral on the whole space. -/ lemma set_integral_eq_integral_of_forall_compl_eq_zero (h : ∀ x, x ∉ s → f x = 0) : ∫ x in s, f x ∂μ = ∫ x, f x ∂μ := set_integral_eq_integral_of_ae_compl_eq_zero (eventually_of_forall h) lemma set_integral_neg_eq_set_integral_nonpos [linear_order E] {f : α → E} (hf : ae_strongly_measurable f μ) : ∫ x in {x | f x < 0}, f x ∂μ = ∫ x in {x | f x ≤ 0}, f x ∂μ := begin have h_union : {x | f x ≤ 0} = {x | f x < 0} ∪ {x | f x = 0}, by { ext, simp_rw [set.mem_union, set.mem_set_of_eq], exact le_iff_lt_or_eq, }, rw h_union, have B : null_measurable_set {x | f x = 0} μ, from hf.null_measurable_set_eq_fun ae_strongly_measurable_zero, symmetry, refine integral_union_eq_left_of_ae _, filter_upwards [ae_restrict_mem₀ B] with x hx using hx, end lemma integral_norm_eq_pos_sub_neg {f : α → ℝ} (hfi : integrable f μ) : ∫ x, ‖f x‖ ∂μ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ := have h_meas : null_measurable_set {x | 0 ≤ f x} μ, from ae_strongly_measurable_const.null_measurable_set_le hfi.1, calc ∫ x, ‖f x‖ ∂μ = ∫ x in {x | 0 ≤ f x}, ‖f x‖ ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ‖f x‖ ∂μ : by rw ← integral_add_compl₀ h_meas hfi.norm ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ‖f x‖ ∂μ : begin congr' 1, refine set_integral_congr₀ h_meas (λ x hx, _), dsimp only, rw [real.norm_eq_abs, abs_eq_self.mpr _], exact hx, end ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | 0 ≤ f x}ᶜ, f x ∂μ : begin congr' 1, rw ← integral_neg, refine set_integral_congr₀ h_meas.compl (λ x hx, _), dsimp only, rw [real.norm_eq_abs, abs_eq_neg_self.mpr _], rw [set.mem_compl_iff, set.nmem_set_of_iff] at hx, linarith, end ... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ : by { rw ← set_integral_neg_eq_set_integral_nonpos hfi.1, congr, ext1 x, simp, } lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator s_meas, ← set_integral_const] @[simp] lemma integral_indicator_one ⦃s : set α⦄ (hs : measurable_set s) : ∫ a, s.indicator 1 a ∂μ = (μ s).to_real := (integral_indicator_const 1 hs).trans ((smul_eq_mul _).trans (mul_one _)) lemma set_integral_indicator_const_Lp {p : ℝ≥0∞} (hs : measurable_set s) (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) : ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (μ (t ∩ s)).to_real • x := calc ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (∫ a in s, t.indicator (λ _, x) a ∂μ) : by rw set_integral_congr_ae hs (indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx)) ... = (μ (t ∩ s)).to_real • x : by rw [integral_indicator_const _ ht, measure.restrict_apply ht] lemma integral_indicator_const_Lp {p : ℝ≥0∞} (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) : ∫ a, indicator_const_Lp p ht hμt x a ∂μ = (μ t).to_real • x := calc ∫ a, indicator_const_Lp p ht hμt x a ∂μ = ∫ a in univ, indicator_const_Lp p ht hμt x a ∂μ : by rw integral_univ ... = (μ (t ∩ univ)).to_real • x : set_integral_indicator_const_Lp measurable_set.univ ht hμt x ... = (μ t).to_real • x : by rw inter_univ lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hf : ae_strongly_measurable f (measure.map g μ)) (hg : ae_measurable g μ) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := begin rw [measure.restrict_map_of_ae_measurable hg hs, integral_map (hg.mono_measure measure.restrict_le_self) (hf.mono_measure _)], exact measure.map_mono_of_ae_measurable measure.restrict_le_self hg end lemma _root_.measurable_embedding.set_integral_map {β} {_ : measurable_space β} {f : α → β} (hf : measurable_embedding f) (g : β → E) (s : set β) : ∫ y in s, g y ∂(measure.map f μ) = ∫ x in f ⁻¹' s, g (f x) ∂μ := by rw [hf.restrict_map, hf.integral_map] lemma _root_.closed_embedding.set_integral_map [topological_space α] [borel_space α] {β} [measurable_space β] [topological_space β] [borel_space β] {g : α → β} {f : β → E} (s : set β) (hg : closed_embedding g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := hg.measurable_embedding.set_integral_map _ _ lemma measure_preserving.set_integral_preimage_emb {β} {_ : measurable_space β} {f : α → β} {ν} (h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) (g : β → E) (s : set β) : ∫ x in f ⁻¹' s, g (f x) ∂μ = ∫ y in s, g y ∂ν := (h₁.restrict_preimage_emb h₂ s).integral_comp h₂ _ lemma measure_preserving.set_integral_image_emb {β} {_ : measurable_space β} {f : α → β} {ν} (h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) (g : β → E) (s : set α) : ∫ y in f '' s, g y ∂ν = ∫ x in s, g (f x) ∂μ := eq.symm $ (h₁.restrict_image_emb h₂ s).integral_comp h₂ _ lemma set_integral_map_equiv {β} [measurable_space β] (e : α ≃ᵐ β) (f : β → E) (s : set β) : ∫ y in s, f y ∂(measure.map e μ) = ∫ x in e ⁻¹' s, f (e x) ∂μ := e.measurable_embedding.set_integral_map f s lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ.restrict s, ‖f x‖ ≤ C) : ‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : is_finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ, x ∈ s → ‖f x‖ ≤ C) (hfm : ae_strongly_measurable f (μ.restrict s)) : ‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real := begin apply norm_set_integral_le_of_norm_le_const_ae hs, have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ‖ae_strongly_measurable.mk f hfm x‖ ≤ C, { filter_upwards [hC, hfm.ae_mem_imp_eq_mk] with _ h1 h2 h3, rw [← h2 h3], exact h1 h3 }, have B : measurable_set {x | ‖(hfm.mk f) x‖ ≤ C} := hfm.strongly_measurable_mk.norm.measurable measurable_set_Iic, filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A] with _ h1 _, rwa h1, end lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ᵐ x ∂μ, x ∈ s → ‖f x‖ ≤ C) : ‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞) (hC : ∀ x ∈ s, ‖f x‖ ≤ C) (hfm : ae_strongly_measurable f (μ.restrict s)) : ‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ x ∈ s, ‖f x‖ ≤ C) : ‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : ∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : 0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) := begin rw [integral_pos_iff_support_of_nonneg_ae hf hfi, measure.restrict_apply₀], rw support_eq_preimage, exact hfi.ae_strongly_measurable.ae_measurable.null_measurable (measurable_set_singleton 0).compl end lemma set_integral_gt_gt {R : ℝ} {f : α → ℝ} (hR : 0 ≤ R) (hfm : measurable f) (hfint : integrable_on f {x | ↑R < f x} μ) (hμ : μ {x | ↑R < f x} ≠ 0): (μ {x | ↑R < f x}).to_real * R < ∫ x in {x | ↑R < f x}, f x ∂μ := begin have : integrable_on (λ x, R) {x | ↑R < f x} μ, { refine ⟨ae_strongly_measurable_const, lt_of_le_of_lt _ hfint.2⟩, refine set_lintegral_mono (measurable.nnnorm _).coe_nnreal_ennreal hfm.nnnorm.coe_nnreal_ennreal (λ x hx, _), { exact measurable_const }, { simp only [ennreal.coe_le_coe, real.nnnorm_of_nonneg hR, real.nnnorm_of_nonneg (hR.trans $ le_of_lt hx), subtype.mk_le_mk], exact le_of_lt hx } }, rw [← sub_pos, ← smul_eq_mul, ← set_integral_const, ← integral_sub hfint this, set_integral_pos_iff_support_of_nonneg_ae], { rw ← zero_lt_iff at hμ, rwa set.inter_eq_self_of_subset_right, exact λ x hx, ne.symm (ne_of_lt $ sub_pos.2 hx) }, { change ∀ᵐ x ∂(μ.restrict _), _, rw ae_restrict_iff, { exact eventually_of_forall (λ x hx, sub_nonneg.2 $ le_of_lt hx) }, { exact measurable_set_le measurable_zero (hfm.sub measurable_const) } }, { exact integrable.sub hfint this }, end lemma set_integral_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → E} (hf_meas : strongly_measurable[m] f) {s : set α} (hs : measurable_set[m] s) : ∫ x in s, f x ∂μ = ∫ x in s, f x ∂(μ.trim hm) := by rwa [integral_trim hm hf_meas, restrict_trim hm μ] /-! ### Lemmas about adding and removing interval boundaries The primed lemmas take explicit arguments about the endpoint having zero measure, while the unprimed ones use `[has_no_atoms μ]`. -/ section partial_order variables [partial_order α] {a b : α} lemma integral_Icc_eq_integral_Ioc' (ha : μ {a} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := set_integral_congr_set_ae (Ioc_ae_eq_Icc' ha).symm lemma integral_Icc_eq_integral_Ico' (hb : μ {b} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ico a b, f t ∂μ := set_integral_congr_set_ae (Ico_ae_eq_Icc' hb).symm lemma integral_Ioc_eq_integral_Ioo' (hb : μ {b} = 0) : ∫ t in Ioc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := set_integral_congr_set_ae (Ioo_ae_eq_Ioc' hb).symm lemma integral_Ico_eq_integral_Ioo' (ha : μ {a} = 0) : ∫ t in Ico a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := set_integral_congr_set_ae (Ioo_ae_eq_Ico' ha).symm lemma integral_Icc_eq_integral_Ioo' (ha : μ {a} = 0) (hb : μ {b} = 0) : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := set_integral_congr_set_ae (Ioo_ae_eq_Icc' ha hb).symm lemma integral_Iic_eq_integral_Iio' (ha : μ {a} = 0) : ∫ t in Iic a, f t ∂μ = ∫ t in Iio a, f t ∂μ := set_integral_congr_set_ae (Iio_ae_eq_Iic' ha).symm lemma integral_Ici_eq_integral_Ioi' (ha : μ {a} = 0) : ∫ t in Ici a, f t ∂μ = ∫ t in Ioi a, f t ∂μ := set_integral_congr_set_ae (Ioi_ae_eq_Ici' ha).symm variable [has_no_atoms μ] lemma integral_Icc_eq_integral_Ioc : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ := integral_Icc_eq_integral_Ioc' $ measure_singleton a lemma integral_Icc_eq_integral_Ico : ∫ t in Icc a b, f t ∂μ = ∫ t in Ico a b, f t ∂μ := integral_Icc_eq_integral_Ico' $ measure_singleton b lemma integral_Ioc_eq_integral_Ioo : ∫ t in Ioc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := integral_Ioc_eq_integral_Ioo' $ measure_singleton b lemma integral_Ico_eq_integral_Ioo : ∫ t in Ico a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ := integral_Ico_eq_integral_Ioo' $ measure_singleton a lemma integral_Icc_eq_integral_Ioo : ∫ t in Icc a b, f t ∂μ = ∫ t in Ico a b, f t ∂μ := by rw [integral_Icc_eq_integral_Ico, integral_Ico_eq_integral_Ioo] lemma integral_Iic_eq_integral_Iio : ∫ t in Iic a, f t ∂μ = ∫ t in Iio a, f t ∂μ := integral_Iic_eq_integral_Iio' $ measure_singleton a lemma integral_Ici_eq_integral_Ioi : ∫ t in Ici a, f t ∂μ = ∫ t in Ioi a, f t ∂μ := integral_Ici_eq_integral_Ioi' $ measure_singleton a end partial_order end normed_add_comm_group section mono variables {μ : measure α} {f g : α → ℝ} {s t : set α} (hf : integrable_on f s μ) (hg : integrable_on g s μ) lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono_ae hf hg h lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h) lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h]) include hf hg -- why do I need this include, but we don't need it in other lemmas? lemma set_integral_mono_on_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := by { refine set_integral_mono_ae_restrict hf hg _, rwa [eventually_le, ae_restrict_iff' hs], } omit hf hg lemma set_integral_mono (h : f ≤ g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono hf hg h lemma set_integral_mono_set (hfi : integrable_on f t μ) (hf : 0 ≤ᵐ[μ.restrict t] f) (hst : s ≤ᵐ[μ] t) : ∫ x in s, f x ∂μ ≤ ∫ x in t, f x ∂μ := integral_mono_measure (measure.restrict_mono_ae hst) hf hfi lemma set_integral_ge_of_const_le {c : ℝ} (hs : measurable_set s) (hμs : μ s ≠ ∞) (hf : ∀ x ∈ s, c ≤ f x) (hfint : integrable_on (λ (x : α), f x) s μ) : c * (μ s).to_real ≤ ∫ x in s, f x ∂μ := begin rw [mul_comm, ← smul_eq_mul, ← set_integral_const c], exact set_integral_mono_on (integrable_on_const.2 (or.inr hμs.lt_top)) hfint hs hf, end end mono section nonneg variables {μ : measure α} {f : α → ℝ} {s : set α} lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) : 0 ≤ ∫ a in s, f a ∂μ := integral_nonneg_of_ae hf lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) lemma set_integral_nonneg_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → 0 ≤ f a) : 0 ≤ ∫ a in s, f a ∂μ := set_integral_nonneg_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs] lemma set_integral_le_nonneg {s : set α} (hs : measurable_set s) (hf : strongly_measurable f) (hfi : integrable f μ) : ∫ x in s, f x ∂μ ≤ ∫ x in {y | 0 ≤ f y}, f x ∂μ := begin rw [← integral_indicator hs, ← integral_indicator (strongly_measurable_const.measurable_set_le hf)], exact integral_mono (hfi.indicator hs) (hfi.indicator (strongly_measurable_const.measurable_set_le hf)) (indicator_le_indicator_nonneg s f), end lemma set_integral_nonpos_of_ae_restrict (hf : f ≤ᵐ[μ.restrict s] 0) : ∫ a in s, f a ∂μ ≤ 0 := integral_nonpos_of_ae hf lemma set_integral_nonpos_of_ae (hf : f ≤ᵐ[μ] 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonpos (hs : measurable_set s) (hf : ∀ a, a ∈ s → f a ≤ 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) lemma set_integral_nonpos_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → f a ≤ 0) : ∫ a in s, f a ∂μ ≤ 0 := set_integral_nonpos_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs] lemma set_integral_nonpos_le {s : set α} (hs : measurable_set s) (hf : strongly_measurable f) (hfi : integrable f μ) : ∫ x in {y | f y ≤ 0}, f x ∂μ ≤ ∫ x in s, f x ∂μ := begin rw [← integral_indicator hs, ← integral_indicator (hf.measurable_set_le strongly_measurable_const)], exact integral_mono (hfi.indicator (hf.measurable_set_le strongly_measurable_const)) (hfi.indicator hs) (indicator_nonpos_le_indicator s f), end end nonneg section integrable_Union variables {μ : measure α} [normed_add_comm_group E] [countable β] lemma integrable_on_Union_of_summable_integral_norm {f : α → E} {s : β → set α} (hs : ∀ (b : β), measurable_set (s b)) (hi : ∀ (b : β), integrable_on f (s b) μ) (h : summable (λ (b : β), ∫ (a : α) in s b, ‖f a‖ ∂μ)) : integrable_on f (Union s) μ := begin refine ⟨ae_strongly_measurable.Union (λ i, (hi i).1), (lintegral_Union_le _ _).trans_lt _⟩, have B := λ (b : β), lintegral_coe_eq_integral (λ (a : α), ‖f a‖₊) (hi b).norm, rw tsum_congr B, have S' : summable (λ (b : β), (⟨∫ (a : α) in s b, ‖f a‖₊ ∂μ, set_integral_nonneg (hs b) (λ a ha, nnreal.coe_nonneg _)⟩ : nnreal)), { rw ←nnreal.summable_coe, exact h }, have S'' := ennreal.tsum_coe_eq S'.has_sum, simp_rw [ennreal.coe_nnreal_eq, nnreal.coe_mk, coe_nnnorm] at S'', convert ennreal.of_real_lt_top, end variables [topological_space α] [borel_space α] [metrizable_space α] [is_locally_finite_measure μ] /-- If `s` is a countable family of compact sets, `f` is a continuous function, and the sequence `‖f.restrict (s i)‖ * μ (s i)` is summable, then `f` is integrable on the union of the `s i`. -/ lemma integrable_on_Union_of_summable_norm_restrict {f : C(α, E)} {s : β → compacts α} (hf : summable (λ i : β, ‖f.restrict (s i)‖ * ennreal.to_real (μ $ s i))) : integrable_on f (⋃ i : β, s i) μ := begin refine integrable_on_Union_of_summable_integral_norm (λ i, (s i).is_compact.is_closed.measurable_set) (λ i, (map_continuous f).continuous_on.integrable_on_compact (s i).is_compact) (summable_of_nonneg_of_le (λ ι, integral_nonneg (λ x, norm_nonneg _)) (λ i, _) hf), rw ←(real.norm_of_nonneg (integral_nonneg (λ a, norm_nonneg _)) : ‖_‖ = ∫ x in s i, ‖f x‖ ∂μ), exact norm_set_integral_le_of_norm_le_const' (s i).is_compact.measure_lt_top (s i).is_compact.is_closed.measurable_set (λ x hx, (norm_norm (f x)).symm ▸ (f.restrict ↑(s i)).norm_coe_le_norm ⟨x, hx⟩) end /-- If `s` is a countable family of compact sets covering `α`, `f` is a continuous function, and the sequence `‖f.restrict (s i)‖ * μ (s i)` is summable, then `f` is integrable. -/ lemma integrable_of_summable_norm_restrict {f : C(α, E)} {s : β → compacts α} (hf : summable (λ i : β, ‖f.restrict (s i)‖ * ennreal.to_real (μ $ s i))) (hs : (⋃ i : β, ↑(s i)) = (univ : set α)) : integrable f μ := by simpa only [hs, integrable_on_univ] using integrable_on_Union_of_summable_norm_restrict hf end integrable_Union section tendsto_mono variables {μ : measure α} [normed_add_comm_group E] [complete_space E] [normed_space ℝ E] {s : ℕ → set α} {f : α → E} lemma _root_.antitone.tendsto_set_integral (hsm : ∀ i, measurable_set (s i)) (h_anti : antitone s) (hfi : integrable_on f (s 0) μ) : tendsto (λi, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋂ n, s n), f a ∂μ)) := begin let bound : α → ℝ := indicator (s 0) (λ a, ‖f a‖), have h_int_eq : (λ i, ∫ a in s i, f a ∂μ) = (λ i, ∫ a, (s i).indicator f a ∂μ), from funext (λ i, (integral_indicator (hsm i)).symm), rw h_int_eq, rw ← integral_indicator (measurable_set.Inter hsm), refine tendsto_integral_of_dominated_convergence bound _ _ _ _, { intro n, rw ae_strongly_measurable_indicator_iff (hsm n), exact (integrable_on.mono_set hfi (h_anti (zero_le n))).1 }, { rw integrable_indicator_iff (hsm 0), exact hfi.norm, }, { simp_rw norm_indicator_eq_indicator_norm, refine λ n, eventually_of_forall (λ x, _), exact indicator_le_indicator_of_subset (h_anti (zero_le n)) (λ a, norm_nonneg _) _ }, { filter_upwards with a using le_trans (h_anti.tendsto_indicator _ _ _) (pure_le_nhds _), }, end end tendsto_mono /-! ### Continuity of the set integral We prove that for any set `s`, the function `λ f : α →₁[μ] E, ∫ x in s, f x ∂μ` is continuous. -/ section continuous_set_integral variables [normed_add_comm_group E] {𝕜 : Type*} [normed_field 𝕜] [normed_add_comm_group F] [normed_space 𝕜 F] {p : ℝ≥0∞} {μ : measure α} /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is additive. -/ lemma Lp_to_Lp_restrict_add (f g : Lp E p μ) (s : set α) : ((Lp.mem_ℒp (f + g)).restrict s).to_Lp ⇑(f + g) = ((Lp.mem_ℒp f).restrict s).to_Lp f + ((Lp.mem_ℒp g).restrict s).to_Lp g := begin ext1, refine (ae_restrict_of_ae (Lp.coe_fn_add f g)).mp _, refine (Lp.coe_fn_add (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s)) (mem_ℒp.to_Lp g ((Lp.mem_ℒp g).restrict s))).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp g).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (f+g)).restrict s)).mono (λ x hx1 hx2 hx3 hx4 hx5, _), rw [hx4, hx1, pi.add_apply, hx2, hx3, hx5, pi.add_apply], end /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map commutes with scalar multiplication. -/ lemma Lp_to_Lp_restrict_smul (c : 𝕜) (f : Lp F p μ) (s : set α) : ((Lp.mem_ℒp (c • f)).restrict s).to_Lp ⇑(c • f) = c • (((Lp.mem_ℒp f).restrict s).to_Lp f) := begin ext1, refine (ae_restrict_of_ae (Lp.coe_fn_smul c f)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _, refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (c • f)).restrict s)).mp _, refine (Lp.coe_fn_smul c (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))).mono (λ x hx1 hx2 hx3 hx4, _), rw [hx2, hx1, pi.smul_apply, hx3, hx4, pi.smul_apply], end /-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by `(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is non-expansive. -/ lemma norm_Lp_to_Lp_restrict_le (s : set α) (f : Lp E p μ) : ‖((Lp.mem_ℒp f).restrict s).to_Lp f‖ ≤ ‖f‖ := begin rw [Lp.norm_def, Lp.norm_def, ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _)], refine (le_of_eq _).trans (snorm_mono_measure _ measure.restrict_le_self), { exact s, }, exact snorm_congr_ae (mem_ℒp.coe_fn_to_Lp _), end variables (α F 𝕜) /-- Continuous linear map sending a function of `Lp F p μ` to the same function in `Lp F p (μ.restrict s)`. -/ def Lp_to_Lp_restrict_clm (μ : measure α) (p : ℝ≥0∞) [hp : fact (1 ≤ p)] (s : set α) : Lp F p μ →L[𝕜] Lp F p (μ.restrict s) := @linear_map.mk_continuous 𝕜 𝕜 (Lp F p μ) (Lp F p (μ.restrict s)) _ _ _ _ _ _ (ring_hom.id 𝕜) ⟨λ f, mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s), λ f g, Lp_to_Lp_restrict_add f g s, λ c f, Lp_to_Lp_restrict_smul c f s⟩ 1 (by { intro f, rw one_mul, exact norm_Lp_to_Lp_restrict_le s f, }) variables {α F 𝕜} variables (𝕜) lemma Lp_to_Lp_restrict_clm_coe_fn [hp : fact (1 ≤ p)] (s : set α) (f : Lp F p μ) : Lp_to_Lp_restrict_clm α F 𝕜 μ p s f =ᵐ[μ.restrict s] f := mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s) variables {𝕜} @[continuity] lemma continuous_set_integral [normed_space ℝ E] [complete_space E] (s : set α) : continuous (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) := begin haveI : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩, have h_comp : (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) = (integral (μ.restrict s)) ∘ (λ f, Lp_to_Lp_restrict_clm α E ℝ μ 1 s f), { ext1 f, rw [function.comp_apply, integral_congr_ae (Lp_to_Lp_restrict_clm_coe_fn ℝ s f)], }, rw h_comp, exact continuous_integral.comp (Lp_to_Lp_restrict_clm α E ℝ μ 1 s).continuous, end end continuous_set_integral end measure_theory open measure_theory asymptotics metric variables {ι : Type*} [normed_add_comm_group E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_space ℝ E] [complete_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {s : ι → set α} {li : filter ι} (hs : tendsto s li l.small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • b) =o[li] m := begin suffices : (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) =o[l.small_sets] (λ s, (μ s).to_real), from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ, refine is_o_iff.2 (λ ε ε₀, _), have : ∀ᶠ s in l.small_sets, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_small_sets_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually, hfm.eventually, this], simp only [mem_closed_ball, dist_eq_norm], intros s hμs h_integrable hfm h_norm, rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_strongly_measurable_const) end /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_within_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [complete_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t) (hfm : strongly_measurable_at_filter f (𝓝[t] a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝[t] a).small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds_within a t) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).small_sets` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [complete_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : strongly_measurable_at_filter f (𝓝 a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝 a).small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_on.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [complete_space E] [second_countable_topology_either α E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t) {s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝[t] a).small_sets) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : (λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m := (hft a ha).integral_sub_linear_is_o_ae ht ⟨t, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩ hs m hsμ section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. This holds for simple functions. The general result follows from the continuity of all involved operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just the composition, as we are dealing with classes of functions, but it has already been defined as `continuous_linear_map.comp_Lp`. We take advantage of this construction here. -/ open_locale complex_conjugate variables {μ : measure α} {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] {p : ennreal} namespace continuous_linear_map variables [complete_space F] [normed_space ℝ F] lemma integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) : ∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ := integral_congr_ae $ coe_fn_comp_Lp _ _ lemma set_integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) {s : set α} (hs : measurable_set s) : ∫ a in s, (L.comp_Lp φ) a ∂μ = ∫ a in s, L (φ a) ∂μ := set_integral_congr_ae hs ((L.coe_fn_comp_Lp φ).mono (λ x hx hx2, hx)) lemma continuous_integral_comp_L1 (L : E →L[𝕜] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := by { rw ← funext L.integral_comp_Lp, exact continuous_integral.comp (L.comp_LpL 1 μ).continuous, } variables [complete_space E] [normed_space ℝ E] lemma integral_comp_comm (L : E →L[𝕜] F) {φ : α → E} (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, ← @smul_one_smul E ℝ 𝕜 _ _ _ _ _ (μ s).to_real e, continuous_linear_map.map_smul, @smul_one_smul F ℝ 𝕜 _ _ _ _ _ (μ s).to_real (L e), ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_int g_int hf hg, simp [L.map_add, integral_add f_int g_int, integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_int hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (hfg.fun_comp L).symm }, { rw integral_congr_ae hfg.symm } }, all_goals { assumption } end lemma integral_apply {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {φ : α → H →L[𝕜] E} (φ_int : integrable φ μ) (v : H) : (∫ a, φ a ∂μ) v = ∫ a, φ a v ∂μ := ((continuous_linear_map.apply 𝕜 E v).integral_comp_comm φ_int).symm lemma integral_comp_comm' (L : E →L[𝕜] F) {K} (hL : antilipschitz_with K L) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin by_cases h : integrable φ μ, { exact integral_comp_comm L h }, have : ¬ (integrable (L ∘ φ) μ), by rwa lipschitz_with.integrable_comp_iff_of_antilipschitz L.lipschitz hL (L.map_zero), simp [integral_undef, h, this] end lemma integral_comp_L1_comm (L : E →L[𝕜] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm (L1.integrable_coe_fn φ) end continuous_linear_map namespace linear_isometry variables [complete_space F] [normed_space ℝ F] [complete_space E] [normed_space ℝ E] lemma integral_comp_comm (L : E →ₗᵢ[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _ end linear_isometry namespace continuous_linear_equiv variables [complete_space F] [normed_space ℝ F] [complete_space E] [normed_space ℝ E] lemma integral_comp_comm (L : E ≃L[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _ end continuous_linear_equiv variables [complete_space E] [normed_space ℝ E] [complete_space F] [normed_space ℝ F] @[norm_cast] lemma integral_of_real {f : α → ℝ} : ∫ a, (f a : 𝕜) ∂μ = ↑∫ a, f a ∂μ := (@is_R_or_C.of_real_li 𝕜 _).integral_comp_comm f lemma integral_re {f : α → 𝕜} (hf : integrable f μ) : ∫ a, is_R_or_C.re (f a) ∂μ = is_R_or_C.re ∫ a, f a ∂μ := (@is_R_or_C.re_clm 𝕜 _).integral_comp_comm hf lemma integral_im {f : α → 𝕜} (hf : integrable f μ) : ∫ a, is_R_or_C.im (f a) ∂μ = is_R_or_C.im ∫ a, f a ∂μ := (@is_R_or_C.im_clm 𝕜 _).integral_comp_comm hf lemma integral_conj {f : α → 𝕜} : ∫ a, conj (f a) ∂μ = conj ∫ a, f a ∂μ := (@is_R_or_C.conj_lie 𝕜 _).to_linear_isometry.integral_comp_comm f lemma integral_coe_re_add_coe_im {f : α → 𝕜} (hf : integrable f μ) : ∫ x, (is_R_or_C.re (f x) : 𝕜) ∂μ + ∫ x, is_R_or_C.im (f x) ∂μ * is_R_or_C.I = ∫ x, f x ∂μ := begin rw [mul_comm, ← smul_eq_mul, ← integral_smul, ← integral_add], { congr, ext1 x, rw [smul_eq_mul, mul_comm, is_R_or_C.re_add_im] }, { exact hf.re.of_real }, { exact hf.im.of_real.smul is_R_or_C.I } end lemma integral_re_add_im {f : α → 𝕜} (hf : integrable f μ) : ((∫ x, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x, f x ∂μ := by { rw [← integral_of_real, ← integral_of_real, integral_coe_re_add_coe_im hf] } lemma set_integral_re_add_im {f : α → 𝕜} {i : set α} (hf : integrable_on f i μ) : ((∫ x in i, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x in i, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x in i, f x ∂μ := integral_re_add_im hf lemma fst_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ := ((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm lemma snd_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ := ((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) : ∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) := have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this) lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] (f : α → 𝕜) (c : E) : ∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c := begin by_cases hf : integrable f μ, { exact ((1 : 𝕜 →L[𝕜] 𝕜).smul_right c).integral_comp_comm hf }, { by_cases hc : c = 0, { simp only [hc, integral_zero, smul_zero] }, rw [integral_undef hf, integral_undef, zero_smul], simp_rw [integrable_smul_const hc, hf, not_false_iff] } end section inner variables {E' : Type*} variables [normed_add_comm_group E'] [inner_product_space 𝕜 E'] variables [complete_space E'] [normed_space ℝ E'] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E' _ x y lemma integral_inner {f : α → E'} (hf : integrable f μ) (c : E') : ∫ x, ⟪c, f x⟫ ∂μ = ⟪c, ∫ x, f x ∂μ⟫ := ((innerSL 𝕜 c).restrict_scalars ℝ).integral_comp_comm hf variables (𝕜) -- variable binder update doesn't work for lemmas which refer to `𝕜` only via the notation local notation (name := inner_with_explicit) `⟪`x`, `y`⟫` := @inner 𝕜 E' _ x y lemma integral_eq_zero_of_forall_integral_inner_eq_zero (f : α → E') (hf : integrable f μ) (hf_int : ∀ (c : E'), ∫ x, ⟪c, f x⟫ ∂μ = 0) : ∫ x, f x ∂μ = 0 := by { specialize hf_int (∫ x, f x ∂μ), rwa [integral_inner hf, inner_self_eq_zero] at hf_int } end inner lemma integral_with_density_eq_integral_smul {f : α → ℝ≥0} (f_meas : measurable f) (g : α → E) : ∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, f a • g a ∂μ := begin by_cases hg : integrable g (μ.with_density (λ x, f x)), swap, { rw [integral_undef hg, integral_undef], rwa [← integrable_with_density_iff_integrable_smul f_meas]; apply_instance }, refine integrable.induction _ _ _ _ _ hg, { assume c s s_meas hs, rw integral_indicator s_meas, simp_rw [← indicator_smul_apply, integral_indicator s_meas], simp only [s_meas, integral_const, measure.restrict_apply', univ_inter, with_density_apply], rw [lintegral_coe_eq_integral, ennreal.to_real_of_real, ← integral_smul_const], { refl }, { exact integral_nonneg (λ x, nnreal.coe_nonneg _) }, { refine ⟨(f_meas.coe_nnreal_real).ae_measurable.ae_strongly_measurable, _⟩, rw with_density_apply _ s_meas at hs, rw has_finite_integral, convert hs, ext1 x, simp only [nnreal.nnnorm_eq] } }, { assume u u' h_disj u_int u'_int h h', change ∫ (a : α), (u a + u' a) ∂μ.with_density (λ (x : α), ↑(f x)) = ∫ (a : α), f a • (u a + u' a) ∂μ, simp_rw [smul_add], rw [integral_add u_int u'_int, h, h', integral_add], { exact (integrable_with_density_iff_integrable_smul f_meas).1 u_int }, { exact (integrable_with_density_iff_integrable_smul f_meas).1 u'_int } }, { have C1 : continuous (λ (u : Lp E 1 (μ.with_density (λ x, f x))), ∫ x, u x ∂(μ.with_density (λ x, f x))) := continuous_integral, have C2 : continuous (λ (u : Lp E 1 (μ.with_density (λ x, f x))), ∫ x, f x • u x ∂μ), { have : continuous ((λ (u : Lp E 1 μ), ∫ x, u x ∂μ) ∘ (with_density_smul_li μ f_meas)) := continuous_integral.comp (with_density_smul_li μ f_meas).continuous, convert this, ext1 u, simp only [function.comp_app, with_density_smul_li_apply], exact integral_congr_ae (mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp.symm }, exact is_closed_eq C1 C2 }, { assume u v huv u_int hu, rw [← integral_congr_ae huv, hu], apply integral_congr_ae, filter_upwards [(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 huv] with x hx, rcases eq_or_ne (f x) 0 with h'x|h'x, { simp only [h'x, zero_smul]}, { rw [hx _], simpa only [ne.def, ennreal.coe_eq_zero] using h'x } } end lemma integral_with_density_eq_integral_smul₀ {f : α → ℝ≥0} (hf : ae_measurable f μ) (g : α → E) : ∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, f a • g a ∂μ := begin let f' := hf.mk _, calc ∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, g a ∂(μ.with_density (λ x, f' x)) : begin congr' 1, apply with_density_congr_ae, filter_upwards [hf.ae_eq_mk] with x hx, rw hx, end ... = ∫ a, f' a • g a ∂μ : integral_with_density_eq_integral_smul hf.measurable_mk _ ... = ∫ a, f a • g a ∂μ : begin apply integral_congr_ae, filter_upwards [hf.ae_eq_mk] with x hx, rw hx, end end lemma set_integral_with_density_eq_set_integral_smul {f : α → ℝ≥0} (f_meas : measurable f) (g : α → E) {s : set α} (hs : measurable_set s) : ∫ a in s, g a ∂(μ.with_density (λ x, f x)) = ∫ a in s, f a • g a ∂μ := by rw [restrict_with_density hs, integral_with_density_eq_integral_smul f_meas] lemma set_integral_with_density_eq_set_integral_smul₀ {f : α → ℝ≥0} {s : set α} (hf : ae_measurable f (μ.restrict s)) (g : α → E) (hs : measurable_set s) : ∫ a in s, g a ∂(μ.with_density (λ x, f x)) = ∫ a in s, f a • g a ∂μ := by rw [restrict_with_density hs, integral_with_density_eq_integral_smul₀ hf] end section thickened_indicator variables [pseudo_emetric_space α] lemma measure_le_lintegral_thickened_indicator_aux (μ : measure α) {E : set α} (E_mble : measurable_set E) (δ : ℝ) : μ E ≤ ∫⁻ a, (thickened_indicator_aux δ E a : ℝ≥0∞) ∂μ := begin convert_to lintegral μ (E.indicator (λ _, (1 : ℝ≥0∞))) ≤ lintegral μ (thickened_indicator_aux δ E), { rw [lintegral_indicator _ E_mble], simp only [lintegral_one, measure.restrict_apply, measurable_set.univ, univ_inter], }, { apply lintegral_mono, apply indicator_le_thickened_indicator_aux, }, end lemma measure_le_lintegral_thickened_indicator (μ : measure α) {E : set α} (E_mble : measurable_set E) {δ : ℝ} (δ_pos : 0 < δ) : μ E ≤ ∫⁻ a, (thickened_indicator δ_pos E a : ℝ≥0∞) ∂μ := begin convert measure_le_lintegral_thickened_indicator_aux μ E_mble δ, dsimp, simp only [thickened_indicator_aux_lt_top.ne, ennreal.coe_to_nnreal, ne.def, not_false_iff], end end thickened_indicator section bilinear_map namespace measure_theory variables {f : β → ℝ} {m m0 : measurable_space β} {μ : measure β} lemma integrable.simple_func_mul (g : simple_func β ℝ) (hf : integrable f μ) : integrable (g * f) μ := begin refine simple_func.induction (λ c s hs, _) (λ g₁ g₂ h_disj h_int₁ h_int₂, (h_int₁.add h_int₂).congr (by rw [simple_func.coe_add, add_mul])) g, simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const, simple_func.coe_zero, set.piecewise_eq_indicator], have : set.indicator s (function.const β c) * f = s.indicator (c • f), { ext1 x, by_cases hx : x ∈ s, { simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] }, { simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, }, rw [this, integrable_indicator_iff hs], exact (hf.smul c).integrable_on, end lemma integrable.simple_func_mul' (hm : m ≤ m0) (g : @simple_func β m ℝ) (hf : integrable f μ) : integrable (g * f) μ := by { rw ← simple_func.coe_to_larger_space_eq hm g, exact hf.simple_func_mul (g.to_larger_space hm) } end measure_theory end bilinear_map
b05f2f47659c61bbe3d1bcfdf7cafc8ce5162982
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/eval_attr_cache.lean
aaf02f48a83cc7ff801278aef022632d09a2b10b
[ "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
875
lean
open tactic meta def list_name.to_expr (n : list name) : tactic expr := to_expr (quote n) meta def my_attr : caching_user_attribute (name → bool) := { name := "my_attr", descr := "my attr", mk_cache := λ ls, do { els ← list_name.to_expr ls, c ← to_expr `(λ n : name, (name.cases_on n ff (λ _ _, to_bool (n ∈ %%els)) (λ _ _, ff) : bool)), eval_expr (name → bool) c }, dependencies := [] } run_command attribute.register `my_attr meta def my_tac : tactic unit := do f ← caching_user_attribute.get_cache my_attr, trace (f `foo), return () @[my_attr] def bla := 10 run_command my_tac @[my_attr] def foo := 10 -- Cache was invalided run_command my_tac -- Add closure to the cache containing auxiliary function created by eval_expr run_command my_tac -- Cache should be flushed since the auxiliary function is gone
6e1ab5d0654b402bd39dd0e46605c5bd1ebd6f41
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/init/measurable.lean
0352c64585c64321d8b363b7091fc609eb696c70
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,380
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Types with a nat-valued complexity measure. -/ prelude import init.nat open nat inductive measurable [class] (A : Type) := mk : (A → nat) → measurable A definition size_of {A : Type} [s : measurable A] : A → nat := measurable.rec_on s (λ f, f) definition nat.measurable [instance] : measurable nat := measurable.mk (λ a, a) definition option.measurable [instance] (A : Type) [measurable A] : measurable (option A) := measurable.mk (λ a, option.cases_on a zero size_of) definition prod.measurable [instance] (A B : Type) [measurable A] [measurable B] : measurable (prod A B) := measurable.mk (λ p, prod.cases_on p (λ a b, size_of a + size_of b)) definition sum.measurable [instance] (A B : Type) [measurable A] [measurable B] : measurable (sum A B) := measurable.mk (λ s, sum.cases_on s (λ a, size_of a) (λ b, size_of b)) definition bool.measurable [instance] : measurable bool := measurable.mk (λb, zero) definition Prop.measurable [instance] : measurable Prop := measurable.mk (λp, zero) definition unit.measurable [instance] : measurable unit := measurable.mk (λu, zero) definition fn.measurable [instance] (A : Type) (B : A → Type) : measurable (Π x, B x) := measurable.mk (λf, zero)
631261b52b2b00827a6c9c383a7ac0a9937f1eef
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/instances/real_vector_space_auto.lean
fab9e94fafa61bfe1266ad83630d3d72a5cdc457
[]
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,939
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.module import Mathlib.topology.instances.real import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Continuous additive maps are `ℝ`-linear In this file we prove that a continuous map `f : E →+ F` between two topological vector spaces over `ℝ` is `ℝ`-linear -/ namespace add_monoid_hom /-- A continuous additive map between two vector spaces over `ℝ` is `ℝ`-linear. -/ theorem map_real_smul {E : Type u_1} [add_comm_group E] [vector_space ℝ E] [topological_space E] [topological_vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] [topological_space F] [topological_vector_space ℝ F] [t2_space F] (f : E →+ F) (hf : continuous ⇑f) (c : ℝ) (x : E) : coe_fn f (c • x) = c • coe_fn f x := sorry /-- Reinterpret a continuous additive homomorphism between two real vector spaces as a continuous real-linear map. -/ def to_real_linear_map {E : Type u_1} [add_comm_group E] [vector_space ℝ E] [topological_space E] [topological_vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] [topological_space F] [topological_vector_space ℝ F] [t2_space F] (f : E →+ F) (hf : continuous ⇑f) : continuous_linear_map ℝ E F := continuous_linear_map.mk (linear_map.mk ⇑f sorry (map_real_smul f hf)) @[simp] theorem coe_to_real_linear_map {E : Type u_1} [add_comm_group E] [vector_space ℝ E] [topological_space E] [topological_vector_space ℝ E] {F : Type u_2} [add_comm_group F] [vector_space ℝ F] [topological_space F] [topological_vector_space ℝ F] [t2_space F] (f : E →+ F) (hf : continuous ⇑f) : ⇑(to_real_linear_map f hf) = ⇑f := rfl end Mathlib
adc12d4f5e71a33042a59b5b43a3fd95eb2a769a
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/basis.lean
0a515acd22cdd8b370a4e1249e03c6c0f5c2fad2
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
35,064
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, Alexander Bentkamp -/ import algebra.big_operators.finsupp import data.fintype.card import linear_algebra.finsupp import linear_algebra.linear_independent import linear_algebra.linear_pmap import linear_algebra.projection /-! # Bases This file defines bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `basis ι R M` is the type of `ι`-indexed `R`-bases for a module `M`, represented by a linear equiv `M ≃ₗ[R] ι →₀ R`. * the basis vectors of a basis `b : basis ι R M` are available as `b i`, where `i : ι` * `basis.repr` is the isomorphism sending `x : M` to its coordinates `basis.repr x : ι →₀ R`. The converse, turning this isomorphism into a basis, is called `basis.of_repr`. * If `ι` is finite, there is a variant of `repr` called `basis.equiv_fun b : M ≃ₗ[R] ι → R` (saving you from having to work with `finsupp`). The converse, turning this isomorphism into a basis, is called `basis.of_equiv_fun`. * `basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis elements `⇑b : ι → M₁`. * `basis.reindex` uses an equiv to map a basis to a different indexing set. * `basis.map` uses a linear equiv to map a basis to a different module. ## Main statements * `basis.mk`: a linear independent set of vectors spanning the whole module determines a basis * `basis.ext` states that two linear maps are equal if they coincide on a basis. Similar results are available for linear equivs (if they coincide on the basis vectors), elements (if their coordinates coincide) and the functions `b.repr` and `⇑b`. * `basis.of_vector_space` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. ## Tags basis, bases -/ noncomputable theory universe u open function set submodule open_locale classical big_operators variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables [semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] section variables (ι) (R) (M) /-- A `basis ι R M` for a module `M` is the type of `ι`-indexed `R`-bases of `M`. The basis vectors are available as `coe_fn (b : basis ι R M) : ι → M`. To turn a linear independent family of vectors spanning `M` into a basis, use `basis.mk`. They are internally represented as linear equivs `M ≃ₗ[R] (ι →₀ R)`, available as `basis.repr`. -/ structure basis := of_repr :: (repr : M ≃ₗ[R] (ι →₀ R)) end namespace basis instance : inhabited (basis ι R (ι →₀ R)) := ⟨basis.of_repr (linear_equiv.refl _ _)⟩ variables (b b₁ : basis ι R M) (i : ι) (c : R) (x : M) section repr /-- `b i` is the `i`th basis vector. -/ instance : has_coe_to_fun (basis ι R M) := { F := λ _, ι → M, coe := λ b i, b.repr.symm (finsupp.single i 1) } @[simp] lemma coe_of_repr (e : M ≃ₗ[R] (ι →₀ R)) : ⇑(of_repr e) = λ i, e.symm (finsupp.single i 1) := rfl protected lemma injective [nontrivial R] : injective b := b.repr.symm.injective.comp (λ _ _, (finsupp.single_left_inj (one_ne_zero : (1 : R) ≠ 0)).mp) lemma repr_symm_single_one : b.repr.symm (finsupp.single i 1) = b i := rfl lemma repr_symm_single : b.repr.symm (finsupp.single i c) = c • b i := calc b.repr.symm (finsupp.single i c) = b.repr.symm (c • finsupp.single i 1) : by rw [finsupp.smul_single', mul_one] ... = c • b i : by rw [linear_equiv.map_smul, repr_symm_single_one] @[simp] lemma repr_self : b.repr (b i) = finsupp.single i 1 := linear_equiv.apply_symm_apply _ _ lemma repr_self_apply (j) [decidable (i = j)] : b.repr (b i) j = if i = j then 1 else 0 := by rw [repr_self, finsupp.single_apply] @[simp] lemma repr_symm_apply (v) : b.repr.symm v = finsupp.total ι M R b v := calc b.repr.symm v = b.repr.symm (v.sum finsupp.single) : by simp ... = ∑ i in v.support, b.repr.symm (finsupp.single i (v i)) : by rw [finsupp.sum, linear_equiv.map_sum] ... = finsupp.total ι M R b v : by simp [repr_symm_single, finsupp.total_apply, finsupp.sum] @[simp] lemma coe_repr_symm : ↑b.repr.symm = finsupp.total ι M R b := linear_map.ext (λ v, b.repr_symm_apply v) @[simp] lemma repr_total (v) : b.repr (finsupp.total _ _ _ b v) = v := by { rw ← b.coe_repr_symm, exact b.repr.apply_symm_apply v } @[simp] lemma total_repr : finsupp.total _ _ _ b (b.repr x) = x := by { rw ← b.coe_repr_symm, exact b.repr.symm_apply_apply x } lemma repr_range : (b.repr : M →ₗ[R] (ι →₀ R)).range = finsupp.supported R R univ := by rw [linear_equiv.range, finsupp.supported_univ] end repr section coord /-- `b.coord i` is the linear function giving the `i`'th coordinate of a vector with respect to the basis `b`. `b.coord i` is an element of the dual space. In particular, for finite-dimensional spaces it is the `ι`th basis vector of the dual space. -/ @[simps] def coord (i : ι) : M →ₗ[R] R := (finsupp.lapply i).comp b.repr lemma forall_coord_eq_zero_iff {x : M} : (∀ i, b.coord i x = 0) ↔ x = 0 := iff.trans (by simp only [b.coord_apply, finsupp.ext_iff, finsupp.zero_apply]) b.repr.map_eq_zero_iff end coord section ext variables {M₁ : Type*} [add_comm_monoid M₁] [module R M₁] /-- Two linear maps are equal if they are equal on basis vectors. -/ theorem ext {f₁ f₂ : M →ₗ[R] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_map.map_sum, linear_map.map_smul, h] } /-- Two linear equivs are equal if they are equal on basis vectors. -/ theorem ext' {f₁ f₂ : M ≃ₗ[R] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_equiv.map_sum, linear_equiv.map_smul, h] } /-- Two elements are equal if their coordinates are equal. -/ theorem ext_elem {x y : M} (h : ∀ i, b.repr x i = b.repr y i) : x = y := by { rw [← b.total_repr x, ← b.total_repr y], congr' 1, ext i, exact h i } lemma repr_eq_iff {b : basis ι R M} {f : M →ₗ[R] ι →₀ R} : ↑b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma repr_eq_iff' {b : basis ι R M} {f : M ≃ₗ[R] ι →₀ R} : b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext' (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma apply_eq_iff {b : basis ι R M} {x : M} {i : ι} : b i = x ↔ b.repr x = finsupp.single i 1 := ⟨λ h, h ▸ b.repr_self i, λ h, b.repr.injective ((b.repr_self i).trans h.symm)⟩ /-- An unbundled version of `repr_eq_iff` -/ lemma repr_apply_eq (f : M → ι → R) (hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x) (f_eq : ∀ i, f (b i) = finsupp.single i 1) (x : M) (i : ι) : b.repr x i = f x i := begin let f_i : M →ₗ[R] R := { to_fun := λ x, f x i, map_add' := λ _ _, by rw [hadd, pi.add_apply], map_smul' := λ _ _, by rw [hsmul, pi.smul_apply] }, have : (finsupp.lapply i).comp ↑b.repr = f_i, { refine b.ext (λ j, _), show b.repr (b j) i = f (b j) i, rw [b.repr_self, f_eq] }, calc b.repr x i = f_i x : by { rw ← this, refl } ... = f x i : rfl end /-- Two bases are equal if they assign the same coordinates. -/ lemma eq_of_repr_eq_repr {b₁ b₂ : basis ι R M} (h : ∀ x i, b₁.repr x i = b₂.repr x i) : b₁ = b₂ := have b₁.repr = b₂.repr, by { ext, apply h }, by { cases b₁, cases b₂, simpa } /-- Two bases are equal if their basis vectors are the same. -/ @[ext] lemma eq_of_apply_eq {b₁ b₂ : basis ι R M} (h : ∀ i, b₁ i = b₂ i) : b₁ = b₂ := suffices b₁.repr = b₂.repr, by { cases b₁, cases b₂, simpa }, repr_eq_iff'.mpr (λ i, by rw [h, b₂.repr_self]) end ext section map variables (f : M ≃ₗ[R] M') /-- Apply the linear equivalence `f` to the basis vectors. -/ protected def map : basis ι R M' := of_repr (f.symm.trans b.repr) @[simp] lemma map_apply (i) : b.map f i = f (b i) := rfl end map section reindex variables (b' : basis ι' R M') variables (e : ι ≃ ι') /-- `b.reindex (e : ι ≃ ι')` is a basis indexed by `ι'` -/ def reindex : basis ι' R M := basis.of_repr (b.repr.trans (finsupp.dom_lcongr e)) lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') := show (b.repr.trans (finsupp.dom_lcongr e)).symm (finsupp.single i' 1) = b.repr.symm (finsupp.single (e.symm i') 1), by rw [linear_equiv.symm_trans_apply, finsupp.dom_lcongr_symm, finsupp.dom_lcongr_single] @[simp] lemma coe_reindex : (b.reindex e : ι' → M) = b ∘ e.symm := funext (b.reindex_apply e) @[simp] lemma coe_reindex_repr : ((b.reindex e).repr x : ι' → R) = b.repr x ∘ e.symm := funext $ λ i', show (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (b.repr x) i' = _, by simp @[simp] lemma reindex_repr (i' : ι') : (b.reindex e).repr x i' = b.repr x (e.symm i') := by rw coe_reindex_repr /-- `simp` normal form version of `range_reindex` -/ @[simp] lemma range_reindex' : set.range (b ∘ e.symm) = set.range b := by rw [range_comp, equiv.range_eq_univ, set.image_univ] lemma range_reindex : set.range (b.reindex e) = set.range b := by rw [coe_reindex, range_reindex'] /-- `b.reindex_range` is a basis indexed by `range b`, the basis vectors themselves. -/ def reindex_range : basis (range b) R M := if h : nontrivial R then by letI := h; exact b.reindex (equiv.of_injective b (basis.injective b)) else by letI : subsingleton R := not_nontrivial_iff_subsingleton.mp h; exact basis.of_repr (module.subsingleton_equiv R M (range b)) lemma finsupp.single_apply_left {α β γ : Type*} [has_zero γ] {f : α → β} (hf : function.injective f) (x z : α) (y : γ) : finsupp.single (f x) y (f z) = finsupp.single x y z := by simp [finsupp.single_apply, hf.eq_iff] lemma reindex_range_self (i : ι) (h := set.mem_range_self i) : b.reindex_range ⟨b i, h⟩ = b i := begin by_cases htr : nontrivial R, { letI := htr, simp [htr, reindex_range, reindex_apply, equiv.apply_of_injective_symm b b.injective, subtype.coe_mk] }, { letI : subsingleton R := not_nontrivial_iff_subsingleton.mp htr, letI := module.subsingleton R M, simp [reindex_range] } end lemma reindex_range_repr_self (i : ι) : b.reindex_range.repr (b i) = finsupp.single ⟨b i, mem_range_self i⟩ 1 := calc b.reindex_range.repr (b i) = b.reindex_range.repr (b.reindex_range ⟨b i, mem_range_self i⟩) : congr_arg _ (b.reindex_range_self _ _).symm ... = finsupp.single ⟨b i, mem_range_self i⟩ 1 : b.reindex_range.repr_self _ @[simp] lemma reindex_range_apply (x : range b) : b.reindex_range x = x := by { rcases x with ⟨bi, ⟨i, rfl⟩⟩, exact b.reindex_range_self i, } lemma reindex_range_repr' (x : M) {bi : M} {i : ι} (h : b i = bi) : b.reindex_range.repr x ⟨bi, ⟨i, h⟩⟩ = b.repr x i := begin nontriviality, subst h, refine (b.repr_apply_eq (λ x i, b.reindex_range.repr x ⟨b i, _⟩) _ _ _ x i).symm, { intros x y, ext i, simp only [pi.add_apply, linear_equiv.map_add, finsupp.coe_add] }, { intros c x, ext i, simp only [pi.smul_apply, linear_equiv.map_smul, finsupp.coe_smul] }, { intros i, ext j, simp only [reindex_range_repr_self], refine @finsupp.single_apply_left _ _ _ _ (λ i, (⟨b i, _⟩ : set.range b)) _ _ _ _, exact λ i j h, b.injective (subtype.mk.inj h) } end @[simp] lemma reindex_range_repr (x : M) (i : ι) (h := set.mem_range_self i) : b.reindex_range.repr x ⟨b i, h⟩ = b.repr x i := b.reindex_range_repr' _ rfl end reindex protected lemma linear_independent : linear_independent R b := linear_independent_iff.mpr $ λ l hl, calc l = b.repr (finsupp.total _ _ _ b l) : (b.repr_total l).symm ... = 0 : by rw [hl, linear_equiv.map_zero] protected lemma ne_zero [nontrivial R] (i) : b i ≠ 0 := b.linear_independent.ne_zero i protected lemma mem_span (x : M) : x ∈ span R (range b) := by { rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], exact submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (submodule.subset_span ⟨i, rfl⟩)) } protected lemma span_eq : span R (range b) = ⊤ := eq_top_iff.mpr $ λ x _, b.mem_span x section constr variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] /-- Construct a linear map given the value at the basis. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ def constr : (ι → M') ≃ₗ[S] (M →ₗ[R] M') := { to_fun := λ f, (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp b.repr, inv_fun := λ f i, f (b i), left_inv := λ f, by { ext, simp }, right_inv := λ f, by { refine b.ext (λ i, _), simp }, map_add' := λ f g, by { refine b.ext (λ i, _), simp }, map_smul' := λ c f, by { refine b.ext (λ i, _), simp } } theorem constr_def (f : ι → M') : b.constr S f = (finsupp.total M' M' R id).comp ((finsupp.lmap_domain R R f).comp b.repr) := rfl theorem constr_apply (f : ι → M') (x : M) : b.constr S f x = (b.repr x).sum (λ b a, a • f b) := by { simp only [constr_def, linear_map.comp_apply, finsupp.lmap_domain_apply, finsupp.total_apply], rw finsupp.sum_map_domain_index; simp [add_smul] } @[simp] lemma constr_basis (f : ι → M') (i : ι) : (b.constr S f : M → M') (b i) = f i := by simp [basis.constr_apply, b.repr_self] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (h : ∀i, g i = f (b i)) : b.constr S g = f := b.ext $ λ i, (b.constr_basis S g i).trans (h i) lemma constr_self (f : M →ₗ[R] M') : b.constr S (λ i, f (b i)) = f := b.constr_eq S $ λ x, rfl lemma constr_range [nonempty ι] {f : ι → M'} : (b.constr S f).range = span R (range f) := by rw [b.constr_def S f, linear_map.range_comp, linear_map.range_comp, linear_equiv.range, ← finsupp.supported_univ, finsupp.lmap_domain_supported, ←set.image_univ, ← finsupp.span_eq_map_total, set.image_id] end constr section equiv variables (b' : basis ι' R M') (e : ι ≃ ι') variables [add_comm_monoid M''] [module R M''] /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and the index types are equivalent, `b.equiv b' e` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `b' (e i)`. -/ protected def equiv : M ≃ₗ[R] M' := b.repr.trans (b'.reindex e.symm).repr.symm @[simp] lemma equiv_apply : b.equiv b' e (b i) = b' (e i) := by simp [basis.equiv] @[simp] lemma equiv_refl : b.equiv b (equiv.refl ι) = linear_equiv.refl R M := b.ext' (λ i, by simp) @[simp] lemma equiv_symm : (b.equiv b' e).symm = b'.equiv b e.symm := b'.ext' $ λ i, (b.equiv b' e).injective (by simp) @[simp] lemma equiv_trans {ι'' : Type*} (b'' : basis ι'' R M'') (e : ι ≃ ι') (e' : ι' ≃ ι'') : (b.equiv b' e).trans (b'.equiv b'' e') = b.equiv b'' (e.trans e') := b.ext' (λ i, by simp) end equiv section prod variables (b' : basis ι' R M') /-- `basis.prod` maps a `ι`-indexed basis for `M` and a `ι'`-indexed basis for `M'` to a `ι ⊕ ι'`-index basis for `M × M'`. -/ protected def prod : basis (ι ⊕ ι') R (M × M') := of_repr ((b.repr.prod b'.repr).trans (finsupp.sum_finsupp_lequiv_prod_finsupp R).symm) @[simp] lemma prod_repr_inl (x) (i) : (b.prod b').repr x (sum.inl i) = b.repr x.1 i := rfl @[simp] lemma prod_repr_inr (x) (i) : (b.prod b').repr x (sum.inr i) = b'.repr x.2 i := rfl lemma prod_apply_inl_fst (i) : (b.prod b' (sum.inl i)).1 = b i := b.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inl_injective } lemma prod_apply_inr_fst (i) : (b.prod b' (sum.inr i)).1 = 0 := b.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inr_ne_inl } lemma prod_apply_inl_snd (i) : (b.prod b' (sum.inl i)).2 = 0 := b'.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inl_ne_inr } lemma prod_apply_inr_snd (i) : (b.prod b' (sum.inr i)).2 = b' i := b'.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inr_injective } @[simp] lemma prod_apply (i) : b.prod b' i = sum.elim (linear_map.inl R M M' ∘ b) (linear_map.inr R M M' ∘ b') i := by { ext; cases i; simp only [prod_apply_inl_fst, sum.elim_inl, linear_map.inl_apply, prod_apply_inr_fst, sum.elim_inr, linear_map.inr_apply, prod_apply_inl_snd, prod_apply_inr_snd, comp_app] } end prod section no_zero_smul_divisors -- Can't be an instance because the basis can't be inferred. protected lemma no_zero_smul_divisors [no_zero_divisors R] (b : basis ι R M) : no_zero_smul_divisors R M := ⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin rw [← b.total_repr x, ← linear_map.map_smul] at hcx, have := linear_independent_iff.mp b.linear_independent (c • b.repr x) hcx, rw smul_eq_zero at this, exact this.resolve_right (λ hr, hx (b.repr.map_eq_zero_iff.mp hr)) end)⟩ protected lemma smul_eq_zero [no_zero_divisors R] (b : basis ι R M) {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := @smul_eq_zero _ _ _ _ _ b.no_zero_smul_divisors _ _ end no_zero_smul_divisors section singleton /-- `basis.singleton ι R` is the basis sending the unique element of `ι` to `1 : R`. -/ protected def singleton (ι R : Type*) [unique ι] [semiring R] : basis ι R R := of_repr { to_fun := λ x, finsupp.single (default ι) x, inv_fun := λ f, f (default ι), left_inv := λ x, by simp, right_inv := λ f, finsupp.unique_ext (by simp), map_add' := λ x y, by simp, map_smul' := λ c x, by simp } @[simp] lemma singleton_apply (ι R : Type*) [unique ι] [semiring R] (i) : basis.singleton ι R i = 1 := apply_eq_iff.mpr (by simp [basis.singleton]) @[simp] lemma singleton_repr (ι R : Type*) [unique ι] [semiring R] (x i) : (basis.singleton ι R).repr x i = x := by simp [basis.singleton, unique.eq_default i] lemma basis_singleton_iff {R M : Type*} [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (ι : Type*) [unique ι] : nonempty (basis ι R M) ↔ ∃ x ≠ 0, ∀ y : M, ∃ r : R, r • x = y := begin fsplit, { rintro ⟨b⟩, refine ⟨b (default ι), b.linear_independent.ne_zero _, _⟩, simpa [span_singleton_eq_top_iff, set.range_unique] using b.span_eq }, { rintro ⟨x, nz, w⟩, refine ⟨of_repr $ linear_equiv.symm { to_fun := λ f, f (default ι) • x, inv_fun := λ y, finsupp.single (default ι) (w y).some, left_inv := λ f, finsupp.unique_ext _, right_inv := λ y, _, map_add' := λ y z, _, map_smul' := λ c y, _ }⟩, { rw [finsupp.add_apply, add_smul] }, { rw [finsupp.smul_apply, smul_assoc] }, { refine smul_right_injective _ nz _, simp only [finsupp.single_eq_same], exact (w (f (default ι) • x)).some_spec }, { simp only [finsupp.single_eq_same], exact (w y).some_spec } } end end singleton section empty variables (M) /-- If `M` is a subsingleton and `ι` is empty, this is the unique `ι`-indexed basis for `M`. -/ protected def empty [subsingleton M] (h_empty : ¬ nonempty ι) : basis ι R M := of_repr { to_fun := λ x, 0, inv_fun := λ f, 0, left_inv := λ x, by simp, right_inv := λ f, by { ext i, cases h_empty ⟨i⟩ }, map_add' := λ x y, by simp, map_smul' := λ c x, by simp } lemma empty_unique [subsingleton M] (h_empty : ¬ nonempty ι) (b : basis ι R M) : b = basis.empty M h_empty := by { ext i, cases h_empty ⟨i⟩ } end empty end basis section fintype open basis open fintype variables [fintype ι] (b : basis ι R M) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans b.repr { to_fun := coe_fn, map_add' := finsupp.coe_add, map_smul' := finsupp.coe_smul, ..finsupp.equiv_fun_on_fintype } /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ b.equiv_fun.to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr b.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma basis.equiv_fun_symm_apply (x : ι → R) : b.equiv_fun.symm x = ∑ i, x i • b i := by { simp [basis.equiv_fun, finsupp.total_apply, finsupp.sum_fintype], refl } @[simp] lemma basis.equiv_fun_apply (u : M) : b.equiv_fun u = b.repr u := rfl lemma basis.sum_equiv_fun (u : M) : ∑ i, b.equiv_fun u i • b i = u := begin conv_rhs { rw ← b.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, b.equiv_fun_apply] end lemma basis.sum_repr (u : M) : ∑ i, b.repr u i • b i = u := b.sum_equiv_fun u @[simp] lemma basis.equiv_fun_self (i j : ι) : b.equiv_fun (b i) j = if i = j then 1 else 0 := by { rw [b.equiv_fun_apply, b.repr_self_apply] } /-- Define a basis by mapping each vector `x : M` to its coordinates `e x : ι → R`, as long as `ι` is finite. -/ def basis.of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : basis ι R M := basis.of_repr $ e.trans $ linear_equiv.symm $ finsupp.linear_equiv_fun_on_fintype R @[simp] lemma basis.of_equiv_fun_repr_apply (e : M ≃ₗ[R] (ι → R)) (x : M) (i : ι) : (basis.of_equiv_fun e).repr x i = e x i := rfl @[simp] lemma basis.coe_of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : (basis.of_equiv_fun e : ι → M) = λ i, e.symm (function.update 0 i 1) := funext $ λ i, e.injective $ funext $ λ j, by simp [basis.of_equiv_fun, finsupp.single_eq_update] variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] @[simp] theorem basis.constr_apply_fintype (f : ι → M') (x : M) : (b.constr S f : M → M') x = ∑ i, (b.equiv_fun x i) • f i := by simp [b.constr_apply, b.equiv_fun_apply, finsupp.sum_fintype] end fintype end module section comm_semiring namespace basis variables [comm_semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] variables (b : basis ι R M) (b' : basis ι' R M') /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and `f`, `g` form a bijection between the basis vectors, `b.equiv' b' f g hf hg hgf hfg` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `f (b i)`. -/ def equiv' (f : M → M') (g : M' → M) (hf : ∀ i, f (b i) ∈ range b') (hg : ∀ i, g (b' i) ∈ range b) (hgf : ∀i, g (f (b i)) = b i) (hfg : ∀i, f (g (b' i)) = b' i) : M ≃ₗ[R] M' := { inv_fun := b'.constr R (g ∘ b'), left_inv := have (b'.constr R (g ∘ b')).comp (b.constr R (f ∘ b)) = linear_map.id, from (b.ext $ λ i, exists.elim (hf i) (λ i' hi', by rw [linear_map.comp_apply, b.constr_basis, function.comp_apply, ← hi', b'.constr_basis, function.comp_apply, hi', hgf, linear_map.id_apply])), λ x, congr_arg (λ (h : M →ₗ[R] M), h x) this, right_inv := have (b.constr R (f ∘ b)).comp (b'.constr R (g ∘ b')) = linear_map.id, from (b'.ext $ λ i, exists.elim (hg i) (λ i' hi', by rw [linear_map.comp_apply, b'.constr_basis, function.comp_apply, ← hi', b.constr_basis, function.comp_apply, hi', hfg, linear_map.id_apply])), λ x, congr_arg (λ (h : M' →ₗ[R] M'), h x) this, .. b.constr R (f ∘ b) } @[simp] lemma equiv'_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι) : b.equiv' b' f g hf hg hgf hfg (b i) = f (b i) := b.constr_basis R _ _ @[simp] lemma equiv'_symm_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι') : (b.equiv' b' f g hf hg hgf hfg).symm (b' i) = g (b' i) := b'.constr_basis R _ _ lemma sum_repr_mul_repr {ι'} [fintype ι'] (b' : basis ι' R M) (x : M) (i : ι) : ∑ (j : ι'), b.repr (b' j) i * b'.repr x j = b.repr x i := begin conv_rhs { rw [← b'.sum_repr x] }, simp_rw [linear_equiv.map_sum, linear_equiv.map_smul, finset.sum_apply'], refine finset.sum_congr rfl (λ j _, _), rw [finsupp.smul_apply, smul_eq_mul, mul_comm] end end basis end comm_semiring section module open linear_map variables {v : ι → M} 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 {c d : R} {x y : M} variables (b : basis ι R M) namespace basis section mk variables (hli : linear_independent R v) (hsp : span R (range v) = ⊤) /-- A linear independent family of vectors spanning the whole module is a basis. -/ protected noncomputable def mk : basis ι R M := basis.of_repr { inv_fun := finsupp.total _ _ _ v, left_inv := λ x, hli.total_repr ⟨x, _⟩, right_inv := λ x, hli.repr_eq rfl, .. hli.repr.comp (linear_map.id.cod_restrict _ (λ h, hsp.symm ▸ submodule.mem_top)) } @[simp] lemma mk_repr : (basis.mk hli hsp).repr x = hli.repr ⟨x, hsp.symm ▸ submodule.mem_top⟩ := rfl lemma mk_apply (i : ι) : basis.mk hli hsp i = v i := show finsupp.total _ _ _ v _ = v i, by simp @[simp] lemma coe_mk : ⇑(basis.mk hli hsp) = v := funext (mk_apply _ _) end mk section span variables (hli : linear_independent R v) /-- A linear independent family of vectors is a basis for their span. -/ protected noncomputable def span : basis ι R (span R (range v)) := basis.mk (linear_independent_span hli) $ begin rw eq_top_iff, intros x _, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, { rw ← set.range_comp }, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), { rw [← span_image, submodule.subtype_eq_val, h₁] }, have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), { rw h₂, apply subtype.mem x }, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, { rw [subtype.ext_iff, ← hy₂], simp }, rwa h_x_eq_y end end span end basis end module section division_ring variables [division_ring K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule namespace basis section exists_basis /-- If `s` is a linear independent set of vectors, we can extend it to a basis. -/ noncomputable def extend (hs : linear_independent K (coe : s → V)) : basis _ K V := basis.mk (@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ (hs.linear_independent_extend _)) (eq_top_iff.mpr $ set_like.coe_subset_coe.mp $ by simpa using hs.subset_span_extend (subset_univ s)) lemma extend_apply_self (hs : linear_independent K (coe : s → V)) (x : hs.extend _) : basis.extend hs x = x := basis.mk_apply _ _ _ @[simp] lemma coe_extend (hs : linear_independent K (coe : s → V)) : ⇑(basis.extend hs) = coe := funext (extend_apply_self hs) lemma range_extend (hs : linear_independent K (coe : s → V)) : range (basis.extend hs) = hs.extend (subset_univ _) := by rw [coe_extend, subtype.range_coe_subtype, set_of_mem_eq] /-- If `v` is a linear independent family of vectors, extend it to a basis indexed by a sum type. -/ noncomputable def sum_extend (hs : linear_independent K v) : basis (ι ⊕ _) K V := let s := set.range v, e : ι ≃ s := equiv.of_injective v hs.injective, b := hs.to_subtype_range.extend (subset_univ (set.range v)) in (basis.extend hs.to_subtype_range).reindex $ equiv.symm $ calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset (hs.to_subtype_range.subset_extend _) lemma subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) : s ⊆ hs.extend (set.subset_univ _) := hs.subset_extend _ section variables (K V) /-- A set used to index `basis.of_vector_space`. -/ noncomputable def of_vector_space_index : set V := (linear_independent_empty K V).extend (subset_univ _) /-- Each vector space has a basis. -/ noncomputable def of_vector_space : basis (of_vector_space_index K V) K V := basis.extend (linear_independent_empty K V) lemma of_vector_space_apply_self (x : of_vector_space_index K V) : of_vector_space K V x = x := basis.mk_apply _ _ _ @[simp] lemma coe_of_vector_space : ⇑(of_vector_space K V) = coe := funext (λ x, of_vector_space_apply_self K V x) lemma of_vector_space_index.linear_independent : linear_independent K (coe : of_vector_space_index K V → V) := by { convert (of_vector_space K V).linear_independent, ext x, rw of_vector_space_apply_self } lemma range_of_vector_space : range (of_vector_space K V) = of_vector_space_index K V := range_extend _ lemma exists_basis : ∃ s : set V, nonempty (basis s K V) := ⟨of_vector_space_index K V, ⟨of_vector_space K V⟩⟩ end end exists_basis end basis open fintype variables (K V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := ⟨card (basis.of_vector_space_index K V), module.card_fintype (basis.of_vector_space K V)⟩ end division_ring section field variables [field K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin let B := basis.of_vector_space_index K V, let hB := basis.of_vector_space K V, have hB₀ : _ := hB.linear_independent.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ : linear_independent K (λ (x : ↥(⇑f '' range (basis.of_vector_space _ _))), ↑x) := @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ f hB₀ (show disjoint _ _, by simp [hf_inj]), rwa [basis.range_of_vector_space K V] at h₁ }, let C := this.extend (subset_univ _), have BC := this.subset_extend (subset_univ _), let hC := basis.extend this, haveI : inhabited V := ⟨0⟩, refine ⟨hC.constr K (C.restrict (inv_fun f)), hB.ext (λ b, _)⟩, rw image_subset_iff at BC, have fb_eq : f b = hC ⟨f b, BC b.2⟩, { change f b = basis.extend this _, rw [basis.extend_apply_self, subtype.coe_mk] }, dsimp [hB], rw [basis.of_vector_space_apply_self, fb_eq, hC.constr_basis], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ instance module.submodule.is_complemented : is_complemented (submodule K V) := ⟨submodule.exists_is_compl⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin let C := basis.of_vector_space_index K V', let hC := basis.of_vector_space K V', haveI : inhabited V := ⟨0⟩, use hC.constr K (C.restrict (inv_fun f)), refine hC.ext (λ c, _), rw [linear_map.comp_apply, hC.constr_basis], simp [right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end /-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole space. -/ lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') : ∃ g : V →ₗ[K] V', g.comp p.subtype = f := let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩ open submodule linear_map /-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map `f : V →ₗ[K] K` such that `p ≤ ker f`. -/ lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) : ∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f := begin rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp, rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩, refine ⟨f, _, _⟩, { rintro rfl, rw [linear_map.zero_comp] at hf, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1, simpa using (linear_map.congr_fun hf _).trans this }, { refine λ x hx, mem_ker.2 _, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0, simpa using (linear_map.congr_fun hf _).trans this } end theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) end field
49283cf0db3a4fa920af126e55086d0c9380242f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/lift.lean
9932cc47836660f30a0e0708d445a89cbac587ee
[ "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
449
lean
import data.nat open nat inductive lift .{l} (A : Type.{l}) : Type.{l+1} := up : A → lift A namespace lift definition down {A : Type} (a : lift A) : A := lift.rec (λ a, a) a theorem down_up {A : Type} (a : A) : down (up a) = a := rfl theorem up_down {A : Type} (a' : lift A) : up (down a') = a' := lift.induction_on a' (λ a, rfl) end lift set_option pp.universes true check nat check lift nat open lift definition one1 : lift nat := up 1
fca8fa33cf022e7e3ba7cdf21a0324d541fa036e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Data/Lsp.lean
12abac02f43be3304db25400429c30d900c628b5
[ "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
571
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Capabilities import Lean.Data.Lsp.Client import Lean.Data.Lsp.Communication import Lean.Data.Lsp.Diagnostics import Lean.Data.Lsp.Extra import Lean.Data.Lsp.InitShutdown import Lean.Data.Lsp.Internal import Lean.Data.Lsp.LanguageFeatures import Lean.Data.Lsp.TextSync import Lean.Data.Lsp.Utf16 import Lean.Data.Lsp.Workspace import Lean.Data.Lsp.Ipc
d4eb807dde5df1dd35891577256b5cda8490b0e5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/idempotents/karoubi.lean
86b704ee356f15642f6b162c5ca3ac5e201e30c0
[ "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
8,644
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.basic import category_theory.preadditive.additive_functor import category_theory.equivalence /-! # The Karoubi envelope of a category In this file, we define the Karoubi envelope `karoubi C` of a category `C`. ## Main constructions and definitions - `karoubi C` is the Karoubi envelope of a category `C`: it is an idempotent complete category. It is also preadditive when `C` is preadditive. - `to_karoubi C : C ⥤ karoubi C` is a fully faithful functor, which is an equivalence (`to_karoubi_is_equivalence`) when `C` is idempotent complete. -/ noncomputable theory open category_theory.category open category_theory.preadditive open category_theory.limits open_locale big_operators namespace category_theory variables (C : Type*) [category C] namespace idempotents /-- In a preadditive category `C`, when an object `X` decomposes as `X ≅ P ⨿ Q`, one may consider `P` as a direct factor of `X` and up to unique isomorphism, it is determined by the obvious idempotent `X ⟶ P ⟶ X` which is the projection onto `P` with kernel `Q`. More generally, one may define a formal direct factor of an object `X : C` : it consists of an idempotent `p : X ⟶ X` which is thought as the "formal image" of `p`. The type `karoubi C` shall be the type of the objects of the karoubi enveloppe of `C`. It makes sense for any category `C`. -/ @[nolint has_nonempty_instance] structure karoubi := (X : C) (p : X ⟶ X) (idem : p ≫ p = p) namespace karoubi variables {C} attribute [simp, reassoc] idem @[ext] lemma ext {P Q : karoubi C} (h_X : P.X = Q.X) (h_p : P.p ≫ eq_to_hom h_X = eq_to_hom h_X ≫ Q.p) : P = Q := begin cases P, cases Q, dsimp at h_X h_p, subst h_X, simpa only [true_and, eq_self_iff_true, id_comp, eq_to_hom_refl, heq_iff_eq, comp_id] using h_p, end /-- A morphism `P ⟶ Q` in the category `karoubi C` is a morphism in the underlying category `C` which satisfies a relation, which in the preadditive case, expresses that it induces a map between the corresponding "formal direct factors" and that it vanishes on the complement formal direct factor. -/ @[ext] structure hom (P Q : karoubi C) := (f : P.X ⟶ Q.X) (comm : f = P.p ≫ f ≫ Q.p) instance [preadditive C] (P Q : karoubi C) : inhabited (hom P Q) := ⟨⟨0, by rw [zero_comp, comp_zero]⟩⟩ @[simp] lemma hom_ext {P Q : karoubi C} {f g : hom P Q} : f = g ↔ f.f = g.f := begin split, { intro h, rw h, }, { ext, } end @[simp, reassoc] lemma p_comp {P Q : karoubi C} (f : hom P Q) : P.p ≫ f.f = f.f := by rw [f.comm, ← assoc, P.idem] @[simp, reassoc] lemma comp_p {P Q : karoubi C} (f : hom P Q) : f.f ≫ Q.p = f.f := by rw [f.comm, assoc, assoc, Q.idem] lemma p_comm {P Q : karoubi C} (f : hom P Q) : P.p ≫ f.f = f.f ≫ Q.p := by rw [p_comp, comp_p] lemma comp_proof {P Q R : karoubi C} (g : hom Q R) (f : hom P Q) : f.f ≫ g.f = P.p ≫ (f.f ≫ g.f) ≫ R.p := by rw [assoc, comp_p, ← assoc, p_comp] /-- The category structure on the karoubi envelope of a category. -/ instance : category (karoubi C) := { hom := karoubi.hom, id := λ P, ⟨P.p, by { repeat { rw P.idem, }, }⟩, comp := λ P Q R f g, ⟨f.f ≫ g.f, karoubi.comp_proof g f⟩, } @[simp] lemma comp_f {P Q R : karoubi C} (f : P ⟶ Q) (g : Q ⟶ R) : (f ≫ g).f = f.f ≫ g.f := by refl @[simp] lemma id_eq {P : karoubi C} : 𝟙 P = ⟨P.p, by repeat { rw P.idem, }⟩ := by refl /-- It is possible to coerce an object of `C` into an object of `karoubi C`. See also the functor `to_karoubi`. -/ instance coe : has_coe_t C (karoubi C) := ⟨λ X, ⟨X, 𝟙 X, by rw comp_id⟩⟩ @[simp] lemma coe_X (X : C) : (X : karoubi C).X = X := by refl @[simp] lemma coe_p (X : C) : (X : karoubi C).p = 𝟙 X := by refl @[simp] lemma eq_to_hom_f {P Q : karoubi C} (h : P = Q) : karoubi.hom.f (eq_to_hom h) = P.p ≫ eq_to_hom (congr_arg karoubi.X h) := by { subst h, simp only [eq_to_hom_refl, karoubi.id_eq, comp_id], } end karoubi /-- The obvious fully faithful functor `to_karoubi` sends an object `X : C` to the obvious formal direct factor of `X` given by `𝟙 X`. -/ @[simps] def to_karoubi : C ⥤ karoubi C := { obj := λ X, ⟨X, 𝟙 X, by rw comp_id⟩, map := λ X Y f, ⟨f, by simp only [comp_id, id_comp]⟩ } instance : full (to_karoubi C) := { preimage := λ X Y f, f.f, } instance : faithful (to_karoubi C) := { } variables {C} @[simps] instance [preadditive C] {P Q : karoubi C} : add_comm_group (P ⟶ Q) := { add := λ f g, ⟨f.f+g.f, begin rw [add_comp, comp_add], congr', exacts [f.comm, g.comm], end⟩, zero := ⟨0, by simp only [comp_zero, zero_comp]⟩, zero_add := λ f, by { ext, simp only [zero_add], }, add_zero := λ f, by { ext, simp only [add_zero], }, add_assoc := λ f g h', by simp only [add_assoc], add_comm := λ f g, by { ext, apply_rules [add_comm], }, neg := λ f, ⟨-f.f, by simpa only [neg_comp, comp_neg, neg_inj] using f.comm⟩, add_left_neg := λ f, by { ext, apply_rules [add_left_neg], }, } namespace karoubi lemma hom_eq_zero_iff [preadditive C] {P Q : karoubi C} {f : hom P Q} : f = 0 ↔ f.f = 0 := hom_ext /-- The map sending `f : P ⟶ Q` to `f.f : P.X ⟶ Q.X` is additive. -/ @[simps] def inclusion_hom [preadditive C] (P Q : karoubi C) : add_monoid_hom (P ⟶ Q) (P.X ⟶ Q.X) := { to_fun := λ f, f.f, map_zero' := rfl, map_add' := λ f g, rfl } @[simp] lemma sum_hom [preadditive C] {P Q : karoubi C} {α : Type*} (s : finset α) (f : α → (P ⟶ Q)) : (∑ x in s, f x).f = ∑ x in s, (f x).f := add_monoid_hom.map_sum (inclusion_hom P Q) f s end karoubi /-- The category `karoubi C` is preadditive if `C` is. -/ instance [preadditive C] : preadditive (karoubi C) := { hom_group := λ P Q, by apply_instance, } instance [preadditive C] : functor.additive (to_karoubi C) := { } open karoubi variables (C) instance : is_idempotent_complete (karoubi C) := begin refine ⟨_⟩, intros P p hp, have hp' := hom_ext.mp hp, simp only [comp_f] at hp', use ⟨P.X, p.f, hp'⟩, use ⟨p.f, by rw [comp_p p, hp']⟩, use ⟨p.f, by rw [hp', p_comp p]⟩, split; simpa only [hom_ext] using hp', end instance [is_idempotent_complete C] : ess_surj (to_karoubi C) := ⟨λ P, begin have h : is_idempotent_complete C := infer_instance, rcases is_idempotent_complete.idempotents_split P.X P.p P.idem with ⟨Y,i,e,⟨h₁,h₂⟩⟩, use Y, exact nonempty.intro { hom := ⟨i, by erw [id_comp, ← h₂, ← assoc, h₁, id_comp]⟩, inv := ⟨e, by erw [comp_id, ← h₂, assoc, h₁, comp_id]⟩, }, end⟩ /-- If `C` is idempotent complete, the functor `to_karoubi : C ⥤ karoubi C` is an equivalence. -/ def to_karoubi_is_equivalence [is_idempotent_complete C] : is_equivalence (to_karoubi C) := equivalence.of_fully_faithfully_ess_surj (to_karoubi C) namespace karoubi variables {C} /-- The split mono which appears in the factorisation `decomp_id P`. -/ @[simps] def decomp_id_i (P : karoubi C) : P ⟶ P.X := ⟨P.p, by erw [coe_p, comp_id, P.idem]⟩ /-- The split epi which appears in the factorisation `decomp_id P`. -/ @[simps] def decomp_id_p (P : karoubi C) : (P.X : karoubi C) ⟶ P := ⟨P.p, by erw [coe_p, id_comp, P.idem]⟩ /-- The formal direct factor of `P.X` given by the idempotent `P.p` in the category `C` is actually a direct factor in the category `karoubi C`. -/ lemma decomp_id (P : karoubi C) : 𝟙 P = (decomp_id_i P) ≫ (decomp_id_p P) := by { ext, simp only [comp_f, id_eq, P.idem, decomp_id_i, decomp_id_p], } lemma decomp_p (P : karoubi C) : (to_karoubi C).map P.p = (decomp_id_p P) ≫ (decomp_id_i P) := by { ext, simp only [comp_f, decomp_id_p_f, decomp_id_i_f, P.idem, to_karoubi_map_f], } lemma decomp_id_i_to_karoubi (X : C) : decomp_id_i ((to_karoubi C).obj X) = 𝟙 _ := by { ext, refl, } lemma decomp_id_p_to_karoubi (X : C) : decomp_id_p ((to_karoubi C).obj X) = 𝟙 _ := by { ext, refl, } lemma decomp_id_i_naturality {P Q : karoubi C} (f : P ⟶ Q) : f ≫ decomp_id_i _ = decomp_id_i _ ≫ ⟨f.f, by erw [comp_id, id_comp]⟩ := by { ext, simp only [comp_f, decomp_id_i_f, karoubi.comp_p, karoubi.p_comp], } lemma decomp_id_p_naturality {P Q : karoubi C} (f : P ⟶ Q) : decomp_id_p P ≫ f = (⟨f.f, by erw [comp_id, id_comp]⟩ : (P.X : karoubi C) ⟶ Q.X) ≫ decomp_id_p Q := by { ext, simp only [comp_f, decomp_id_p_f, karoubi.comp_p, karoubi.p_comp], } end karoubi end idempotents end category_theory
7386ed6bfa8fb80cad72197f58cfbe46c3eff788
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/zfc.lean
ff71ce2d22ec9d16aecdc14cfc2105764f6b554c
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
21,652
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .bfol .forcing .forcing_CH open lattice open bSet open fol local notation h :: t := dvector.cons h t local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`:0) := l local infixr ` ⟹' `:65 := lattice.imp local prefix `∃'` := bd_ex local prefix `∼` := bd_not local infixr ` ⊓' `:70 := bd_and local infixr ` ⊔' `:70 := bd_or local infix ` ⟹'' `:62 := bd_imp local infix ` ⇔' `:50 := lattice.biimp -- local infix ` ⇔ `:61 := bd_biimp universe u section ZFC inductive ZFC_rel : ℕ → Type 1 | ε : ZFC_rel 2 inductive ZFC_func : ℕ → Type 1 | emptyset : ZFC_func 0 | pr : ZFC_func 2 | ω : ZFC_func 0 | P : ZFC_func 1 | Union : ZFC_func 1 def L_ZFC : Language.{1} := { functions := ZFC_func, relations := ZFC_rel } end ZFC section ZFC variables {β : Type 0} [nontrivial_complete_boolean_algebra β] def bSet_model_fun_map : Π {n : ℕ}, L_ZFC.functions n → dvector (bSet β) n → bSet β := begin intros n S, induction S, from λ _, bSet.empty, from λ x, by {cases x, refine bSet.pair x_x _, cases x_xs, from x_xs_x}, from λ _, bSet.omega, from λ x, by {cases x, exact bv_powerset x_x}, from λ x, by {cases x, from bv_union ‹_›} end def bSet_model_rel_map : Π {n : ℕ}, L_ZFC.relations n → dvector (bSet β) n → β := begin intros n R, induction R, intro x, cases x, cases x_xs, from x_x ∈ᴮ x_xs_x end variable (β) def V : bStructure L_ZFC (β) := { carrier := (bSet β), fun_map := by apply bSet_model_fun_map, rel_map := by apply bSet_model_rel_map, eq := bv_eq, eq_refl := bv_eq_refl, eq_symm := by apply bv_eq_symm, eq_trans := by apply bv_eq_trans, fun_congr := begin intros n F, cases F, {intros x y, cases x, cases y, simp}, tactic.rotate 1, {intros x y, cases x, cases y, simp}, {intros x y, cases x, cases y, cases x_xs, cases y_xs, change (_ ⊓ _ : β) ≤ (bv_powerset _) =ᴮ (bv_powerset _), simp, tidy_context, apply bv_powerset_congr ‹_› }, {intros x y, cases x, cases y, cases x_xs, cases y_xs, change (_ ⊓ _ : β) ≤ (bv_union _) =ᴮ (bv_union _), simp, tidy_context, from bv_union_congr ‹_›}, {intros x y, cases x, cases y, cases x_xs, cases y_xs, change (_ ⊓ (_ ⊓ _) : β) ≤ pair x_x x_xs_x =ᴮ pair y_x y_xs_x, cases x_xs_xs, cases y_xs_xs, simp } end, rel_congr := begin intros n R, cases R, intros x y, cases x, cases y, cases x_xs, cases y_xs, cases x_xs_xs, cases y_xs_xs, change ((_ ⊓ _) ⊓ (_ ∈ᴮ _) : β) ≤ (_ ∈ᴮ _), simp, tidy_context, apply mem_congr; from ‹_› end} @[simp] lemma carrier_V : ↥(V β) = bSet β := rfl @[simp]lemma V_forall {C : (V β) → β} : (⨅(x : V β), C x) = (⨅(x : bSet β), C x) := rfl @[simp]lemma V_exists {C : (V β) → β} : (⨆(x : V β), C x) = (⨆(x : bSet β), C x) := rfl @[simp]lemma V_eq {a b} : (V β).eq a b = a =ᴮ b := rfl @[instance]lemma V_β_nonempty : nonempty (V β) := ⟨bSet.empty⟩ lemma alpha_equiv₁ {C : (bSet β) → β} : (⨅(x : bSet β), C x) = ⨅(y : bSet β), C y := rfl lemma alpha_equiv₂ {C : (bSet β) → β} : (⨆(x : bSet β), C x) = ⨆(y : bSet β), C y := rfl def emptyset {n} : bounded_term L_ZFC n := bd_const ZFC_func.emptyset notation `∅'` := emptyset def omega {n} : bounded_term L_ZFC n := bd_const ZFC_func.ω notation `ω'` := omega def Powerset {n} : bounded_term L_ZFC n → bounded_term L_ZFC n := bd_app (bd_func ZFC_func.P) notation `P'` := Powerset def mem {n} (t₁ t₂ : bounded_term L_ZFC n) : bounded_formula L_ZFC n := @bounded_formula_of_relation L_ZFC 2 n ZFC_rel.ε t₁ t₂ local infix ` ∈'`:100 := _root_.mem def pair' {n} (t₁ t₂ : bounded_term L_ZFC n) : bounded_term L_ZFC n := @bounded_term_of_function L_ZFC 2 n ZFC_func.pr t₁ t₂ def union' {n} : bounded_term L_ZFC n → bounded_term L_ZFC n := bd_app (bd_func ZFC_func.Union) notation `⋃'` := union' local prefix `&'`:max := bd_var @[simp] lemma boolean_realize_bounded_formula_mem {n} {v : dvector (V β) n} (t₁ t₂ : bounded_term L_ZFC n) : boolean_realize_bounded_formula v (t₁ ∈' t₂) ([]) = boolean_realize_bounded_term v t₁ ([]) ∈ᴮ boolean_realize_bounded_term v t₂ ([]) := by refl @[simp] lemma boolean_realize_bounded_term_Union {n} {v : dvector (V β) n} (t : bounded_term L_ZFC n) : boolean_realize_bounded_term v (⋃' t) ([]) = bv_union (boolean_realize_bounded_term v t ([])) := by refl @[simp] lemma boolean_realize_bounded_term_Powerset {n} {v : dvector (V β) n} (t : bounded_term L_ZFC n) : boolean_realize_bounded_term v (P' t) ([]) = bv_powerset (boolean_realize_bounded_term v t ([])) := by refl @[simp] lemma boolean_realize_bounded_term_omega {n} {v : dvector (V β) n} : boolean_realize_bounded_term v ω' ([]) = bSet.omega := by refl @[simp] lemma boolean_realize_bounded_term_emptyset {n} {v : dvector (V β) n} : boolean_realize_bounded_term v ∅' ([]) = bSet.empty := by refl @[simp]lemma boolean_realize_bounded_term_pair {n} {v : dvector (V β) n} (t₁ t₂ : bounded_term L_ZFC n) : boolean_realize_bounded_term v (pair' t₁ t₂) ([]) = pair (boolean_realize_bounded_term v t₁ ([])) (boolean_realize_bounded_term v t₂ ([])) := by refl @[simp] lemma fin_0 {n : ℕ} : (0 : fin (n+1)).1 = 0 := by refl @[simp] lemma fin_1 {n : ℕ} : (1 : fin (n+2)).1 = 1 := by refl @[simp] lemma fin_2 {n : ℕ} : (2 : fin (n+3)).1 = 2 := by refl @[simp] lemma fin_3 {n : ℕ} : (3 : fin (n+4)).1 = 3 := by refl def axiom_of_emptyset : sentence L_ZFC := ∀' (∼(&0 ∈' ∅')) lemma bSet_models_emptyset : ⊤ ⊩[V β] axiom_of_emptyset := by {change ⊤ ≤ _, simp[axiom_of_emptyset, -top_le_iff], intro x, from empty_spec} -- axiom of ordered pairs -- ∀x y z w, (x, y) = (z, w) ↔ x = z ∧ y = w def axiom_of_ordered_pairs : sentence L_ZFC := ∀' ∀' ∀' ∀'(((pair' &'3 &'2 ≃ pair' &'1 &'0)) ⇔ (&'3 ≃ &'1 ⊓ &'2 ≃ &'0)) lemma bSet_models_ordered_pairs : ⊤ ⊩[V β] axiom_of_ordered_pairs := begin change ⊤ ≤ _, simp[axiom_of_ordered_pairs], intros a b x y, tidy, from eq_of_eq_pair_left, from eq_of_eq_pair_right end -- axiom of extensionality -- ∀ x y, (∀ z, (z ∈ x ↔ z ∈ y)) → x = y def axiom_of_extensionality : sentence L_ZFC := ∀' ∀' (∀'(&'0 ∈' &'2 ⇔ &'0 ∈' &'1) ⟹ (&1 ≃ &0)) lemma bSet_models_extensionality : ⊤ ⊩[V β] axiom_of_extensionality := by { simp [forced_in, axiom_of_extensionality], exact bSet_axiom_of_extensionality } -- axiom schema of "strong" collection -- For every formula `ϕ(x,y,p)` with (at most) `n+2` free variables (`p` is a vector of length `n`), -- ∀ p ∀ A, (∀ x ∈ A, ∃ y, ϕ(x,y,p)) ⟹ -- (∃ B, (∀ x ∈ A, ∃ y ∈ B, ϕ(x,y,p)) ∧ ∀ y ∈ B, ∃ x ∈ A, ϕ(x,y,p)) def axiom_of_collection {n} (ϕ : bounded_formula L_ZFC (n+2)) : sentence L_ZFC := bd_alls (n+1) $ (∀' (&'0 ∈' &'1 ⟹ ∃' (ϕ ↑' 1 # 2))) ⟹ (∃' (∀'(&'0 ∈' &'2 ⟹ ∃' (&'0 ∈' &'2 ⊓ (ϕ ↑' 2 # 2))) ⊓ ∀'(&'0 ∈' &'1 ⟹ ∃' (&'0 ∈' &'3 ⊓' ((ϕ ↑' 3 # 2)[&'1/0] : _))))) lemma lift2_helper {L n l} (f : bounded_preformula L n l) {k} (m : ℕ) : f ↑' (k+2) # m = ((f ↑' (k+1) # m) ↑' 1 # m : _) := by { ext, simp only [lift_bounded_formula_fst], rw [lift_formula_at2_medium], refl, linarith } lemma B_ext_left_realize_bounded_formula {n : ℕ} (ϕ : bounded_formula L_ZFC (n + 1)) (xs : dvector (V β) n) : ∀ (x y : V β), x =ᴮ y ⊓ (boolean_realize_bounded_formula (x::xs) ϕ dvector.nil) ≤ boolean_realize_bounded_formula (y::xs) ϕ dvector.nil := begin intros x y, suffices : (x =ᴮ y = ⨅ (m : fin (n+1)), (V β).eq ((x::xs).nth _ m.is_lt) ((y::xs).nth _ m.is_lt)), by {rw this, apply boolean_realize_bounded_formula_congr, apply_instance}, refine le_antisymm _ _, { apply le_infi, rintro ⟨m,Hm⟩, cases m, { refl }, { rw [dvector.nth_cons, dvector.nth_cons], {exact bSet.bv_refl, { exact nat.lt_of_succ_lt_succ Hm }}, }}, { tidy_context, exact a ⟨0, dec_trivial⟩ } end lemma B_ext_right_realize_bounded_formula {n : ℕ} (ϕ : bounded_formula L_ZFC (n + 2)) (xs : dvector (V β) n) : ∀ (x y z : V β), x =ᴮ y ⊓ (boolean_realize_bounded_formula (z::x::xs) ϕ dvector.nil) ≤ boolean_realize_bounded_formula (z::y::xs) ϕ dvector.nil := begin intros x y z, suffices : (x =ᴮ y = ⨅ (m : fin (n+2)), (V β).eq ((z::x::xs).nth _ m.is_lt) ((z::y::xs).nth _ m.is_lt)), by {rw this, apply boolean_realize_bounded_formula_congr, apply_instance}, refine le_antisymm _ _, { apply le_infi, rintro ⟨m,Hm⟩, cases m, { exact bSet.bv_refl }, { cases m, { refl }, { repeat {rw dvector.nth_cons}, { exact bSet.bv_refl, apply nat.lt_of_succ_lt_succ, apply nat.lt_of_succ_lt_succ, from ‹_› }} }}, { tidy_context, exact a ⟨1, dec_trivial⟩ } end lemma bSet_models_collection {n} (ϕ : bounded_formula L_ZFC (n+2)) : ⊤ ⊩[V β] axiom_of_collection ϕ := begin change ⊤ ≤ _, simp only [axiom_of_collection, boolean_realize_sentence_bd_alls], bv_intro xs, cases xs with _ u xs, simp only [ boolean_realize_bounded_formula_and, boolean_realize_bounded_term, imp_top_iff_le, boolean_realize_bounded_formula_ex, top_le_iff, boolean_realize_bounded_formula, boolean_realize_formula_insert_lift2, lift2_helper, boolean_realize_subst_formula0, fin_2 ], have := bSet_axiom_of_collection (λ a b : V β, boolean_realize_bounded_formula (b :: a :: xs) ϕ ([])) _ _ u, simp only [lattice.top_le_iff, bSet.mem, lattice.imp_top_iff_le, lattice.le_infi_iff] at this, exact this, { intros, apply B_ext_left_realize_bounded_formula }, { intros, apply B_ext_right_realize_bounded_formula }, end -- axiom of union -- ∀ u x, x ∈ ⋃ u ↔ ∃ y ∈ u, x ∈ y def axiom_of_union : sentence L_ZFC := ∀' ∀' (&'0 ∈' ⋃' &'1 ⇔ (∃' (&'0 ∈' &'2 ⊓ &'1 ∈' &'0))) lemma bSet_models_union : ⊤ ⊩[V β] axiom_of_union := begin simp [-top_le_iff, forced_in, axiom_of_union, -lattice.le_inf_iff], intros x z, have := @bv_union_spec' _ _ x ⊤, replace this := this z, dsimp at this, bv_split, bv_split_goal end -- axiom of powerset -- ∀ u x, x ∈ P(u) ↔ ∀ y ∈ x, y ∈ u def axiom_of_powerset : sentence L_ZFC := ∀' ∀' (&'0 ∈' P' &'1 ⇔ (∀' (&'0 ∈' &'1 ⟹ &'0 ∈' &'2))) lemma bSet_models_powerset : ⊤ ⊩[V β] axiom_of_powerset := begin simp [forced_in, axiom_of_powerset, -lattice.le_inf_iff, -top_le_iff], intros x z, have := @bv_powerset_spec _ _ x z, rw [subset_unfold'] at this, apply le_inf, bv_imp_intro, exact this.mpr H, bv_imp_intro, exact this.mp H end /-- &1 ⊆ &0 ↔ ∀ z, (z ∈ &1 ⟹ z ∈ &0)-/ def subset'' {n} (t₁ t₂ : bounded_term L_ZFC n): bounded_formula L_ZFC n := ∀' (&'0 ∈' (t₁ ↑ 1) ⟹ &'0 ∈' (t₂ ↑ 1)) local infix ` ⊆'`:100 := subset'' @[simp] lemma boolean_realize_bounded_formula_subset {n} {v : dvector (V β) n} (t₁ t₂ : bounded_term L_ZFC n) : boolean_realize_bounded_formula v (t₁ ⊆' t₂) ([]) = boolean_realize_bounded_term v t₁ ([]) ⊆ᴮ boolean_realize_bounded_term v t₂ ([]) := by { simp [subset'', subset_unfold'] } /- `z` is transitive if `∀ x, x ∈ z ⟹ x ⊆ z` -/ def is_transitive_f : bounded_formula L_ZFC 1 := ∀' ((&'0 ∈' &'1) ⟹ &'0 ⊆' &'1) /- `z` is `∈`-trichotomous if `∀ x y ∈ z, x = y ∨ x ∈ y ∨ y ∈ x` -/ def epsilon_trichotomy_f : bounded_formula L_ZFC 1 := ∀' ((&'0 ∈' &'1) ⟹''(∀' (&'0 ∈' &'2 ⟹'' (&'1 ≃ &'0 ⊔' &'1 ∈' &'0) ⊔' &'0 ∈' &'1))) /- `z` is `∈`-well-founded if `∀ x, x ⊆ z ⟹ x ≠ ∅ ⟹ ∃y ∈ x. ∀w ∈ x. w ∉ y`. Note: this is true for every set by regularity, so we don't have to assume this. But we do it for completeness, to explicitly state that the order relation is well-founded. -/ def epsilon_well_founded_f : bounded_formula L_ZFC 1 := ∀' (((&'0 ⊆' &'1) ⟹'' ((∼(&'0 ≃ ∅')) ⟹'' ∃' (&'0 ∈' &'1 ⊓' (∀' (&'0 ∈' &'2 ⟹'' ∼(&'0 ∈' &'1))))))) /- `z` is `∈`-well-order if it is `∈`-well-founded and `∈`-trichotomous. -/ def ewo_f : bounded_formula L_ZFC 1 := epsilon_trichotomy_f ⊓' epsilon_well_founded_f /- `z` is an ordinal if forms is an `∈`-well-order and `∈` is transitive on `z`. -/ def Ord_f : bounded_formula L_ZFC 1 := ewo_f ⊓' is_transitive_f @[simp]lemma Ord_f_is_Ord {x : V β} : boolean_realize_bounded_formula (by exact [x]) Ord_f dvector.nil = Ord x := by {simp [Ord_f,ewo_f,is_transitive_f,epsilon_well_founded_f, epsilon_trichotomy_f], refl} -- this is the usual axiom of infinity, plus a characterization of omega as the least limit ordinal def axiom_of_infinity : sentence L_ZFC := (∅' ∈' ω' ⊓' ∀'(&'0 ∈' ω' ⟹ ∃' (&'0 ∈' ω' ⊓' &'1 ∈' &'0))) ⊓' (∃' (Ord_f ⊓' ω' ≃ &'0)) ⊓' ∀' (Ord_f ⟹ ((∅' ∈' &'0 ⊓' ∀'(&'0 ∈' &'1 ⟹ ∃' (&'0 ∈' &'2 ⊓' &'1 ∈' &'0))) ⟹ ω' ⊆' &0)) lemma bSet_models_infinity : ⊤ ⊩[V β] axiom_of_infinity := begin simp [forced_in, axiom_of_infinity, boolean_realize_sentence, -lattice.le_inf_iff, -top_le_iff], refine le_inf _ _, { exact bSet_axiom_of_infinity' }, { refine le_inf _ _, { apply bv_use bSet.omega, exact le_inf Ord_omega bv_refl }, { exact omega_least_is_limit } } end -- axiom of regularity -- ∀ x, x ≠ ∅ ⟹ ∃ y ∈ x, ∀ z ∈ x, z ∉ y def axiom_of_regularity : sentence L_ZFC := ∀' (∼(&0 ≃ ∅') ⟹ (∃' (&'0 ∈' &'1 ⊓ ∀' (&'0 ∈' &'2 ⟹ ∼(&'0 ∈' &'1))))) lemma bSet_models_regularity : ⊤ ⊩[V β] axiom_of_regularity := begin change ⊤ ≤ _, unfold axiom_of_regularity, simp[-top_le_iff], intro x, bv_imp_intro, apply bSet_axiom_of_regularity, convert H end /- ∀ x, x ≠ ∅ ∧ ((∀ y, y ⊆ x ∧ ∀ w₁ w₂ ∈ y, w₁ ⊆ w₂ ∨ w₂ ⊆ w₁) → (⋃y) ∈ x) → ∃ c ∈ x, ∀ z ∈ x, c ⊆ z → c = z -/ def zorns_lemma : sentence L_ZFC := ∀' (∼ (&'0 ≃ ∅') ⟹ (∀' (&'0 ⊆' &'1 ⊓' (∀' ∀' ((&'1 ∈' &'2 ⊓' &'0 ∈' &'2) ⟹ (&'1 ⊆' &'0 ⊔' &'0 ⊆' &'1))) ⟹ (⋃' &' 0 ∈' &'1))) ⟹ (∃' (&'0 ∈' &'1 ⊓ ∀' (&'0 ∈' &'2 ⟹ &'1 ⊆' &'0 ⟹ &'1 ≃ &'0 )))) lemma bSet_models_Zorn : ⊤ ⊩[V β] zorns_lemma := begin simp [forced_in, zorns_lemma, boolean_realize_sentence, -lattice.le_inf_iff, -top_le_iff, -lattice.le_infi_iff], from bSet_zorns_lemma' end def ZFC : Theory L_ZFC := {axiom_of_emptyset, axiom_of_ordered_pairs, axiom_of_extensionality, axiom_of_union, axiom_of_powerset, axiom_of_infinity, axiom_of_regularity, zorns_lemma} ∪ set.Union (λ(n : ℕ), axiom_of_collection '' (set.univ : set $ bounded_formula L_ZFC (n+2))) theorem bSet_models_ZFC : ⊤ ⊩[V β] ZFC := begin change ⊤ ≤ _, bv_intro f, bv_intro H, repeat{auto_cases}; try{subst H}; try {cases H}, from bSet_models_Zorn _, from bSet_models_regularity _, from bSet_models_infinity _, from bSet_models_powerset _, from bSet_models_union _, from bSet_models_extensionality _, from bSet_models_ordered_pairs _, from bSet_models_emptyset _, from bSet_models_collection _ ‹_› end include β theorem ZFC_consistent : is_consistent ZFC := consis_of_exists_bmodel (bSet_models_ZFC β) omit β /-- f is =ᴮ-extensional if for every w₁ w₂ v₁ v₂, if pair (w₁, v₁) and pair (w₂, v₂) ∈ f and w₁ =ᴮ w₂, then v₁ =ᴮ v₂ -/ def is_func_f : bounded_formula L_ZFC 1 := ∀' ∀' ∀' ∀' ((pair' &'3 &'1 ∈' &'4 ⊓' pair' &'2 &'0 ∈' &'4 ⟹ (&'3 ≃ &'2 ⟹ &'1 ≃ &'0))) @[simp]lemma realize_is_func_f {f : V β} : boolean_realize_bounded_formula (by exact [f]) is_func_f dvector.nil = is_func f := begin simp[is_func_f, bSet.is_func], refl end def is_total'_f : bounded_formula L_ZFC 3 := (∀' (&'0 ∈' &'3 ⟹ (∃' (&'0 ∈' &'3 ⊓' (pair' &'1 &'0 ∈' &'2))))) @[simp]lemma realize_is_total'_f {x y f : V β} : boolean_realize_bounded_formula (by exact [f, y, x]) is_total'_f dvector.nil = is_total x y f := begin simp [bSet.is_total, is_total'_f] end -- is_total'_f₂ S y f is the same as is_total'_f y S f def is_total'_f₂ : bounded_formula L_ZFC 3 := (∀' (&'0 ∈' &'2 ⟹ (∃' (&'0 ∈' &'4 ⊓' (pair' &'1 &'0 ∈' &'2))))) @[simp]lemma realize_is_total'_f₂ {x y f : V β} : boolean_realize_bounded_formula (by exact [f, y, x]) is_total'_f₂ dvector.nil = is_total y x f := begin rw [bSet.is_total, is_total'_f₂], simp, refl end def is_func'_f : bounded_formula L_ZFC 3 := (is_func_f.cast (dec_trivial)) ⊓' is_total'_f def is_func'_f₂ : bounded_formula L_ZFC 3 := (is_func_f.cast dec_trivial) ⊓' is_total'_f₂ @[simp]lemma realize_is_func'_f {x y f : V β} : boolean_realize_bounded_formula (by exact [f, y, x]) is_func'_f dvector.nil = is_func' x y f := by simp [is_func'_f, is_func'] @[simp]lemma realize_is_func'_f₂ {x y f : V β} : boolean_realize_bounded_formula (by exact [f, y, x]) is_func'_f₂ dvector.nil = is_func' y x f := by simp [is_func'_f₂, is_func'] /- `at_most_f x y` means `∃ S, ∃ f, S ⊆ y ∧ f contains a function from S to x ∧ f surjects S onto x` In `bSet` it corresponds to the formula `larger_than y x`. `at_most_f x y` is equivalent to `¬ y ≺ x`. -/ def at_most_f : bounded_formula L_ZFC 2 := ∃' (∃' (((&'1 ⊆' &'3) ⊓' (is_func'_f₂).cast (dec_trivial : 3 ≤ 4)) ⊓' ∀' ( &0 ∈' &3 ⟹ (∃' (&'0 ∈' &'3 ⊓' pair' &'0 &'1 ∈' &'2))))) @[simp]lemma realize_at_most_f {x y : V β} : boolean_realize_bounded_formula ([y,x]) at_most_f dvector.nil = larger_than x y := by simp[larger_than, at_most_f, is_func] def is_inj_f : bounded_formula L_ZFC 1 := ∀' ∀' ∀' ∀' (((pair' &'3 &'1 ∈' &'4 ⊓' pair' &'2 &'0 ∈' &'4) ⊓ &'1 ≃ &'0) ⟹ &'3 ≃ &'2) @[simp]lemma realize_is_inj_f (f : V β) : boolean_realize_bounded_formula (by exact [f]) is_inj_f dvector.nil = is_inj f := by {simp[is_inj_f, is_inj], refl} def injects_into_f : bounded_formula L_ZFC 2 := ∃' (is_func'_f ⊓' is_inj_f.cast (dec_trivial)) @[simp]lemma realize_injects_into {x y : V β} : boolean_realize_bounded_formula (by exact [y,x]) injects_into_f dvector.nil = injects_into x y := by {simp[injects_into_f, injects_into]} def non_empty_f : bounded_formula L_ZFC 1 := ∼(&'0 ≃ ∅') @[simp]lemma non_empty_f_is_non_empty {x : V β} : boolean_realize_bounded_formula (by exact [x]) non_empty_f dvector.nil = not_empty x := by {simp[non_empty_f], refl} /-- The continuum hypothesis is given by the formula `∀x, x is an ordinal ⟹ x ≤ ω ∨ P(ω) ≤ x`. Here `a ≤ b` means there is a surjection from a subset of `b` to `a`. We have to perform two substitutions (`substmax_bounded_formula` and `[../0]`) to apply `at_most_f` to the appropriate arguments. -/ def CH_f : sentence L_ZFC := ∀' (Ord_f ⟹ (substmax_bounded_formula at_most_f ω' ⊔' at_most_f[Powerset omega/0])) variable {β} lemma CH_f_is_CH : ⟦CH_f⟧[V β] = CH₂ := begin have h1 : ∀(x : V β), boolean_realize_bounded_formula ([x]) (substmax_bounded_formula at_most_f omega) ([]) = boolean_realize_bounded_formula ([x,omega]) at_most_f ([]), { intro, refl }, have h2 : ∀(x : V β), boolean_realize_bounded_formula ([x]) (at_most_f[P' omega /0]) ([]) = boolean_realize_bounded_formula (([bv_powerset omega, x] : dvector (V β) 2)) at_most_f ([]), { intro, refl }, -- note: once we have proven realize_substmax_bf and realize_subst0_bf, we can add them to this simp set simp [-substmax_bounded_formula, CH_f, CH₂, neg_supr, sup_assoc, h1, h2, lattice.imp] end lemma CH_f_sound {Γ : β} : Γ ⊩[V β] CH_f ↔ Γ ≤ CH₂ := by {change _ ≤ _ ↔ _ ≤ _, rw CH_f_is_CH} lemma neg_CH_f_sound {Γ : β} : Γ ⊩[V β] ∼CH_f ↔ Γ ≤ - CH₂ := by {change _ ≤ _ ↔ _ ≤ _, rw [boolean_realize_sentence_not, CH_f_is_CH]} end ZFC open pSet cardinal section CH_unprovable lemma V_𝔹_cohen_models_neg_CH : ⊤ ⊩[V 𝔹_cohen] ∼CH_f := begin rw neg_CH_f_sound, exact neg_CH₂ end instance V_𝔹_nonempty : nonempty (V 𝔹_cohen) := ⟨bSet.empty⟩ theorem CH_f_unprovable : ¬ (ZFC ⊢' CH_f) := unprovable_of_model_neg _ (bSet_models_ZFC _) (nontrivial.bot_lt_top) V_𝔹_cohen_models_neg_CH end CH_unprovable open collapse_algebra section neg_CH_unprovable instance V_𝔹_collapse_nonempty : nonempty (V 𝔹_collapse) := ⟨bSet.empty⟩ lemma V_𝔹_collapse_models_CH : ⊤ ⊩[V 𝔹_collapse] CH_f := by { rw CH_f_sound, exact CH₂_true } theorem neg_CH_f_unprovable : ¬ (ZFC ⊢' ∼CH_f) := unprovable_of_model_neg (V 𝔹_collapse) (bSet_models_ZFC _) (nontrivial.bot_lt_top) (by {rw forced_in_not, from V_𝔹_collapse_models_CH}) end neg_CH_unprovable section -- a nicer formulation of CH using formulae @[simp] def Powerset_t : term L_ZFC → term L_ZFC := app (func ZFC_func.P) @[simp] def omega_t : term L_ZFC := func ZFC_func.ω @[simp] def leq_f : formula L_ZFC := at_most_f.fst @[simp] def is_ordinal : formula L_ZFC := Ord_f.fst def CH_formula : formula L_ZFC := ∀' (is_ordinal ⟹ leq_f[omega_t//1] ⊔ leq_f[Powerset_t omega_t//0]) lemma CH_f_fst : CH_f.fst = CH_formula := by { simp [CH_f, CH_formula, -substmax_bounded_formula], refl } end
7c59e11d401b280890a2f8a0334700c0d62530b9
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/relations/random_reln_transitive.lean
b8e6aa8ed220747612bd35cf1951840b627fcd61
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
766
lean
import tactic -- Let X be the set {A,B,C} @[derive fintype] inductive X | A : X | B : X | C : X open X inductive R : X → X → Prop | AB : R A B | AC : R A C instance : decidable_rel R := begin unfold decidable_rel, intros a b, cases a; cases b; [left, right, right, left, left, left, left, left, left]; exact R.AB <|> exact R.AC <|> rintro (_ | _), end instance : decidable (transitive R) := begin unfold transitive, apply_instance, end theorem R_fst {x y : X} : R x y → x = A := begin rintro (hAB | hAC); refl end example : transitive R := begin exact dec_trivial, -- human proof below -- intros p q r, -- intros hpq hqr, -- have hp := R_fst hpq, -- subst hp, -- have hq := R_fst hqr, -- subst hq, -- assumption, end
17dae1a265d13fb84572e9c9fc07eaf85beb79ad
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebraic_topology/dold_kan/p_infty.lean
b95df628099e377230883df0e59c2c21aff6a597
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,955
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.projections import category_theory.idempotents.functor_categories import category_theory.idempotents.functor_extension /-! # Construction of the projection `P_infty` for the Dold-Kan correspondence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. TODO (@joelriou) continue adding the various files referenced below In this file, we construct the projection `P_infty : K[X] ⟶ K[X]` by passing to the limit the projections `P q` defined in `projections.lean`. This projection is a critical tool in this formalisation of the Dold-Kan correspondence, because in the case of abelian categories, `P_infty` corresponds to the projection on the normalized Moore subcomplex, with kernel the degenerate subcomplex. (See `equivalence.lean` for the general strategy of proof.) -/ open category_theory open category_theory.category open category_theory.preadditive open category_theory.simplicial_object open category_theory.idempotents open opposite open_locale simplicial dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] {X : simplicial_object C} lemma P_is_eventually_constant {q n : ℕ} (hqn : n ≤ q) : ((P (q+1)).f n : X _[n] ⟶ _ ) = (P q).f n := begin cases n, { simp only [P_f_0_eq], }, { unfold P, simp only [add_right_eq_self, comp_add, homological_complex.comp_f, homological_complex.add_f_apply, comp_id], exact (higher_faces_vanish.of_P q n).comp_Hσ_eq_zero (nat.succ_le_iff.mp hqn), }, end lemma Q_is_eventually_constant {q n : ℕ} (hqn : n ≤ q) : ((Q (q+1)).f n : X _[n] ⟶ _ ) = (Q q).f n := by simp only [Q, homological_complex.sub_f_apply, P_is_eventually_constant hqn] /-- The endomorphism `P_infty : K[X] ⟶ K[X]` obtained from the `P q` by passing to the limit. -/ def P_infty : K[X] ⟶ K[X] := chain_complex.of_hom _ _ _ _ _ _ (λ n, ((P n).f n : X _[n] ⟶ _ )) (λ n, by simpa only [← P_is_eventually_constant (show n ≤ n, by refl), alternating_face_map_complex.obj_d_eq] using (P (n+1)).comm (n+1) n) /-- The endomorphism `Q_infty : K[X] ⟶ K[X]` obtained from the `Q q` by passing to the limit. -/ def Q_infty : K[X] ⟶ K[X] := 𝟙 _ - P_infty @[simp] lemma P_infty_f_0 : (P_infty.f 0 : X _[0] ⟶ X _[0]) = 𝟙 _ := rfl lemma P_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ X _[n] ) = (P n).f n := rfl @[simp] lemma Q_infty_f_0 : (Q_infty.f 0 : X _[0] ⟶ X _[0]) = 0 := by { dsimp [Q_infty], simp only [sub_self], } lemma Q_infty_f (n : ℕ) : (Q_infty.f n : X _[n] ⟶ X _[n] ) = (Q n).f n := rfl @[simp, reassoc] lemma P_infty_f_naturality (n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ P_infty.f n = P_infty.f n ≫ f.app (op [n]) := P_f_naturality n n f @[simp, reassoc] lemma Q_infty_f_naturality (n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ Q_infty.f n = Q_infty.f n ≫ f.app (op [n]) := Q_f_naturality n n f @[simp, reassoc] lemma P_infty_f_idem (n : ℕ) : (P_infty.f n : X _[n] ⟶ _) ≫ (P_infty.f n) = P_infty.f n := by simp only [P_infty_f, P_f_idem] @[simp, reassoc] lemma P_infty_idem : (P_infty : K[X] ⟶ _) ≫ P_infty = P_infty := by { ext n, exact P_infty_f_idem n, } @[simp, reassoc] lemma Q_infty_f_idem (n : ℕ) : (Q_infty.f n : X _[n] ⟶ _) ≫ (Q_infty.f n) = Q_infty.f n := Q_f_idem _ _ @[simp, reassoc] lemma Q_infty_idem : (Q_infty : K[X] ⟶ _) ≫ Q_infty = Q_infty := by { ext n, exact Q_infty_f_idem n, } @[simp, reassoc] lemma P_infty_f_comp_Q_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ _) ≫ Q_infty.f n = 0 := begin dsimp only [Q_infty], simp only [homological_complex.sub_f_apply, homological_complex.id_f, comp_sub, comp_id, P_infty_f_idem, sub_self], end @[simp, reassoc] lemma P_infty_comp_Q_infty : (P_infty : K[X] ⟶ _) ≫ Q_infty = 0 := by { ext n, apply P_infty_f_comp_Q_infty_f, } @[simp, reassoc] lemma Q_infty_f_comp_P_infty_f (n : ℕ) : (Q_infty.f n : X _[n] ⟶ _) ≫ P_infty.f n = 0 := begin dsimp only [Q_infty], simp only [homological_complex.sub_f_apply, homological_complex.id_f, sub_comp, id_comp, P_infty_f_idem, sub_self], end @[simp, reassoc] lemma Q_infty_comp_P_infty : (Q_infty : K[X] ⟶ _) ≫ P_infty = 0 := by { ext n, apply Q_infty_f_comp_P_infty_f, } @[simp] lemma P_infty_add_Q_infty : (P_infty : K[X] ⟶ _) + Q_infty = 𝟙 _ := by { dsimp only [Q_infty], simp only [add_sub_cancel'_right], } lemma P_infty_f_add_Q_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ _ ) + Q_infty.f n = 𝟙 _ := homological_complex.congr_hom (P_infty_add_Q_infty) n variable (C) /-- `P_infty` induces a natural transformation, i.e. an endomorphism of the functor `alternating_face_map_complex C`. -/ @[simps] def nat_trans_P_infty : alternating_face_map_complex C ⟶ alternating_face_map_complex C := { app := λ _, P_infty, naturality' := λ X Y f, by { ext n, exact P_infty_f_naturality n f, }, } /-- The natural transformation in each degree that is induced by `nat_trans_P_infty`. -/ @[simps] def nat_trans_P_infty_f (n : ℕ) := nat_trans_P_infty C ◫ 𝟙 (homological_complex.eval _ _ n) variable {C} @[simp] lemma map_P_infty_f {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (n : ℕ) : (P_infty : K[((whiskering C D).obj G).obj X] ⟶ _).f n = G.map ((P_infty : alternating_face_map_complex.obj X ⟶ _).f n) := by simp only [P_infty_f, map_P] /-- Given an object `Y : karoubi (simplicial_object C)`, this lemma computes `P_infty` for the associated object in `simplicial_object (karoubi C)` in terms of `P_infty` for `Y.X : simplicial_object C` and `Y.p`. -/ lemma karoubi_P_infty_f {Y : karoubi (simplicial_object C)} (n : ℕ) : ((P_infty : K[(karoubi_functor_category_embedding _ _).obj Y] ⟶ _).f n).f = Y.p.app (op [n]) ≫ (P_infty : K[Y.X] ⟶ _).f n := begin -- We introduce P_infty endomorphisms P₁, P₂, P₃, P₄ on various objects Y₁, Y₂, Y₃, Y₄. let Y₁ := (karoubi_functor_category_embedding _ _).obj Y, let Y₂ := Y.X, let Y₃ := (((whiskering _ _).obj (to_karoubi C)).obj Y.X), let Y₄ := (karoubi_functor_category_embedding _ _).obj ((to_karoubi _).obj Y.X), let P₁ : K[Y₁] ⟶ _ := P_infty, let P₂ : K[Y₂] ⟶ _ := P_infty, let P₃ : K[Y₃] ⟶ _ := P_infty, let P₄ : K[Y₄] ⟶ _ := P_infty, -- The statement of lemma relates P₁ and P₂. change (P₁.f n).f = Y.p.app (op [n]) ≫ P₂.f n, -- The proof proceeds by obtaining relations h₃₂, h₄₃, h₁₄. have h₃₂ : (P₃.f n).f = P₂.f n := karoubi.hom_ext.mp (map_P_infty_f (to_karoubi C) Y₂ n), have h₄₃ : P₄.f n = P₃.f n, { have h := functor.congr_obj (to_karoubi_comp_karoubi_functor_category_embedding _ _) Y₂, simp only [← nat_trans_P_infty_f_app], congr', }, let τ₁ := 𝟙 (karoubi_functor_category_embedding (simplex_categoryᵒᵖ) C), let τ₂ := nat_trans_P_infty_f (karoubi C) n, let τ := τ₁ ◫ τ₂, have h₁₄ := idempotents.nat_trans_eq τ Y, dsimp [τ, τ₁, τ₂, nat_trans_P_infty_f] at h₁₄, rw [id_comp, id_comp, comp_id, comp_id] at h₁₄, /- We use the three equalities h₃₂, h₄₃, h₁₄. -/ rw [← h₃₂, ← h₄₃, h₁₄], simp only [karoubi_functor_category_embedding.map_app_f, karoubi.decomp_id_p_f, karoubi.decomp_id_i_f, karoubi.comp_f], let π : Y₄ ⟶ Y₄ := (to_karoubi _ ⋙ karoubi_functor_category_embedding _ _).map Y.p, have eq := karoubi.hom_ext.mp (P_infty_f_naturality n π), simp only [karoubi.comp_f] at eq, dsimp [π] at eq, rw [← eq, reassoc_of (app_idem Y (op [n]))], end end dold_kan end algebraic_topology
220c9e6af6ca164b8a790d4b6cc19885465b5912
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/linear_algebra/basis.lean
3d3bd86768ee2bc8a5e513ae750da415210f1ee8
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
53,710
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, Alexander Bentkamp -/ import linear_algebra.basic linear_algebra.finsupp order.zorn import data.fintype.card /-! # Linear independence and bases This file defines linear independence and bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. * `is_basis R v` states that the vector family `v` is a basis, i.e. it is linearly independent and spans the entire space. * `is_basis.repr hv x` is the basis version of `linear_independent.repr hv x`. It returns the linear combination representing `x : M` on a basis `v` of `M` (using classical choice). The argument `hv` must be a proof that `is_basis R v`. `is_basis.repr hv` is given as a linear map as well. * `is_basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis `v : ι → M₁`, given `hv : is_basis R v`. ## Main statements * `is_basis.ext` states that two linear maps are equal if they coincide on a basis. * `exists_is_basis` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence, basis -/ noncomputable theory open function set submodule open_locale classical variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} {M : Type*} {M' : Type*} {V : Type*} {V' : Type*} section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] variables [module R M] [module R M'] variables {a b : R} {x y : M} variables (R) (v) /-- Linearly independent family of vectors -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, s.sum (λ i, g i • v i) = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (s.sum $ λ i, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = s.sum (λ j, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j))) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = s.sum (λ j, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (not_nonempty_iff_imp_false.1 h i) end lemma ne_zero_of_linear_independent {i : ι} (ne : 0 ≠ (1:R)) (hv : linear_independent R v) : v i ≠ 0 := λ h, ne $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext, convert h_map_domain a, simp only [finsupp.map_domain_apply hf], end lemma linear_independent_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : linear_independent R v := linear_independent_iff.2 (λ l hl, finsupp.eq_zero_of_zero_eq_one zero_eq_one _) lemma linear_independent.unique (hv : linear_independent R v) {l₁ l₂ : ι →₀ R} : finsupp.total ι M R v l₁ = finsupp.total ι M R v l₂ → l₁ = l₂ := by apply linear_map.ker_eq_bot.1 hv lemma linear_independent.injective (zero_ne_one : (0 : R) ≠ 1) (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { rw finsupp.total_apply, rw finsupp.sum_sub_index, { simp [finsupp.sum_single_index, hij] }, { intros, apply sub_smul } }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, show i = j, { apply or.elim ((finsupp.single_eq_single_iff _ _ _ _).1 h_single_eq), simp, exact λ h, false.elim (zero_ne_one.symm h.1) } end lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := begin rw linear_independent_iff at *, intros l hl, apply hs l, have := congr_arg (submodule.subtype (span R (range v))) hl, convert this, rw [finsupp.total_apply, finsupp.total_apply], unfold finsupp.sum, rw linear_map.map_sum (submodule.subtype (span R (range v))), simp end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin rw [linear_independent_iff, finsupp.total_comp], simp only [linear_map.comp_apply], split, { intros h l hl₁ hl₂, have h_bij : bij_on subtype.val (subtype.val ⁻¹' l.support.to_set : set s) l.support.to_set, { apply bij_on.mk, { unfold maps_to }, { apply subtype.val_injective.inj_on }, intros i hi, rw [image_preimage_eq_inter_range, subtype.range_val], exact ⟨hi, (finsupp.mem_supported _ _).1 hl₁ hi⟩ }, show l = 0, { apply finsupp.eq_zero_of_comap_domain_eq_zero (subtype.val : s → ι) _ h_bij, apply h, convert hl₂, rw [finsupp.lmap_domain_apply, finsupp.map_domain_comap_domain], exact subtype.val_injective, rw subtype.range_val, exact (finsupp.mem_supported _ _).1 hl₁ } }, { intros h l hl, have hl' : finsupp.total ι M R v (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) = 0, { rw finsupp.emb_domain_eq_map_domain ⟨subtype.val, subtype.val_injective⟩ l, apply hl }, apply finsupp.emb_domain_inj.1, rw [h (finsupp.emb_domain ⟨subtype.val, subtype.val_injective⟩ l) _ hl', finsupp.emb_domain_zero], rw [finsupp.mem_supported, finsupp.support_emb_domain], intros x hx, rw [finset.mem_coe, finset.mem_map] at hx, rcases hx with ⟨i, x', hx'⟩, rw ←hx', simp } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ subtype.val : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.to_subtype_range (hv : linear_independent R v) : linear_independent R (λ x, x : range v → M) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, rw linear_independent_subtype, intros l hl₁ hl₂, have h_bij : bij_on v (v ⁻¹' finset.to_set (l.support)) (finset.to_set (l.support)), { apply bij_on.mk, { unfold maps_to }, { apply (linear_independent.injective zero_eq_one hv).inj_on }, intros x hx, rcases mem_range.1 (((finsupp.mem_supported _ _).1 hl₁ : ↑(l.support) ⊆ range v) hx) with ⟨i, hi⟩, rw mem_image, use i, rw [mem_preimage, hi], exact ⟨hx, rfl⟩ }, apply finsupp.eq_zero_of_comap_domain_eq_zero v l, apply linear_independent_iff.1 hv, rw [finsupp.total_comap_domain, finset.sum_preimage v l.support h_bij (λ (x : M), l x • x)], rw [finsupp.total_apply, finsupp.sum] at hl₂, apply hl₂ end lemma linear_independent.of_subtype_range (hv : injective v) (h : linear_independent R (λ x, x : range v → M)) : linear_independent R v := begin rw linear_independent_iff, intros l hl, apply finsupp.injective_map_domain hv, apply linear_independent_subtype.1 h (l.map_domain v), { rw finsupp.mem_supported, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support hx), rw finset.coe_image at this, apply set.image_subset_range _ _ this, }, { rwa [finsupp.total_map_domain _ _ hv, left_id] } end lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ subtype.val : s → M)) : linear_independent R (s.restrict v) := begin have h_restrict : restrict v s = v ∘ (λ x, x.val) := rfl, rw [linear_independent_iff, h_restrict, finsupp.total_comp], intros l hl, have h_map_domain_subtype_eq_0 : l.map_domain subtype.val = 0, { rw linear_independent_comp_subtype at hs, apply hs (finsupp.lmap_domain R R (λ x : subtype s, x.val) l) _ hl, rw finsupp.mem_supported, simp, intros x hx, have := finset.mem_coe.2 (finsupp.map_domain_support (finset.mem_coe.1 hx)), rw finset.coe_image at this, exact subtype.val_image_subset _ _ this }, apply @finsupp.injective_map_domain _ (subtype s) ι, { apply subtype.val_injective }, { simpa }, end lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint_mono_left (finsupp.supported_mono h)) end lemma linear_independent_union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := begin rw [linear_independent_subtype_disjoint, disjoint_def, finsupp.supported_union], intros l h₁ h₂, rw mem_sup at h₁, rcases h₁ with ⟨ls, hls, lt, hlt, rfl⟩, have h_ls_mem_t : finsupp.total M M R id ls ∈ span R t, { rw [← image_id t, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hlt)).1, rw [← linear_map.map_add, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_lt_mem_s : finsupp.total M M R id lt ∈ span R s, { rw [← image_id s, finsupp.span_eq_map_total], apply (add_mem_iff_left (map _ _) (mem_image_of_mem _ hls)).1, rw [← linear_map.map_add, add_comm, linear_map.mem_ker.1 h₂], apply zero_mem }, have h_ls_mem_s : (finsupp.total M M R id) ls ∈ span R s, { rw ← image_id s, apply (finsupp.mem_span_iff_total _).2 ⟨ls, hls, rfl⟩ }, have h_lt_mem_t : (finsupp.total M M R id) lt ∈ span R t, { rw ← image_id t, apply (finsupp.mem_span_iff_total _).2 ⟨lt, hlt, rfl⟩ }, have h_ls_0 : ls = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 hs) _ hls (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id ls) h_ls_mem_s h_ls_mem_t), have h_lt_0 : lt = 0 := disjoint_def.1 (linear_independent_subtype_disjoint.1 ht) _ hlt (linear_map.mem_ker.2 $ disjoint_def.1 hst (finsupp.total M M R id lt) h_lt_mem_s h_lt_mem_t), show ls + lt = 0, by simp [h_ls_0, h_lt_0], end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin haveI := classical.dec (nonempty η), by_cases hη : nonempty η, { refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le hη fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine linear_independent_empty.mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed ((directed_comp _ _ _).2 $ (directed_on_iff_directed _).1 hs) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros ⟨i⟩ s his ih, rw [finset.sup_insert], apply linear_independent_union, { apply hl }, { apply ih }, rw [finset.sup_eq_supr], refine disjoint_mono (le_refl _) _ (hd i _ _ his), { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros ⟨i⟩, exact ⟨i, le_refl _⟩ }, { change finite (plift.up ⁻¹' s.to_set), exact finite_preimage (assume i j _ _, plift.up.inj) s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective zero_eq_one (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only [] at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim (ne_zero_of_linear_independent zero_eq_one (hindep x₁) h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.coe_ext.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.coe_ext.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := classical.not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) (zero_ne_one : 0 ≠ (1 : R)): surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.inj).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.inj).total_repr, { refl }, { exact f.inj } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype {s t : set M} (zero_ne_one : (0 : R) ≠ 1) (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.val_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _ zero_ne_one, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image (hv : linear_independent R v) {f : M →ₗ M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv, rw hv at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent, finsupp.total_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, ker_comp, eq_bot_iff], apply hf_inj, exact λ _, rfl, end lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [disjoint, ← set.image_id s, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [linear_independent_subtype_disjoint, disjoint, ← finsupp.lmap_domain_supported _ _ f, map_inf_eq_map_inf_comap, map_le_iff_le_comap, ← ker_comp], rw [@finsupp.lmap_domain_total _ _ R _ _ _, ker_comp], { exact le_trans (le_inf inf_le_left hf_inj) (le_trans (linear_independent_subtype_disjoint.1 hs) bot_le) }, { simp } end lemma linear_independent_inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin apply linear_independent_union, exact (hs.image_subtype $ by simp), exact (ht.image_subtype $ by simp), rw [span_image, span_image]; simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin by_cases zero_eq_one : (0 : R) = 1, { apply linear_independent_of_zero_eq_one zero_eq_one }, have inj_v : injective v := (linear_independent.injective zero_eq_one hv), have inj_v' : injective v' := (linear_independent.injective zero_eq_one hv'), apply linear_independent.of_subtype_range, { apply sum.elim_injective, { exact injective_comp prod.injective_inl inj_v }, { exact injective_comp prod.injective_inr inj_v' }, { intros, simp [ne_zero_of_linear_independent zero_eq_one hv] } }, { rw sum.elim_range, apply linear_independent_union, { apply linear_independent.to_subtype_range, apply linear_independent.image hv, simp [ker_inl] }, { apply linear_independent.to_subtype_range, apply linear_independent.image hv', simp [ker_inr] }, { apply disjoint_mono _ _ disjoint_inl_inr, { rw [set.range_comp, span_image], apply linear_map.map_le_range }, { rw [set.range_comp, span_image], apply linear_map.map_le_range } } } end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [integral_domain L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action L L; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. s.sum (λ i, ((g i * i x - g i * a x) • i : G → L)) y = s.sum (λ i, (g i * i x - g i * a x) * i y) : pi.finset_sum_apply _ _ _ ... = s.sum (λ i, g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = s.sum (λ i, g i * i x * i y) - s.sum (λ i, g i * a x * i y) : finset.sum_sub_distrib ... = (g a * a x * a y + s.sum (λ i, g i * i x * i y)) - (g a * a x * a y + s.sum (λ i, g i * a x * i y)) : by rw add_sub_add_left_eq_sub ... = (insert a s).sum (λ i, g i * i x * i y) - (insert a s).sum (λ i, g i * a x * i y) : by rw [finset.sum_insert has, finset.sum_insert has] ... = (insert a s).sum (λ i, g i * i (x * y)) - (insert a s).sum (λ i, a x * (g i * i y)) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (insert a s).sum (λ i, (g i • i : G → L)) (x * y) - a x * (insert a s).sum (λ i, (g i • i : G → L)) y : by rw [pi.finset_sum_apply, pi.finset_sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (insert a s).sum (λ i, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype zero_ne_one (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff {s t u: set M} (zero_ne_one : (0 : R) ≠ 1) (hl : linear_independent R (subtype.val : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span zero_ne_one hl hsu htu, span_mono⟩ variables (R) (v) /-- A family of vectors is a basis if it is linearly independent and all vectors are in the span. -/ def is_basis := linear_independent R v ∧ span R (range v) = ⊤ variables {R} {v} section is_basis variables {s t : set M} (hv : is_basis R v) lemma is_basis.mem_span (hv : is_basis R v) : ∀ x, x ∈ span R (range v) := eq_top_iff'.1 hv.2 lemma is_basis.comp (hv : is_basis R v) (f : ι' → ι) (hf : bijective f) : is_basis R (v ∘ f) := begin split, { apply hv.1.comp f hf.1 }, { rw[set.range_comp, range_iff_surjective.2 hf.2, image_univ, hv.2] } end lemma is_basis.injective (hv : is_basis R v) (zero_ne_one : (0 : R) ≠ 1) : injective v := λ x y h, linear_independent.injective zero_ne_one hv.1 h /-- Given a basis, any vector can be written as a linear combination of the basis vectors. They are given by this linear map. This is one direction of `module_equiv_finsupp`. -/ def is_basis.repr : M →ₗ (ι →₀ R) := (hv.1.repr).comp (linear_map.id.cod_restrict _ hv.mem_span) lemma is_basis.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := hv.1.total_repr ⟨x, _⟩ lemma is_basis.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = linear_map.id := linear_map.ext hv.total_repr lemma is_basis.repr_ker : hv.repr.ker = ⊥ := linear_map.ker_eq_bot.2 $ injective_of_left_inverse hv.total_repr lemma is_basis.repr_range : hv.repr.range = finsupp.supported R R univ := by rw [is_basis.repr, linear_map.range, submodule.map_comp, linear_map.map_cod_restrict, submodule.map_id, comap_top, map_top, hv.1.repr_range, finsupp.supported_univ] lemma is_basis.repr_total (x : ι →₀ R) (hx : x ∈ finsupp.supported R R (univ : set ι)) : hv.repr (finsupp.total ι M R v x) = x := begin rw [← hv.repr_range, linear_map.mem_range] at hx, cases hx with w hw, rw [← hw, hv.total_repr], end lemma is_basis.repr_eq_single {i} : hv.repr (v i) = finsupp.single i 1 := by apply hv.1.repr_eq_single; simp /-- Construct a linear map given the value at the basis. -/ def is_basis.constr (f : ι → M') : M →ₗ[R] M' := (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f).comp hv.repr theorem is_basis.constr_apply (f : ι → M') (x : M) : (hv.constr f : M → M') x = (hv.repr x).sum (λb a, a • f b) := by dsimp [is_basis.constr]; rw [finsupp.total_apply, finsupp.sum_map_domain_index]; simp [add_smul] lemma is_basis.ext {f g : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, f (v i) = g (v i)) : f = g := begin apply linear_map.ext (λ x, linear_eq_on (range v) _ (hv.mem_span x)), exact (λ y hy, exists.elim (set.mem_range.1 hy) (λ i hi, by rw ←hi; exact h i)) end lemma constr_basis {f : ι → M'} {i : ι} (hv : is_basis R v) : (hv.constr f : M → M') (v i) = f i := by simp [is_basis.constr_apply, hv.repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (hv : is_basis R v) (h : ∀i, g i = f (v i)) : hv.constr g = f := hv.ext $ λ i, (constr_basis hv).trans (h i) lemma constr_self (f : M →ₗ[R] M') : hv.constr (λ i, f (v i)) = f := constr_eq hv $ λ x, rfl lemma constr_zero (hv : is_basis R v) : hv.constr (λi, (0 : M')) = 0 := constr_eq hv $ λ x, rfl lemma constr_add {g f : ι → M'} (hv : is_basis R v) : hv.constr (λi, f i + g i) = hv.constr f + hv.constr g := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_neg {f : ι → M'} (hv : is_basis R v) : hv.constr (λi, - f i) = - hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_sub {g f : ι → M'} (hs : is_basis R v) : hv.constr (λi, f i - g i) = hs.constr f - hs.constr g := by simp [sub_eq_add_neg, constr_add, constr_neg] -- this only works on functions if `R` is a commutative ring lemma constr_smul {ι R M} [comm_ring R] [add_comm_group M] [module R M] {v : ι → R} {f : ι → M} {a : R} (hv : is_basis R v) : hv.constr (λb, a • f b) = a • hv.constr f := constr_eq hv $ by simp [constr_basis hv] {contextual := tt} lemma constr_range [nonempty ι] (hv : is_basis R v) {f : ι → M'} : (hv.constr f).range = span R (range f) := by rw [is_basis.constr, linear_map.range_comp, linear_map.range_comp, is_basis.repr_range, finsupp.lmap_domain_supported, ←set.image_univ, ←finsupp.span_eq_map_total, image_id] /-- Canonical equivalence between a module and the linear combinations of basis vectors. -/ def module_equiv_finsupp (hv : is_basis R v) : M ≃ₗ[R] ι →₀ R := (hv.1.total_equiv.trans (linear_equiv.of_top _ hv.2)).symm /-- Isomorphism between the two modules, given two modules `M` and `M'` with respective bases `v` and `v'` and a bijection between the two bases. -/ def equiv_of_is_basis {v : ι → M} {v' : ι' → M'} {f : M → M'} {g : M' → M} (hv : is_basis R v) (hv' : is_basis R v') (hf : ∀i, f (v i) ∈ range v') (hg : ∀i, g (v' i) ∈ range v) (hgf : ∀i, g (f (v i)) = v i) (hfg : ∀i, f (g (v' i)) = v' i) : M ≃ₗ M' := { inv_fun := hv'.constr (g ∘ v'), left_inv := have (hv'.constr (g ∘ v')).comp (hv.constr (f ∘ v)) = linear_map.id, from hv.ext $ λ i, exists.elim (hf i) (λ i' hi', by simp [constr_basis, hi'.symm]; rw [hi', hgf]), λ x, congr_arg (λ h:M →ₗ[R] M, h x) this, right_inv := have (hv.constr (f ∘ v)).comp (hv'.constr (g ∘ v')) = linear_map.id, from hv'.ext $ λ i', exists.elim (hg i') (λ i hi, by simp [constr_basis, hi.symm]; rw [hi, hfg]), λ y, congr_arg (λ h:M' →ₗ[R] M', h y) this, ..hv.constr (f ∘ v) } lemma is_basis_inl_union_inr {v : ι → M} {v' : ι' → M'} (hv : is_basis R v) (hv' : is_basis R v') : is_basis R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := begin split, apply linear_independent_inl_union_inr' hv.1 hv'.1, rw [sum.elim_range, span_union, set.range_comp, span_image (inl R M M'), hv.2, map_top, set.range_comp, span_image (inr R M M'), hv'.2, map_top], exact linear_map.sup_range_inl_inr end end is_basis lemma is_basis_singleton_one (R : Type*) [unique ι] [ring R] : is_basis R (λ (_ : ι), (1 : R)) := begin split, { refine linear_independent_iff.2 (λ l, _), rw [finsupp.unique_single l, finsupp.total_single, smul_eq_mul, mul_one], intro hi, simp [hi] }, { refine top_unique (λ _ _, _), simp [submodule.mem_span_singleton] } end protected lemma linear_equiv.is_basis (hs : is_basis R v) (f : M ≃ₗ[R] M') : is_basis R (f ∘ v) := begin split, { apply @linear_independent.image _ _ _ _ _ _ _ _ _ _ hs.1 (f : M →ₗ[R] M'), simp [linear_equiv.ker f] }, { rw set.range_comp, have : span R ((f : M →ₗ[R] M') '' range v) = ⊤, { rw [span_image (f : M →ₗ[R] M'), hs.2], simp }, exact this } end lemma is_basis_span (hs : linear_independent R v) : @is_basis ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self _)⟩) _ _ _ := begin split, { apply linear_independent_span hs }, { rw eq_top_iff', intro x, have h₁ : subtype.val '' set.range (λ i, subtype.mk (v i) _) = range v, by rw ←set.range_comp, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), by rw [←span_image, submodule.subtype_eq_val, h₁], have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), by rw h₂; apply subtype.mem x, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, by rw [subtype.coe_ext, ← hy₂]; simp, rw h_x_eq_y, exact hy₁ } end lemma is_basis_empty (h_empty : ¬ nonempty ι) (h : ∀x:M, x = 0) : is_basis R (λ x : ι, (0 : M)) := ⟨ linear_independent_empty_type h_empty, eq_top_iff'.2 $ assume x, (h x).symm ▸ submodule.zero_mem _ ⟩ lemma is_basis_empty_bot (h_empty : ¬ nonempty ι) : is_basis R (λ _ : ι, (0 : (⊥ : submodule R M))) := begin apply is_basis_empty h_empty, intro x, apply subtype.ext.2, exact (submodule.mem_bot R).1 (subtype.mem x), end open fintype variables [fintype ι] (h : is_basis R v) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def equiv_fun_basis : M ≃ₗ[R] (ι → R) := linear_equiv.trans (module_equiv_finsupp h) { to_fun := finsupp.to_fun, add := λ x y, by ext; exact finsupp.add_apply, smul := λ x y, by ext; exact finsupp.smul_apply, ..finsupp.equiv_fun_on_fintype } theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr (equiv_fun_basis h).to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma equiv_fun_basis_symm_apply (x : ι → R) : (equiv_fun_basis h).symm x = finset.sum finset.univ (λi, x i • v i) := begin change finsupp.sum ((finsupp.equiv_fun_on_fintype.symm : (ι → R) ≃ (ι →₀ R)) x) (λ (i : ι) (a : R), a • v i) = finset.sum finset.univ (λi, x i • v i), dsimp [finsupp.equiv_fun_on_fintype, finsupp.sum], rw finset.sum_filter, refine finset.sum_congr rfl (λi hi, _), by_cases H : x i = 0, { simp [H] }, { simp [H], refl } end end module section vector_space variables {v : ι → V} [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ section set_option class.instance_max_depth 36 lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique [unique ι] (h : v (default ι) ≠ 0): linear_independent K v := begin rw linear_independent_iff, intros l hl, ext i, rw [unique.eq_default i, finsupp.zero_apply], by_contra hc, have := smul_smul (l (default ι))⁻¹ (l (default ι)) (v (default ι)), rw [finsupp.unique_single l, finsupp.total_single] at hl, rw [hl, inv_mul_cancel hc, smul_zero, one_smul] at this, exact h this.symm end lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := begin apply @linear_independent_unique _ _ _ _ _ _ _ _ _, apply set.unique_singleton, apply hx, end lemma disjoint_span_singleton {p : submodule K V} {x : V} (x0 : x ≠ 0) : disjoint p (span K {x}) ↔ x ∉ p := ⟨λ H xp, x0 (disjoint_def.1 H _ xp (singleton_subset_iff.1 subset_span:_)), begin simp [disjoint_def, mem_span_singleton], rintro xp y yp a rfl, by_cases a0 : a = 0, {simp [a0]}, exact xp.elim ((smul_mem_iff p a0).1 yp), end⟩ lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply linear_independent_union hs (linear_independent_singleton x0), rwa [disjoint_span_singleton x0] end lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, haveI := classical.dec (x ∈ span K b), by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end lemma exists_subset_is_basis (hs : linear_independent K (λ x, x : s → V)) : ∃b, s ⊆ b ∧ is_basis K (λ i : b, i.val) := let ⟨b, hb₀, hx, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨ b, hx, @linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ hb₃, by simp; exact eq_top_iff.2 hb₂⟩ variables (K V) lemma exists_is_basis : ∃b : set V, is_basis K (λ i : b, i.val) := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype (@zero_ne_one K _) hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin letI := classical.dec_pred (λx, x ∈ s), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { apply finset.ext.mpr, intro x, by_cases x ∈ s; simp *, finish }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : V →ₗ[K] V'} (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ V, g.comp f = linear_map.id := begin rcases exists_is_basis K V with ⟨B, hB⟩, have hB₀ : _ := hB.1.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ := hB₀.image_subtype (show disjoint (span K (range (λ i : B, i.val))) (linear_map.ker f), by simp [hf_inj]), have h₂ : range (λ (i : B), i.val) = B := subtype.range_val B, rwa h₂ at h₁ }, rcases exists_subset_is_basis this with ⟨C, BC, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hB, intros b, rw image_subset_iff at BC, simp, have := BC (subtype.mem b), rw mem_preimage at this, have : f (b.val) = (subtype.mk (f ↑b) (begin rw ←mem_preimage, exact BC (subtype.mem b) end) : C).val, by simp; unfold_coes, rw this, rw [constr_basis hC], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _, end lemma exists_right_inverse_linear_map_of_surjective {f : V →ₗ[K] V'} (hf_surj : f.range = ⊤) : ∃g:V' →ₗ V, f.comp g = linear_map.id := begin rcases exists_is_basis K V' with ⟨C, hC⟩, haveI : inhabited V := ⟨0⟩, use hC.constr (C.restrict (inv_fun f)), apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ hC, intros c, simp [constr_basis hC], exact right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) _ end set_option class.instance_max_depth 49 open submodule linear_map theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty ((p.quotient × p) ≃ₗ[K] V) := begin haveI := classical.dec_eq (quotient p), rcases exists_right_inverse_linear_map_of_surjective p.range_mkq with ⟨f, hf⟩, have mkf : ∀ x, submodule.quotient.mk (f x) = x := linear_map.ext_iff.1 hf, have fp : ∀ x, x - f (p.mkq x) ∈ p := λ x, (submodule.quotient.eq p).1 (mkf (p.mkq x)).symm, refine ⟨linear_equiv.of_linear (f.coprod p.subtype) (p.mkq.prod (cod_restrict p (linear_map.id - f.comp p.mkq) fp)) (by ext; simp) _⟩, ext ⟨⟨x⟩, y, hy⟩; simp, { apply (submodule.quotient.eq p).2, simpa [sub_eq_add_neg, add_left_comm] using sub_mem p hy (fp x) }, { refine subtype.coe_ext.2 _, simp [mkf, (submodule.quotient.mk_eq_zero p).2 hy] } end open fintype theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := begin apply exists.elim (exists_is_basis K V), intros b hb, haveI := classical.dec_pred (λ x, x ∈ b), use card b, exact module.card_fintype hb, end end vector_space namespace pi open set linear_map section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} variables [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] lemma linear_independent_std_basis (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, apply linear_independent.image (hs j), simp [ker_std_basis] }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr_le_supr (λ i, supr_le_supr (λ H, h₀ i)), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ, rw ←@set_of_mem_eq _ {j}, refl }, refine disjoint_mono h₁ h₂ (disjoint_std_basis_std_basis _ _ _ _ h₃), } end variable [fintype η] lemma is_basis_std_basis (s : Πj, ιs j → (Ms j)) (hs : ∀j, is_basis R (s j)) : is_basis R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (s ji.1 ji.2)) := begin split, { apply linear_independent_std_basis _ (assume i, (hs i).1) }, have h₁ : Union (λ j, set.range (std_basis R Ms j ∘ s j)) ⊆ range (λ (ji : Σ (j : η), ιs j), (std_basis R Ms (ji.fst)) (s (ji.fst) (ji.snd))), { apply Union_subset, intro i, apply range_comp_subset_range (λ x : ιs i, (⟨i, x⟩ : Σ (j : η), ιs j)) (λ (ji : Σ (j : η), ιs j), std_basis R Ms (ji.fst) (s (ji.fst) (ji.snd))) }, have h₂ : ∀ i, span R (range (std_basis R Ms i ∘ s i)) = range (std_basis R Ms i), { intro i, rw [set.range_comp, submodule.span_image, (assume i, (hs i).2), submodule.map_top] }, apply eq_top_mono, apply span_mono h₁, rw span_Union, simp only [h₂], apply supr_range_std_basis end section variables (R η) lemma is_basis_fun₀ : is_basis R (λ (ji : Σ (j : η), (λ _, unit) j), (std_basis R (λ (i : η), R) (ji.fst)) 1) := begin haveI := classical.dec_eq, apply @is_basis_std_basis R η (λi:η, unit) (λi:η, R) _ _ _ _ (λ _ _, (1 : R)) (assume i, @is_basis_singleton_one _ _ _ _), end lemma is_basis_fun : is_basis R (λ i, std_basis R (λi:η, R) i 1) := begin apply is_basis.comp (is_basis_fun₀ R η) (λ i, ⟨i, punit.star⟩), apply bijective_iff_has_inverse.2, use (λ x, x.1), simp [function.left_inverse, function.right_inverse], intros _ b, rw [unique.eq_default b, unique.eq_default punit.star] end end end module end pi
676004ed3478ba96c3e3a9c8dc6b521eefd2215e
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/continuous_function/algebra.lean
69ec92ac4f687ed72e9b062726b808b04e90b82d
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,070
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Nicolò Cavalleri -/ import topology.algebra.module import topology.continuous_function.basic import algebra.algebra.subalgebra /-! # Algebraic structures over continuous functions In this file we define instances of algebraic structures over continuous functions. Instances are present both in the case of the subtype of continuous functions and the type of continuous bundled functions. Both implementations have advantages and disadvantages, but many experienced people in Zulip have expressed a preference towards continuous bundled maps, so when there is no particular reason to use the subtype, continuous bundled functions should be used for the sake of uniformity. -/ local attribute [elab_simple] continuous.comp namespace continuous_functions variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {f g : {f : α → β | continuous f }} instance : has_coe_to_fun {f : α → β | continuous f} := ⟨_, subtype.val⟩ end continuous_functions namespace continuous_map variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] @[to_additive] instance has_mul [has_mul β] [has_continuous_mul β] : has_mul C(α, β) := ⟨λ f g, ⟨f * g, continuous_mul.comp (f.continuous.prod_mk g.continuous : _)⟩⟩ @[simp, norm_cast, to_additive] lemma mul_coe [has_mul β] [has_continuous_mul β] (f g : C(α, β)) : ((f * g : C(α, β)) : α → β) = (f : α → β) * (g : α → β) := rfl @[to_additive] instance [has_one β] : has_one C(α, β) := ⟨const (1 : β)⟩ @[simp, norm_cast, to_additive] lemma one_coe [has_one β] : ((1 : C(α, β)) : α → β) = (1 : α → β) := rfl @[simp, to_additive] lemma mul_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [semigroup γ] [has_continuous_mul γ] (f₁ f₂ : C(β, γ)) (g : C(α, β)) : (f₁ * f₂).comp g = f₁.comp g * f₂.comp g := by { ext, simp, } end continuous_map section group_structure /-! ### Group stucture In this section we show that continuous functions valued in a topological group inherit the structure of a group. -/ section subtype @[to_additive] instance continuous_submonoid (α : Type*) (β : Type*) [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : is_submonoid { f : α → β | continuous f } := { one_mem := @continuous_const _ _ _ _ 1, mul_mem := λ f g fc gc, continuous.comp has_continuous_mul.continuous_mul (continuous.prod_mk fc gc : _) } @[to_additive] instance continuous_subgroup (α : Type*) (β : Type*) [topological_space α] [topological_space β] [group β] [topological_group β] : is_subgroup { f : α → β | continuous f } := { inv_mem := λ f fc, continuous.comp (@topological_group.continuous_inv β _ _ _) fc, ..continuous_submonoid α β, }. @[to_additive] instance continuous_monoid {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid { f : α → β | continuous f } := subtype.monoid @[to_additive] instance continuous_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group { f : α → β | continuous f } := subtype.group @[to_additive] instance continuous_comm_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group { f : α → β | continuous f } := @subtype.comm_group _ _ _ (continuous_subgroup α β) -- infer_instance doesn't work?! end subtype section continuous_map @[to_additive] instance continuous_map_semigroup {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semigroup β] [has_continuous_mul β] : semigroup C(α, β) := { mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _, ..continuous_map.has_mul} @[to_additive] instance continuous_map_monoid {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : monoid C(α, β) := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, ..continuous_map_semigroup, ..continuous_map.has_one } /-- Coercion to a function as an `monoid_hom`. Similar to `monoid_hom.coe_fn`. -/ @[simps, to_additive "Coercion to a function as an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn`."] def coe_fn_monoid_hom {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] : C(α, β) →* (α → β) := { to_fun := coe_fn, map_one' := continuous_map.one_coe, map_mul' := continuous_map.mul_coe } @[simp, norm_cast] lemma continuous_map.pow_coe {α : Type*} {β : Type*} [topological_space α] [topological_space β] [monoid β] [has_continuous_mul β] (f : C(α, β)) (n : ℕ) : ((f^n : C(α, β)) : α → β) = (f : α → β)^n := begin ext x, induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end @[simp] lemma continuous_map.pow_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [monoid γ] [has_continuous_mul γ] (f : C(β, γ)) (n : ℕ) (g : C(α, β)) : (f^n).comp g = (f.comp g)^n := begin induction n with n ih, { ext, simp, }, { simp [pow_succ, ih], } end @[to_additive] instance continuous_map_comm_monoid {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_monoid β] [has_continuous_mul β] : comm_monoid C(α, β) := { one_mul := λ a, by ext; exact one_mul _, mul_one := λ a, by ext; exact mul_one _, mul_comm := λ a b, by ext; exact mul_comm _ _, ..continuous_map_semigroup, ..continuous_map.has_one } open_locale big_operators @[simp, to_additive] lemma continuous_map.coe_prod {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) : ⇑(∏ i in s, f i) = (∏ i in s, (f i : α → β)) := (@coe_fn_monoid_hom α β _ _ _ _).map_prod f s @[to_additive] lemma continuous_map.prod_apply {α : Type*} {β : Type*} [comm_monoid β] [topological_space α] [topological_space β] [has_continuous_mul β] {ι : Type*} (s : finset ι) (f : ι → C(α, β)) (a : α) : (∏ i in s, f i) a = (∏ i in s, f i a) := by simp @[to_additive] instance continuous_map_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] : group C(α, β) := { inv := λ f, ⟨λ x, (f x)⁻¹, continuous_inv.comp f.continuous⟩, mul_left_inv := λ a, by ext; exact mul_left_inv _, ..continuous_map_monoid } @[simp, norm_cast, to_additive] lemma continuous_map.inv_coe {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] (f : C(α, β)) : ((f⁻¹ : C(α, β)) : α → β) = (f⁻¹ : α → β) := rfl @[simp, norm_cast, to_additive] lemma continuous_map.div_coe {α : Type*} {β : Type*} [topological_space α] [topological_space β] [group β] [topological_group β] (f g : C(α, β)) : ((f / g : C(α, β)) : α → β) = (f : α → β) / (g : α → β) := by { simp only [div_eq_mul_inv], refl, } @[simp, to_additive] lemma continuous_map.inv_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [group γ] [topological_group γ] (f : C(β, γ)) (g : C(α, β)) : (f⁻¹).comp g = (f.comp g)⁻¹ := by { ext, simp, } @[simp, to_additive] lemma continuous_map.div_comp {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] [group γ] [topological_group γ] (f g : C(β, γ)) (h : C(α, β)) : (f / g).comp h = (f.comp h) / (g.comp h) := by { ext, simp, } @[to_additive] instance continuous_map_comm_group {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_group β] [topological_group β] : comm_group C(α, β) := { ..continuous_map_group, ..continuous_map_comm_monoid } end continuous_map end group_structure section ring_structure /-! ### Ring stucture In this section we show that continuous functions valued in a topological ring `R` inherit the structure of a ring. -/ section subtype instance continuous_subring (α : Type*) (R : Type*) [topological_space α] [topological_space R] [ring R] [topological_ring R] : is_subring { f : α → R | continuous f } := { ..continuous_add_subgroup α R, ..continuous_submonoid α R }. instance continuous_ring {α : Type*} {R : Type*} [topological_space α] [topological_space R] [ring R] [topological_ring R] : ring { f : α → R | continuous f } := @subtype.ring _ _ _ (continuous_subring α R) -- infer_instance doesn't work?! instance continuous_comm_ring {α : Type*} {R : Type*} [topological_space α] [topological_space R] [comm_ring R] [topological_ring R] : comm_ring { f : α → R | continuous f } := @subtype.comm_ring _ _ _ (continuous_subring α R) -- infer_instance doesn't work?! end subtype section continuous_map instance continuous_map_semiring {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semiring β] [topological_semiring β] : semiring C(α, β) := { left_distrib := λ a b c, by ext; exact left_distrib _ _ _, right_distrib := λ a b c, by ext; exact right_distrib _ _ _, zero_mul := λ a, by ext; exact zero_mul _, mul_zero := λ a, by ext; exact mul_zero _, ..continuous_map_add_comm_monoid, ..continuous_map_monoid } instance continuous_map_ring {α : Type*} {β : Type*} [topological_space α] [topological_space β] [ring β] [topological_ring β] : ring C(α, β) := { ..continuous_map_semiring, ..continuous_map_add_comm_group, } instance continuous_map_comm_ring {α : Type*} {β : Type*} [topological_space α] [topological_space β] [comm_ring β] [topological_ring β] : comm_ring C(α, β) := { ..continuous_map_semiring, ..continuous_map_add_comm_group, ..continuous_map_comm_monoid,} end continuous_map end ring_structure local attribute [ext] subtype.eq section semimodule_structure /-! ### Semiodule stucture In this section we show that continuous functions valued in a topological semimodule `M` over a topological semiring `R` inherit the structure of a semimodule. -/ section subtype variables {α : Type*} [topological_space α] variables {R : Type*} [semiring R] [topological_space R] variables {M : Type*} [topological_space M] [add_comm_group M] variables [semimodule R M] [has_continuous_smul R M] instance continuous_has_scalar : has_scalar R { f : α → M | continuous f } := ⟨λ r f, ⟨r • f, f.property.const_smul r⟩⟩ @[simp, norm_cast] lemma continuous_functions.smul_coe (f : { f : α → M | continuous f }) (r : R) : ⇑(r • f) = r • f := rfl instance continuous_semimodule [topological_add_group M] : semimodule R { f : α → M | continuous f } := semimodule.of_core $ { smul := (•), smul_add := λ c f g, by ext x; exact smul_add c (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul c₁ c₂ (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul c₁ c₂ (f x), one_smul := λ f, by ext x; exact one_smul R (f x) } end subtype section continuous_map variables {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] instance continuous_map_has_scalar [semimodule R M] [has_continuous_smul R M] : has_scalar R C(α, M) := ⟨λ r f, ⟨r • f, f.continuous.const_smul r⟩⟩ @[simp, norm_cast] lemma continuous_map.smul_coe [semimodule R M] [has_continuous_smul R M] (c : R) (f : C(α, M)) : ⇑(c • f) = c • f := rfl lemma continuous_map.smul_apply [semimodule R M] [has_continuous_smul R M] (c : R) (f : C(α, M)) (a : α) : (c • f) a = c • (f a) := by simp @[simp] lemma continuous_map.smul_comp {α : Type*} {β : Type*} [topological_space α] [topological_space β] [semimodule R M] [has_continuous_smul R M] (r : R) (f : C(β, M)) (g : C(α, β)) : (r • f).comp g = r • (f.comp g) := by { ext, simp, } variables [has_continuous_add M] [semimodule R M] [has_continuous_smul R M] instance continuous_map_semimodule : semimodule R C(α, M) := { smul := (•), smul_add := λ c f g, by { ext, exact smul_add c (f x) (g x) }, add_smul := λ c₁ c₂ f, by { ext, exact add_smul c₁ c₂ (f x) }, mul_smul := λ c₁ c₂ f, by { ext, exact mul_smul c₁ c₂ (f x) }, one_smul := λ f, by { ext, exact one_smul R (f x) }, zero_smul := λ f, by { ext, exact zero_smul _ _ }, smul_zero := λ r, by { ext, exact smul_zero _ } } end continuous_map end semimodule_structure section algebra_structure /-! ### Algebra structure In this section we show that continuous functions valued in a topological algebra `A` over a ring `R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra is obtained by requiring that `A` be both a `has_continuous_smul` and a `topological_semiring` (by now we require `topological_ring`: see TODO below).-/ section subtype variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [ring A] [algebra R A] [topological_ring A] /-- Continuous constant functions as a `ring_hom`. -/ def continuous.C : R →+* { f : α → A | continuous f } := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } variables [topological_space R] [has_continuous_smul R A] instance : algebra R { f : α → A | continuous f } := { to_ring_hom := continuous.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, ..continuous_semimodule, ..continuous_ring } /- TODO: We are assuming `A` to be a ring and not a semiring just because there is not yet an instance of semiring. In turn, we do not want to define yet an instance of semiring because there is no `is_subsemiring` but only `subsemiring`, and it will make sense to change this when the whole file will have no more `is_subobject`s but only `subobject`s. It does not make sense to change it yet in this direction as `subring` does not exist yet, so everything is being blocked by `subring`: afterwards everything will need to be updated to the new conventions of Mathlib. Then the instance of `topological_ring` can also be removed, as it is below for `continuous_map`. -/ end subtype section continuous_map variables {α : Type*} [topological_space α] {R : Type*} [comm_semiring R] {A : Type*} [topological_space A] [semiring A] [algebra R A] [topological_semiring A] /-- Continuous constant functions as a `ring_hom`. -/ def continuous_map.C : R →+* C(α, A) := { to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩, map_one' := by ext x; exact (algebra_map R A).map_one, map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _, map_zero' := by ext x; exact (algebra_map R A).map_zero, map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ } @[simp] lemma continuous_map.C_apply (r : R) (a : α) : continuous_map.C r a = algebra_map R A r := rfl variables [topological_space R] [has_continuous_smul R A] instance continuous_map_algebra : algebra R C(α, A) := { to_ring_hom := continuous_map.C, commutes' := λ c f, by ext x; exact algebra.commutes' _ _, smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _, ..continuous_map_semiring } /-- A version of `separates_points` for subalgebras of the continuous functions, used for stating the Stone-Weierstrass theorem. -/ abbreviation subalgebra.separates_points (s : subalgebra R C(α, A)) : Prop := separates_points ((λ f : C(α, A), (f : α → A)) '' (s : set C(α, A))) lemma subalgebra.separates_points_monotone : monotone (λ s : subalgebra R C(α, A), s.separates_points) := λ s s' r h x y n, begin obtain ⟨f, m, w⟩ := h n, rcases m with ⟨f, ⟨m, rfl⟩⟩, exact ⟨_, ⟨f, ⟨r m, rfl⟩⟩, w⟩, end @[simp] lemma algebra_map_apply (k : R) (a : α) : algebra_map R C(α, A) k a = k • 1 := by { rw algebra.algebra_map_eq_smul_one, refl, } variables {𝕜 : Type*} [field 𝕜] [topological_space 𝕜] [topological_ring 𝕜] /-- Working in continuous functions into a topological field, a subalgebra of functions that separates points also separates points strongly. By the hypothesis, we can find a function `f` so `f x ≠ f y`. By an affine transformation in the field we can arrange so that `f x = a` and `f x = b`. -/ lemma subalgebra.separates_points.strongly {s : subalgebra 𝕜 C(α, 𝕜)} (h : s.separates_points) : separates_points_strongly ((λ f : C(α, 𝕜), (f : α → 𝕜)) '' (s : set C(α, 𝕜))) := λ x y n, begin obtain ⟨f, ⟨f, ⟨m, rfl⟩⟩, w⟩ := h n, replace w : f x - f y ≠ 0 := sub_ne_zero_of_ne w, intros a b, let f' := ((b - a) * (f x - f y)⁻¹) • (continuous_map.C (f x) - f) + continuous_map.C a, refine ⟨f', _, _, _⟩, { simp only [set.mem_image, coe_coe], refine ⟨f', _, rfl⟩, simp only [f', set_like.mem_coe, subalgebra.mem_to_submodule], -- TODO should there be a tactic for this? -- We could add an attribute `@[subobject_mem]`, and a tactic -- ``def subobject_mem := `[solve_by_elim with subobject_mem { max_depth := 10 }]`` solve_by_elim [subalgebra.add_mem, subalgebra.smul_mem, subalgebra.sub_mem, subalgebra.algebra_map_mem] { max_depth := 6 }, }, { simp [f'], }, { simp [f', inv_mul_cancel_right' w], }, end end continuous_map end algebra_structure section module_over_continuous_functions /-! ### Structure as module over scalar functions If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M` is naturally a module over the ring of continuous functions from `α` to `M`. -/ section subtype instance continuous_has_scalar' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] [semimodule R M] [has_continuous_smul R M] : has_scalar { f : α → R | continuous f } { f : α → M | continuous f } := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance continuous_module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_group M] [topological_add_group M] [module R M] [has_continuous_smul R M] : module { f : α → R | continuous f } { f : α → M | continuous f } := semimodule.of_core $ { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x) } end subtype section continuous_map instance continuous_map_has_scalar' {α : Type*} [topological_space α] {R : Type*} [semiring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_monoid M] [semimodule R M] [has_continuous_smul R M] : has_scalar C(α, R) C(α, M) := ⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩ instance continuous_map_module' {α : Type*} [topological_space α] (R : Type*) [ring R] [topological_space R] [topological_ring R] (M : Type*) [topological_space M] [add_comm_monoid M] [has_continuous_add M] [semimodule R M] [has_continuous_smul R M] : semimodule C(α, R) C(α, M) := { smul := (•), smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x), add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x), mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x), one_smul := λ f, by ext x; exact one_smul R (f x), zero_smul := λ f, by ext x; exact zero_smul _ _, smul_zero := λ r, by ext x; exact smul_zero _, } end continuous_map end module_over_continuous_functions /-! We now provide formulas for `f ⊓ g` and `f ⊔ g`, where `f g : C(α, β)`, in terms of `continuous_map.abs`. -/ section variables {R : Type*} [linear_ordered_field R] -- TODO: -- This lemma (and the next) could go all the way back in `algebra.ordered_field`, -- except that it is tedious to prove without tactics. -- Rather than stranding it at some intermediate location, -- it's here, immediately prior to the point of use. lemma min_eq_half_add_sub_abs_sub {x y : R} : min x y = 2⁻¹ * (x + y - abs (x - y)) := begin dsimp [min, max, abs], simp only [neg_le_self_iff, if_congr, sub_nonneg, neg_sub], split_ifs; ring_nf; linarith, end lemma max_eq_half_add_add_abs_sub {x y : R} : max x y = 2⁻¹ * (x + y + abs (x - y)) := begin dsimp [min, max, abs], simp only [neg_le_self_iff, if_congr, sub_nonneg, neg_sub], split_ifs; ring_nf; linarith, end end namespace continuous_map section lattice variables {α : Type*} [topological_space α] variables {β : Type*} [linear_ordered_field β] [topological_space β] [order_topology β] [topological_ring β] lemma inf_eq (f g : C(α, β)) : f ⊓ g = (2⁻¹ : β) • (f + g - (f - g).abs) := ext (λ x, by simpa using min_eq_half_add_sub_abs_sub) -- Not sure why this is grosser than `inf_eq`: lemma sup_eq (f g : C(α, β)) : f ⊔ g = (2⁻¹ : β) • (f + g + (f - g).abs) := ext (λ x, by simpa [mul_add] using @max_eq_half_add_add_abs_sub _ _ (f x) (g x)) end lattice end continuous_map
01cd4d1de269b4b6aacdbd2f73c04affff0d691e
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/unit_interval.lean
7a858b6b679e065fd0b620b4bbfab4621b9de19d
[ "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
6,377
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison -/ import topology.instances.real import topology.algebra.field import data.set.intervals.proj_Icc /-! # The unit interval, as a topological space Use `open_locale unit_interval` to turn on the notation `I := set.Icc (0 : ℝ) (1 : ℝ)`. We provide basic instances, as well as a custom tactic for discharging `0 ≤ ↑x`, `0 ≤ 1 - ↑x`, `↑x ≤ 1`, and `1 - ↑x ≤ 1` when `x : I`. -/ noncomputable theory open_locale classical topological_space filter open set int /-! ### The unit interval -/ /-- The unit interval `[0,1]` in ℝ. -/ abbreviation unit_interval : set ℝ := set.Icc 0 1 localized "notation `I` := unit_interval" in unit_interval namespace unit_interval lemma zero_mem : (0 : ℝ) ∈ I := ⟨le_rfl, zero_le_one⟩ lemma one_mem : (1 : ℝ) ∈ I := ⟨zero_le_one, le_rfl⟩ lemma mul_mem {x y : ℝ} (hx : x ∈ I) (hy : y ∈ I) : x * y ∈ I := ⟨mul_nonneg hx.1 hy.1, (mul_le_mul hx.2 hy.2 hy.1 zero_le_one).trans_eq $ one_mul 1⟩ lemma div_mem {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) (hxy : x ≤ y) : x / y ∈ I := ⟨div_nonneg hx hy, div_le_one_of_le hxy hy⟩ lemma fract_mem (x : ℝ) : fract x ∈ I := ⟨fract_nonneg _, (fract_lt_one _).le⟩ lemma mem_iff_one_sub_mem {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance has_zero : has_zero I := ⟨⟨0, zero_mem⟩⟩ @[simp, norm_cast] lemma coe_zero : ((0 : I) : ℝ) = 0 := rfl @[simp] lemma mk_zero (h : (0 : ℝ) ∈ Icc (0 : ℝ) 1) : (⟨0, h⟩ : I) = 0 := rfl @[simp, norm_cast] lemma coe_eq_zero {x : I} : (x : ℝ) = 0 ↔ x = 0 := by { symmetry, exact subtype.ext_iff } instance has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_one : ((1 : I) : ℝ) = 1 := rfl lemma coe_ne_zero {x : I} : (x : ℝ) ≠ 0 ↔ x ≠ 0 := not_iff_not.mpr coe_eq_zero @[simp] lemma mk_one (h : (1 : ℝ) ∈ Icc (0 : ℝ) 1) : (⟨1, h⟩ : I) = 1 := rfl @[simp, norm_cast] lemma coe_eq_one {x : I} : (x : ℝ) = 1 ↔ x = 1 := by { symmetry, exact subtype.ext_iff } lemma coe_ne_one {x : I} : (x : ℝ) ≠ 1 ↔ x ≠ 1 := not_iff_not.mpr coe_eq_one instance : nonempty I := ⟨0⟩ instance : has_mul I := ⟨λ x y, ⟨x * y, mul_mem x.2 y.2⟩⟩ @[simp, norm_cast] lemma coe_mul {x y : I} : ((x * y : I) : ℝ) = x * y := rfl -- todo: we could set up a `linear_ordered_comm_monoid_with_zero I` instance lemma mul_le_left {x y : I} : x * y ≤ x := subtype.coe_le_coe.mp $ (mul_le_mul_of_nonneg_left y.2.2 x.2.1).trans_eq $ mul_one x lemma mul_le_right {x y : I} : x * y ≤ y := subtype.coe_le_coe.mp $ (mul_le_mul_of_nonneg_right x.2.2 y.2.1).trans_eq $ one_mul y /-- Unit interval central symmetry. -/ def symm : I → I := λ t, ⟨1 - t, mem_iff_one_sub_mem.mp t.prop⟩ localized "notation `σ` := unit_interval.symm" in unit_interval @[simp] lemma symm_zero : σ 0 = 1 := subtype.ext $ by simp [symm] @[simp] lemma symm_one : σ 1 = 0 := subtype.ext $ by simp [symm] @[simp] lemma symm_symm (x : I) : σ (σ x) = x := subtype.ext $ by simp [symm] @[simp] lemma coe_symm_eq (x : I) : (σ x : ℝ) = 1 - x := rfl @[continuity] lemma continuous_symm : continuous σ := by continuity! instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ /-- Verify there is an instance for `compact_space I`. -/ example : compact_space I := by apply_instance lemma nonneg (x : I) : 0 ≤ (x : ℝ) := x.2.1 lemma one_minus_nonneg (x : I) : 0 ≤ 1 - (x : ℝ) := by simpa using x.2.2 lemma le_one (x : I) : (x : ℝ) ≤ 1 := x.2.2 lemma one_minus_le_one (x : I) : 1 - (x : ℝ) ≤ 1 := by simpa using x.2.1 /-- like `unit_interval.nonneg`, but with the inequality in `I`. -/ lemma nonneg' {t : I} : 0 ≤ t := t.2.1 /-- like `unit_interval.le_one`, but with the inequality in `I`. -/ lemma le_one' {t : I} : t ≤ 1 := t.2.2 lemma mul_pos_mem_iff {a t : ℝ} (ha : 0 < a) : a * t ∈ I ↔ t ∈ set.Icc (0 : ℝ) (1/a) := begin split; rintros ⟨h₁, h₂⟩; split, { exact nonneg_of_mul_nonneg_left h₁ ha }, { rwa [le_div_iff ha, mul_comm] }, { exact mul_nonneg ha.le h₁ }, { rwa [le_div_iff ha, mul_comm] at h₂ } end lemma two_mul_sub_one_mem_iff {t : ℝ} : 2 * t - 1 ∈ I ↔ t ∈ set.Icc (1/2 : ℝ) 1 := by split; rintros ⟨h₁, h₂⟩; split; linarith end unit_interval @[simp] lemma proj_Icc_eq_zero {x : ℝ} : proj_Icc (0 : ℝ) 1 zero_le_one x = 0 ↔ x ≤ 0 := proj_Icc_eq_left zero_lt_one @[simp] lemma proj_Icc_eq_one {x : ℝ} : proj_Icc (0 : ℝ) 1 zero_le_one x = 1 ↔ 1 ≤ x := proj_Icc_eq_right zero_lt_one namespace tactic.interactive /-- A tactic that solves `0 ≤ ↑x`, `0 ≤ 1 - ↑x`, `↑x ≤ 1`, and `1 - ↑x ≤ 1` for `x : I`. -/ meta def unit_interval : tactic unit := `[apply unit_interval.nonneg] <|> `[apply unit_interval.one_minus_nonneg] <|> `[apply unit_interval.le_one] <|> `[apply unit_interval.one_minus_le_one] end tactic.interactive section variables {𝕜 : Type*} [linear_ordered_field 𝕜] [topological_space 𝕜] [topological_ring 𝕜] /-- The image of `[0,1]` under the homeomorphism `λ x, a * x + b` is `[b, a+b]`. -/ -- We only need the ordering on `𝕜` here to avoid talking about flipping the interval over. -- At the end of the day I only care about `ℝ`, so I'm hesitant to put work into generalizing. lemma affine_homeomorph_image_I (a b : 𝕜) (h : 0 < a) : affine_homeomorph a b h.ne.symm '' set.Icc 0 1 = set.Icc b (a + b) := by simp [h] /-- The affine homeomorphism from a nontrivial interval `[a,b]` to `[0,1]`. -/ def Icc_homeo_I (a b : 𝕜) (h : a < b) : set.Icc a b ≃ₜ set.Icc (0 : 𝕜) (1 : 𝕜) := begin let e := homeomorph.image (affine_homeomorph (b-a) a (sub_pos.mpr h).ne.symm) (set.Icc 0 1), refine (e.trans _).symm, apply homeomorph.set_congr, simp [sub_pos.mpr h], end @[simp] lemma Icc_homeo_I_apply_coe (a b : 𝕜) (h : a < b) (x : set.Icc a b) : ((Icc_homeo_I a b h) x : 𝕜) = (x - a) / (b - a) := rfl @[simp] lemma Icc_homeo_I_symm_apply_coe (a b : 𝕜) (h : a < b) (x : set.Icc (0 : 𝕜) (1 : 𝕜)) : ((Icc_homeo_I a b h).symm x : 𝕜) = (b - a) * x + a := rfl end
8fa8dd90989928fbb33b88860f77ec226ae00405
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/format_macro.lean
25e33ba3f8e04c5c3d03b52d6573fdb6e4bca137
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
294
lean
#eval format!"hi" #eval format! "hi" #eval format!"hi\nhi" #eval format!"{1}+{1}" #eval format!"{1+1}" #eval format!"{{{1+1}}" #eval format!"a{1}" #eval format!"{1}a" #eval format!"}" #check λ α, format!"{α}" #eval format!"{" #eval format!"{}" #eval format!"{1+}" #eval sformat!"a{'b'}c"
c477dce9c87074edcc5a9a972446149e72d103b1
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/normed_space/banach.lean
fb75643187b779489e8e64f48a4941ad07447230
[ "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
21,402
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.baire import analysis.normed_space.operator_norm import analysis.normed_space.affine_isometry /-! # Banach open mapping theorem This file contains the Banach open mapping theorem, i.e., the fact that a bijective bounded linear map between Banach spaces has a bounded inverse. -/ open function metric set filter finset open_locale classical topological_space big_operators nnreal variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E →L[𝕜] F) include 𝕜 namespace continuous_linear_map /-- A (possibly nonlinear) right inverse to a continuous linear map, which doesn't have to be linear itself but which satisfies a bound `∥inverse x∥ ≤ C * ∥x∥`. A surjective continuous linear map doesn't always have a continuous linear right inverse, but it always has a nonlinear inverse in this sense, by Banach's open mapping theorem. -/ structure nonlinear_right_inverse := (to_fun : F → E) (nnnorm : ℝ≥0) (bound' : ∀ y, ∥to_fun y∥ ≤ nnnorm * ∥y∥) (right_inv' : ∀ y, f (to_fun y) = y) instance : has_coe_to_fun (nonlinear_right_inverse f) (λ _, F → E) := ⟨λ fsymm, fsymm.to_fun⟩ @[simp] lemma nonlinear_right_inverse.right_inv {f : E →L[𝕜] F} (fsymm : nonlinear_right_inverse f) (y : F) : f (fsymm y) = y := fsymm.right_inv' y lemma nonlinear_right_inverse.bound {f : E →L[𝕜] F} (fsymm : nonlinear_right_inverse f) (y : F) : ∥fsymm y∥ ≤ fsymm.nnnorm * ∥y∥ := fsymm.bound' y end continuous_linear_map /-- Given a continuous linear equivalence, the inverse is in particular an instance of `nonlinear_right_inverse` (which turns out to be linear). -/ noncomputable def continuous_linear_equiv.to_nonlinear_right_inverse (f : E ≃L[𝕜] F) : continuous_linear_map.nonlinear_right_inverse (f : E →L[𝕜] F) := { to_fun := f.inv_fun, nnnorm := ∥(f.symm : F →L[𝕜] E)∥₊, bound' := λ y, continuous_linear_map.le_op_norm (f.symm : F →L[𝕜] E) _, right_inv' := f.apply_symm_apply } noncomputable instance (f : E ≃L[𝕜] F) : inhabited (continuous_linear_map.nonlinear_right_inverse (f : E →L[𝕜] F)) := ⟨f.to_nonlinear_right_inverse⟩ /-! ### Proof of the Banach open mapping theorem -/ variable [complete_space F] namespace continuous_linear_map /-- First step of the proof of the Banach open mapping theorem (using completeness of `F`): by Baire's theorem, there exists a ball in `E` whose image closure has nonempty interior. Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by images of elements of norm at most `C * ∥y∥`. For further use, we will only need such an element whose image is within distance `∥y∥/2` of `y`, to apply an iterative process. -/ lemma exists_approx_preimage_norm_le (surj : surjective f) : ∃C ≥ 0, ∀y, ∃x, dist (f x) y ≤ 1/2 * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥ := begin have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ, { refine subset.antisymm (subset_univ _) (λy hy, _), rcases surj y with ⟨x, hx⟩, rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩, refine mem_Union.2 ⟨n, subset_closure _⟩, refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩, rwa [mem_ball, dist_eq_norm, sub_zero] }, have : ∃ (n : ℕ) x, x ∈ interior (closure (f '' (ball 0 n))) := nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A, simp only [mem_interior_iff_mem_nhds, metric.mem_nhds_iff] at this, rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩, { refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _, exacts [inv_nonneg.2 (div_nonneg (le_of_lt εpos) (by norm_num)), n.cast_nonneg] }, { by_cases hy : y = 0, { use 0, simp [hy] }, { rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydlt, leyd, dinv⟩, let δ := ∥d∥ * ∥y∥/4, have δpos : 0 < δ := div_pos (mul_pos (norm_pos_iff.2 hd) (norm_pos_iff.2 hy)) (by norm_num), have : a + d • y ∈ ball a ε, by simp [dist_eq_norm, lt_of_le_of_lt ydlt.le (half_lt_self εpos)], rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩, rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩, rw ← xz₁ at h₁, rw [mem_ball, dist_eq_norm, sub_zero] at hx₁, have : a ∈ ball a ε, by { simp, exact εpos }, rcases metric.mem_closure_iff.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩, rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩, rw ← xz₂ at h₂, rw [mem_ball, dist_eq_norm, sub_zero] at hx₂, let x := x₁ - x₂, have I : ∥f x - d • y∥ ≤ 2 * δ := calc ∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ : by { congr' 1, simp only [x, f.map_sub], abel } ... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ : norm_sub_le _ _ ... ≤ δ + δ : begin apply add_le_add, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ }, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ } end ... = 2 * δ : (two_mul _).symm, have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc ∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ : by rwa [f.map_smul _, inv_mul_cancel, one_smul] ... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub] ... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, norm_inv] ... ≤ ∥d∥⁻¹ * (2 * δ) : begin apply mul_le_mul_of_nonneg_left I, rw inv_nonneg, exact norm_nonneg _ end ... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring } ... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] } ... = (1/2) * ∥y∥ : by ring, rw ← dist_eq_norm at J, have K : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc ∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, norm_inv] ... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin refine mul_le_mul dinv _ (norm_nonneg _) _, { exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) }, { apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _), exact inv_nonneg.2 (le_of_lt (half_pos εpos)) } end ... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring, exact ⟨d⁻¹ • x, J, K⟩ } }, end variable [complete_space E] /-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then any point has a preimage with controlled norm. -/ theorem exists_preimage_norm_le (surj : surjective f) : ∃C > 0, ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ := begin obtain ⟨C, C0, hC⟩ := exists_approx_preimage_norm_le f surj, /- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`, leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a preimage of `y`. This uses completeness of `E`. -/ choose g hg using hC, let h := λy, y - f (g y), have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥, { assume y, rw [← dist_eq_norm, dist_comm], exact (hg y).1 }, refine ⟨2 * C + 1, by linarith, λy, _⟩, have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥, { assume n, induction n with n IH, { simp only [one_div, nat.nat_zero_eq_zero, one_mul, iterate_zero_apply, pow_zero] }, { rw [iterate_succ'], apply le_trans (hle _) _, rw [pow_succ, mul_assoc], apply mul_le_mul_of_nonneg_left IH, norm_num } }, let u := λn, g((h^[n]) y), have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥), { assume n, apply le_trans (hg _).2 _, calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0 ... = (1 / 2) ^ n * (C * ∥y∥) : by ring }, have sNu : summable (λn, ∥u n∥), { refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _, exact summable.mul_right _ (summable_geometric_of_lt_1 (by norm_num) (by norm_num)) }, have su : summable u := summable_of_summable_norm sNu, let x := tsum u, have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc ∥x∥ ≤ ∑'n, ∥u n∥ : norm_tsum_le_tsum_norm sNu ... ≤ ∑'n, (1/2)^n * (C * ∥y∥) : tsum_le_tsum ule sNu (summable.mul_right _ summable_geometric_two) ... = (∑'n, (1/2)^n) * (C * ∥y∥) : tsum_mul_right ... = 2 * C * ∥y∥ : by rw [tsum_geometric_two, mul_assoc] ... ≤ 2 * C * ∥y∥ + ∥y∥ : le_add_of_nonneg_right (norm_nonneg y) ... = (2 * C + 1) * ∥y∥ : by ring, have fsumeq : ∀n:ℕ, f (∑ i in finset.range n, u i) = y - (h^[n]) y, { assume n, induction n with n IH, { simp [f.map_zero] }, { rw [sum_range_succ, f.map_add, IH, iterate_succ', sub_add] } }, have : tendsto (λn, ∑ i in finset.range n, u i) at_top (𝓝 x) := su.has_sum.tendsto_sum_nat, have L₁ : tendsto (λn, f (∑ i in finset.range n, u i)) at_top (𝓝 (f x)) := (f.continuous.tendsto _).comp this, simp only [fsumeq] at L₁, have L₂ : tendsto (λn, y - (h^[n]) y) at_top (𝓝 (y - 0)), { refine tendsto_const_nhds.sub _, rw tendsto_iff_norm_tendsto_zero, simp only [sub_zero], refine squeeze_zero (λ_, norm_nonneg _) hnle _, rw [← zero_mul ∥y∥], refine (tendsto_pow_at_top_nhds_0_of_lt_1 _ _).mul tendsto_const_nhds; norm_num }, have feq : f x = y - 0 := tendsto_nhds_unique L₁ L₂, rw sub_zero at feq, exact ⟨x, feq, x_ineq⟩ end /-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/ protected theorem is_open_map (surj : surjective f) : is_open_map f := begin assume s hs, rcases exists_preimage_norm_le f surj with ⟨C, Cpos, hC⟩, refine is_open_iff.2 (λy yfs, _), rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩, rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩, refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩, rcases hC (z-y) with ⟨w, wim, wnorm⟩, have : f (x + w) = z, by { rw [f.map_add, wim, fxy, add_sub_cancel'_right] }, rw ← this, have : x + w ∈ ball x ε := calc dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp } ... ≤ C * ∥z - y∥ : wnorm ... < C * (ε/C) : begin apply mul_lt_mul_of_pos_left _ Cpos, rwa [mem_ball, dist_eq_norm] at hz, end ... = ε : mul_div_cancel' _ (ne_of_gt Cpos), exact set.mem_image_of_mem _ (hε this) end protected theorem quotient_map (surj : surjective f) : quotient_map f := (f.is_open_map surj).to_quotient_map f.continuous surj lemma _root_.affine_map.is_open_map {P Q : Type*} [metric_space P] [normed_add_torsor E P] [metric_space Q] [normed_add_torsor F Q] (f : P →ᵃ[𝕜] Q) (hf : continuous f) (surj : surjective f) : is_open_map f := affine_map.is_open_map_linear_iff.mp $ continuous_linear_map.is_open_map { cont := affine_map.continuous_linear_iff.mpr hf, .. f.linear } (f.surjective_iff_linear_surjective.mpr surj) /-! ### Applications of the Banach open mapping theorem -/ lemma interior_preimage (hsurj : surjective f) (s : set F) : interior (f ⁻¹' s) = f ⁻¹' (interior s) := ((f.is_open_map hsurj).preimage_interior_eq_interior_preimage f.continuous s).symm lemma closure_preimage (hsurj : surjective f) (s : set F) : closure (f ⁻¹' s) = f ⁻¹' (closure s) := ((f.is_open_map hsurj).preimage_closure_eq_closure_preimage f.continuous s).symm lemma frontier_preimage (hsurj : surjective f) (s : set F) : frontier (f ⁻¹' s) = f ⁻¹' (frontier s) := ((f.is_open_map hsurj).preimage_frontier_eq_frontier_preimage f.continuous s).symm lemma exists_nonlinear_right_inverse_of_surjective (f : E →L[𝕜] F) (hsurj : f.range = ⊤) : ∃ (fsymm : nonlinear_right_inverse f), 0 < fsymm.nnnorm := begin choose C hC fsymm h using exists_preimage_norm_le _ (linear_map.range_eq_top.mp hsurj), use { to_fun := fsymm, nnnorm := ⟨C, hC.lt.le⟩, bound' := λ y, (h y).2, right_inv' := λ y, (h y).1 }, exact hC end /-- A surjective continuous linear map between Banach spaces admits a (possibly nonlinear) controlled right inverse. In general, it is not possible to ensure that such a right inverse is linear (take for instance the map from `E` to `E/F` where `F` is a closed subspace of `E` without a closed complement. Then it doesn't have a continuous linear right inverse.) -/ @[irreducible] noncomputable def nonlinear_right_inverse_of_surjective (f : E →L[𝕜] F) (hsurj : f.range = ⊤) : nonlinear_right_inverse f := classical.some (exists_nonlinear_right_inverse_of_surjective f hsurj) lemma nonlinear_right_inverse_of_surjective_nnnorm_pos (f : E →L[𝕜] F) (hsurj : f.range = ⊤) : 0 < (nonlinear_right_inverse_of_surjective f hsurj).nnnorm := begin rw nonlinear_right_inverse_of_surjective, exact classical.some_spec (exists_nonlinear_right_inverse_of_surjective f hsurj) end end continuous_linear_map namespace linear_equiv variables [complete_space E] /-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/ @[continuity] theorem continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) : continuous e.symm := begin rw continuous_def, intros s hs, rw [← e.image_eq_preimage], rw [← e.coe_coe] at h ⊢, exact continuous_linear_map.is_open_map ⟨↑e, h⟩ e.surjective s hs end /-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the inverse map is also continuous. -/ def to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) : E ≃L[𝕜] F := { continuous_to_fun := h, continuous_inv_fun := e.continuous_symm h, ..e } @[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) : ⇑(e.to_continuous_linear_equiv_of_continuous h) = e := rfl @[simp] lemma coe_fn_to_continuous_linear_equiv_of_continuous_symm (e : E ≃ₗ[𝕜] F) (h : continuous e) : ⇑(e.to_continuous_linear_equiv_of_continuous h).symm = e.symm := rfl end linear_equiv namespace continuous_linear_equiv variables [complete_space E] /-- Convert a bijective continuous linear map `f : E →L[𝕜] F` from a Banach space to a normed space to a continuous linear equivalence. -/ noncomputable def of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) : E ≃L[𝕜] F := (linear_equiv.of_bijective ↑f (linear_map.ker_eq_bot.mp hinj) (linear_map.range_eq_top.mp hsurj)) .to_continuous_linear_equiv_of_continuous f.continuous @[simp] lemma coe_fn_of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) : ⇑(of_bijective f hinj hsurj) = f := rfl lemma coe_of_bijective (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) : ↑(of_bijective f hinj hsurj) = f := by { ext, refl } @[simp] lemma of_bijective_symm_apply_apply (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) (x : E) : (of_bijective f hinj hsurj).symm (f x) = x := (of_bijective f hinj hsurj).symm_apply_apply x @[simp] lemma of_bijective_apply_symm_apply (f : E →L[𝕜] F) (hinj : f.ker = ⊥) (hsurj : f.range = ⊤) (y : F) : f ((of_bijective f hinj hsurj).symm y) = y := (of_bijective f hinj hsurj).apply_symm_apply y end continuous_linear_equiv namespace continuous_linear_map variables [complete_space E] /-- Intermediate definition used to show `continuous_linear_map.closed_complemented_range_of_is_compl_of_ker_eq_bot`. This is `f.coprod G.subtypeL` as an `continuous_linear_equiv`. -/ noncomputable def coprod_subtypeL_equiv_of_is_compl (f : E →L[𝕜] F) {G : submodule 𝕜 F} (h : is_compl f.range G) [complete_space G] (hker : f.ker = ⊥) : (E × G) ≃L[𝕜] F := continuous_linear_equiv.of_bijective (f.coprod G.subtypeL) (begin rw ker_coprod_of_disjoint_range, { rw [hker, submodule.ker_subtypeL, submodule.prod_bot] }, { rw submodule.range_subtypeL, exact h.disjoint } end) (by simp only [range_coprod, h.sup_eq_top, submodule.range_subtypeL]) lemma range_eq_map_coprod_subtypeL_equiv_of_is_compl (f : E →L[𝕜] F) {G : submodule 𝕜 F} (h : is_compl f.range G) [complete_space G] (hker : f.ker = ⊥) : f.range = ((⊤ : submodule 𝕜 E).prod (⊥ : submodule 𝕜 G)).map (f.coprod_subtypeL_equiv_of_is_compl h hker : E × G →ₗ[𝕜] F) := by rw [coprod_subtypeL_equiv_of_is_compl, _root_.coe_coe, continuous_linear_equiv.coe_of_bijective, coe_coprod, linear_map.coprod_map_prod, submodule.map_bot, sup_bot_eq, submodule.map_top, range] /- TODO: remove the assumption `f.ker = ⊥` in the next lemma, by using the map induced by `f` on `E / f.ker`, once we have quotient normed spaces. -/ lemma closed_complemented_range_of_is_compl_of_ker_eq_bot (f : E →L[𝕜] F) (G : submodule 𝕜 F) (h : is_compl f.range G) (hG : is_closed (G : set F)) (hker : f.ker = ⊥) : is_closed (f.range : set F) := begin haveI : complete_space G := hG.complete_space_coe, let g := coprod_subtypeL_equiv_of_is_compl f h hker, rw congr_arg coe (range_eq_map_coprod_subtypeL_equiv_of_is_compl f h hker ), apply g.to_homeomorph.is_closed_image.2, exact is_closed_univ.prod is_closed_singleton, end end continuous_linear_map section closed_graph_thm variables [complete_space E] (g : E →ₗ[𝕜] F) /-- The **closed graph theorem** : a linear map between two Banach spaces whose graph is closed is continuous. -/ theorem linear_map.continuous_of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) : continuous g := begin letI : complete_space g.graph := complete_space_coe_iff_is_complete.mpr hg.is_complete, let φ₀ : E →ₗ[𝕜] E × F := linear_map.id.prod g, have : function.left_inverse prod.fst φ₀ := λ x, rfl, let φ : E ≃ₗ[𝕜] g.graph := (linear_equiv.of_left_inverse this).trans (linear_equiv.of_eq _ _ g.graph_eq_range_prod.symm), let ψ : g.graph ≃L[𝕜] E := φ.symm.to_continuous_linear_equiv_of_continuous continuous_subtype_coe.fst, exact (continuous_subtype_coe.comp ψ.symm.continuous).snd end /-- A useful form of the **closed graph theorem** : let `f` be a linear map between two Banach spaces. To show that `f` is continuous, it suffices to show that for any convergent sequence `uₙ ⟶ x`, if `f(uₙ) ⟶ y` then `y = f(x)`. -/ theorem linear_map.continuous_of_seq_closed_graph (hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) : continuous g := begin refine g.continuous_of_is_closed_graph (is_seq_closed_iff_is_closed.mp $ is_seq_closed_of_def _), rintros φ ⟨x, y⟩ hφg hφ, refine hg (prod.fst ∘ φ) x y ((continuous_fst.tendsto _).comp hφ) _, have : g ∘ prod.fst ∘ φ = prod.snd ∘ φ, { ext n, exact (hφg n).symm }, rw this, exact (continuous_snd.tendsto _).comp hφ end variable {g} namespace continuous_linear_map /-- Upgrade a `linear_map` to a `continuous_linear_map` using the **closed graph theorem**. -/ def of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) : E →L[𝕜] F := { to_linear_map := g, cont := g.continuous_of_is_closed_graph hg } @[simp] lemma coe_fn_of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) : ⇑(continuous_linear_map.of_is_closed_graph hg) = g := rfl lemma coe_of_is_closed_graph (hg : is_closed (g.graph : set $ E × F)) : ↑(continuous_linear_map.of_is_closed_graph hg) = g := by { ext, refl } /-- Upgrade a `linear_map` to a `continuous_linear_map` using a variation on the **closed graph theorem**. -/ def of_seq_closed_graph (hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) : E →L[𝕜] F := { to_linear_map := g, cont := g.continuous_of_seq_closed_graph hg } @[simp] lemma coe_fn_of_seq_closed_graph (hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) : ⇑(continuous_linear_map.of_seq_closed_graph hg) = g := rfl lemma coe_of_seq_closed_graph (hg : ∀ (u : ℕ → E) x y, tendsto u at_top (𝓝 x) → tendsto (g ∘ u) at_top (𝓝 y) → y = g x) : ↑(continuous_linear_map.of_seq_closed_graph hg) = g := by { ext, refl } end continuous_linear_map end closed_graph_thm
d93b65e18df0614aa34710414e4ccea306148fac
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/calculus/lhopital.lean
9aa92fb7a55a21e42a0ac6a97322512337be7383
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
24,851
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.calculus.mean_value /-! # L'Hôpital's rule for 0/0 indeterminate forms In this file, we prove several forms of "L'Hopital's rule" for computing 0/0 indeterminate forms. The proof of `has_deriv_at.lhopital_zero_right_on_Ioo` is based on the one given in the corresponding [Wikibooks](https://en.wikibooks.org/wiki/Calculus/L%27H%C3%B4pital%27s_Rule) chapter, and all other statements are derived from this one by composing by carefully chosen functions. Note that the filter `f'/g'` tends to isn't required to be one of `𝓝 a`, `at_top` or `at_bot`. In fact, we give a slightly stronger statement by allowing it to be any filter on `ℝ`. Each statement is available in a `has_deriv_at` form and a `deriv` form, which is denoted by each statement being in either the `has_deriv_at` or the `deriv` namespace. ## Tags L'Hôpital's rule, L'Hopital's rule -/ open filter set open_locale filter topological_space pointwise variables {a b : ℝ} (hab : a < b) {l : filter ℝ} {f f' g g' : ℝ → ℝ} /-! ## Interval-based versions We start by proving statements where all conditions (derivability, `g' ≠ 0`) have to be satisfied on an explicitly-provided interval. -/ namespace has_deriv_at include hab theorem lhopital_zero_right_on_Ioo (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hg' : ∀ x ∈ Ioo a b, g' x ≠ 0) (hfa : tendsto f (𝓝[>] a) (𝓝 0)) (hga : tendsto g (𝓝[>] a) (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[>] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[>] a) l := begin have sub : ∀ x ∈ Ioo a b, Ioo a x ⊆ Ioo a b := λ x hx, Ioo_subset_Ioo (le_refl a) (le_of_lt hx.2), have hg : ∀ x ∈ (Ioo a b), g x ≠ 0, { intros x hx h, have : tendsto g (𝓝[<] x) (𝓝 0), { rw [← h, ← nhds_within_Ioo_eq_nhds_within_Iio hx.1], exact ((hgg' x hx).continuous_at.continuous_within_at.mono $ sub x hx).tendsto }, obtain ⟨y, hyx, hy⟩ : ∃ c ∈ Ioo a x, g' c = 0, from exists_has_deriv_at_eq_zero' hx.1 hga this (λ y hy, hgg' y $ sub x hx hy), exact hg' y (sub x hx hyx) hy }, have : ∀ x ∈ Ioo a b, ∃ c ∈ Ioo a x, (f x) * (g' c) = (g x) * (f' c), { intros x hx, rw [← sub_zero (f x), ← sub_zero (g x)], exact exists_ratio_has_deriv_at_eq_ratio_slope' g g' hx.1 f f' (λ y hy, hgg' y $ sub x hx hy) (λ y hy, hff' y $ sub x hx hy) hga hfa (tendsto_nhds_within_of_tendsto_nhds (hgg' x hx).continuous_at.tendsto) (tendsto_nhds_within_of_tendsto_nhds (hff' x hx).continuous_at.tendsto) }, choose! c hc using this, have : ∀ x ∈ Ioo a b, ((λ x', (f' x') / (g' x')) ∘ c) x = f x / g x, { intros x hx, rcases hc x hx with ⟨h₁, h₂⟩, field_simp [hg x hx, hg' (c x) ((sub x hx) h₁)], simp only [h₂], rwa mul_comm }, have cmp : ∀ x ∈ Ioo a b, a < c x ∧ c x < x, from λ x hx, (hc x hx).1, rw ← nhds_within_Ioo_eq_nhds_within_Ioi hab, apply tendsto_nhds_within_congr this, simp only, apply hdiv.comp, refine tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (tendsto_nhds_within_of_tendsto_nhds tendsto_id) _ _) _, all_goals { apply eventually_nhds_within_of_forall, intros x hx, have := cmp x hx, try {simp}, linarith [this] } end theorem lhopital_zero_right_on_Ico (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hcf : continuous_on f (Ico a b)) (hcg : continuous_on g (Ico a b)) (hg' : ∀ x ∈ Ioo a b, g' x ≠ 0) (hfa : f a = 0) (hga : g a = 0) (hdiv : tendsto (λ x, (f' x) / (g' x)) (nhds_within a (Ioi a)) l) : tendsto (λ x, (f x) / (g x)) (nhds_within a (Ioi a)) l := begin refine lhopital_zero_right_on_Ioo hab hff' hgg' hg' _ _ hdiv, { rw [← hfa, ← nhds_within_Ioo_eq_nhds_within_Ioi hab], exact ((hcf a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto }, { rw [← hga, ← nhds_within_Ioo_eq_nhds_within_Ioi hab], exact ((hcg a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto }, end theorem lhopital_zero_left_on_Ioo (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hg' : ∀ x ∈ Ioo a b, g' x ≠ 0) (hfb : tendsto f (nhds_within b (Iio b)) (𝓝 0)) (hgb : tendsto g (nhds_within b (Iio b)) (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) (nhds_within b (Iio b)) l) : tendsto (λ x, (f x) / (g x)) (nhds_within b (Iio b)) l := begin -- Here, we essentially compose by `has_neg.neg`. The following is mostly technical details. have hdnf : ∀ x ∈ -Ioo a b, has_deriv_at (f ∘ has_neg.neg) (f' (-x) * (-1)) x, from λ x hx, comp x (hff' (-x) hx) (has_deriv_at_neg x), have hdng : ∀ x ∈ -Ioo a b, has_deriv_at (g ∘ has_neg.neg) (g' (-x) * (-1)) x, from λ x hx, comp x (hgg' (-x) hx) (has_deriv_at_neg x), rw preimage_neg_Ioo at hdnf, rw preimage_neg_Ioo at hdng, have := lhopital_zero_right_on_Ioo (neg_lt_neg hab) hdnf hdng (by { intros x hx h, apply hg' _ (by {rw ← preimage_neg_Ioo at hx, exact hx}), rwa [mul_comm, ← neg_eq_neg_one_mul, neg_eq_zero] at h }) (hfb.comp tendsto_neg_nhds_within_Ioi_neg) (hgb.comp tendsto_neg_nhds_within_Ioi_neg) (by { simp only [neg_div_neg_eq, mul_one, mul_neg_eq_neg_mul_symm], exact (tendsto_congr $ λ x, rfl).mp (hdiv.comp tendsto_neg_nhds_within_Ioi_neg) }), have := this.comp tendsto_neg_nhds_within_Iio, unfold function.comp at this, simpa only [neg_neg] end theorem lhopital_zero_left_on_Ioc (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hcf : continuous_on f (Ioc a b)) (hcg : continuous_on g (Ioc a b)) (hg' : ∀ x ∈ Ioo a b, g' x ≠ 0) (hfb : f b = 0) (hgb : g b = 0) (hdiv : tendsto (λ x, (f' x) / (g' x)) (nhds_within b (Iio b)) l) : tendsto (λ x, (f x) / (g x)) (nhds_within b (Iio b)) l := begin refine lhopital_zero_left_on_Ioo hab hff' hgg' hg' _ _ hdiv, { rw [← hfb, ← nhds_within_Ioo_eq_nhds_within_Iio hab], exact ((hcf b $ right_mem_Ioc.mpr hab).mono Ioo_subset_Ioc_self).tendsto }, { rw [← hgb, ← nhds_within_Ioo_eq_nhds_within_Iio hab], exact ((hcg b $ right_mem_Ioc.mpr hab).mono Ioo_subset_Ioc_self).tendsto }, end omit hab theorem lhopital_zero_at_top_on_Ioi (hff' : ∀ x ∈ Ioi a, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioi a, has_deriv_at g (g' x) x) (hg' : ∀ x ∈ Ioi a, g' x ≠ 0) (hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) at_top l) : tendsto (λ x, (f x) / (g x)) at_top l := begin obtain ⟨ a', haa', ha'⟩ : ∃ a', a < a' ∧ 0 < a' := ⟨1 + max a 0, ⟨lt_of_le_of_lt (le_max_left a 0) (lt_one_add _), lt_of_le_of_lt (le_max_right a 0) (lt_one_add _)⟩⟩, have fact1 : ∀ (x:ℝ), x ∈ Ioo 0 a'⁻¹ → x ≠ 0 := λ _ hx, (ne_of_lt hx.1).symm, have fact2 : ∀ x ∈ Ioo 0 a'⁻¹, a < x⁻¹, from λ _ hx, lt_trans haa' ((lt_inv ha' hx.1).mpr hx.2), have hdnf : ∀ x ∈ Ioo 0 a'⁻¹, has_deriv_at (f ∘ has_inv.inv) (f' (x⁻¹) * (-(x^2)⁻¹)) x, from λ x hx, comp x (hff' (x⁻¹) $ fact2 x hx) (has_deriv_at_inv $ fact1 x hx), have hdng : ∀ x ∈ Ioo 0 a'⁻¹, has_deriv_at (g ∘ has_inv.inv) (g' (x⁻¹) * (-(x^2)⁻¹)) x, from λ x hx, comp x (hgg' (x⁻¹) $ fact2 x hx) (has_deriv_at_inv $ fact1 x hx), have := lhopital_zero_right_on_Ioo (inv_pos.mpr ha') hdnf hdng (by { intros x hx, refine mul_ne_zero _ (neg_ne_zero.mpr $ inv_ne_zero $ pow_ne_zero _ $ fact1 x hx), exact hg' _ (fact2 x hx) }) (hftop.comp tendsto_inv_zero_at_top) (hgtop.comp tendsto_inv_zero_at_top) (by { refine (tendsto_congr' _).mp (hdiv.comp tendsto_inv_zero_at_top), rw eventually_eq_iff_exists_mem, use [Ioi 0, self_mem_nhds_within], intros x hx, unfold function.comp, erw mul_div_mul_right, refine neg_ne_zero.mpr (inv_ne_zero $ pow_ne_zero _ $ ne_of_gt hx) }), have := this.comp tendsto_inv_at_top_zero', unfold function.comp at this, simpa only [inv_inv₀], end theorem lhopital_zero_at_bot_on_Iio (hff' : ∀ x ∈ Iio a, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Iio a, has_deriv_at g (g' x) x) (hg' : ∀ x ∈ Iio a, g' x ≠ 0) (hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) at_bot l) : tendsto (λ x, (f x) / (g x)) at_bot l := begin -- Here, we essentially compose by `has_neg.neg`. The following is mostly technical details. have hdnf : ∀ x ∈ -Iio a, has_deriv_at (f ∘ has_neg.neg) (f' (-x) * (-1)) x, from λ x hx, comp x (hff' (-x) hx) (has_deriv_at_neg x), have hdng : ∀ x ∈ -Iio a, has_deriv_at (g ∘ has_neg.neg) (g' (-x) * (-1)) x, from λ x hx, comp x (hgg' (-x) hx) (has_deriv_at_neg x), rw preimage_neg_Iio at hdnf, rw preimage_neg_Iio at hdng, have := lhopital_zero_at_top_on_Ioi hdnf hdng (by { intros x hx h, apply hg' _ (by {rw ← preimage_neg_Iio at hx, exact hx}), rwa [mul_comm, ← neg_eq_neg_one_mul, neg_eq_zero] at h }) (hfbot.comp tendsto_neg_at_top_at_bot) (hgbot.comp tendsto_neg_at_top_at_bot) (by { simp only [mul_one, mul_neg_eq_neg_mul_symm, neg_div_neg_eq], exact (tendsto_congr $ λ x, rfl).mp (hdiv.comp tendsto_neg_at_top_at_bot) }), have := this.comp tendsto_neg_at_bot_at_top, unfold function.comp at this, simpa only [neg_neg], end end has_deriv_at namespace deriv include hab theorem lhopital_zero_right_on_Ioo (hdf : differentiable_on ℝ f (Ioo a b)) (hg' : ∀ x ∈ Ioo a b, deriv g x ≠ 0) (hfa : tendsto f (𝓝[>] a) (𝓝 0)) (hga : tendsto g (𝓝[>] a) (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[>] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[>] a) l := begin have hdf : ∀ x ∈ Ioo a b, differentiable_at ℝ f x, from λ x hx, (hdf x hx).differentiable_at (Ioo_mem_nhds hx.1 hx.2), have hdg : ∀ x ∈ Ioo a b, differentiable_at ℝ g x, from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)), exact has_deriv_at.lhopital_zero_right_on_Ioo hab (λ x hx, (hdf x hx).has_deriv_at) (λ x hx, (hdg x hx).has_deriv_at) hg' hfa hga hdiv end theorem lhopital_zero_right_on_Ico (hdf : differentiable_on ℝ f (Ioo a b)) (hcf : continuous_on f (Ico a b)) (hcg : continuous_on g (Ico a b)) (hg' : ∀ x ∈ (Ioo a b), (deriv g) x ≠ 0) (hfa : f a = 0) (hga : g a = 0) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (nhds_within a (Ioi a)) l) : tendsto (λ x, (f x) / (g x)) (nhds_within a (Ioi a)) l := begin refine lhopital_zero_right_on_Ioo hab hdf hg' _ _ hdiv, { rw [← hfa, ← nhds_within_Ioo_eq_nhds_within_Ioi hab], exact ((hcf a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto }, { rw [← hga, ← nhds_within_Ioo_eq_nhds_within_Ioi hab], exact ((hcg a $ left_mem_Ico.mpr hab).mono Ioo_subset_Ico_self).tendsto }, end theorem lhopital_zero_left_on_Ioo (hdf : differentiable_on ℝ f (Ioo a b)) (hg' : ∀ x ∈ (Ioo a b), (deriv g) x ≠ 0) (hfb : tendsto f (nhds_within b (Iio b)) (𝓝 0)) (hgb : tendsto g (nhds_within b (Iio b)) (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (nhds_within b (Iio b)) l) : tendsto (λ x, (f x) / (g x)) (nhds_within b (Iio b)) l := begin have hdf : ∀ x ∈ Ioo a b, differentiable_at ℝ f x, from λ x hx, (hdf x hx).differentiable_at (Ioo_mem_nhds hx.1 hx.2), have hdg : ∀ x ∈ Ioo a b, differentiable_at ℝ g x, from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)), exact has_deriv_at.lhopital_zero_left_on_Ioo hab (λ x hx, (hdf x hx).has_deriv_at) (λ x hx, (hdg x hx).has_deriv_at) hg' hfb hgb hdiv end omit hab theorem lhopital_zero_at_top_on_Ioi (hdf : differentiable_on ℝ f (Ioi a)) (hg' : ∀ x ∈ (Ioi a), (deriv g) x ≠ 0) (hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_top l) : tendsto (λ x, (f x) / (g x)) at_top l := begin have hdf : ∀ x ∈ Ioi a, differentiable_at ℝ f x, from λ x hx, (hdf x hx).differentiable_at (Ioi_mem_nhds hx), have hdg : ∀ x ∈ Ioi a, differentiable_at ℝ g x, from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)), exact has_deriv_at.lhopital_zero_at_top_on_Ioi (λ x hx, (hdf x hx).has_deriv_at) (λ x hx, (hdg x hx).has_deriv_at) hg' hftop hgtop hdiv, end theorem lhopital_zero_at_bot_on_Iio (hdf : differentiable_on ℝ f (Iio a)) (hg' : ∀ x ∈ (Iio a), (deriv g) x ≠ 0) (hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_bot l) : tendsto (λ x, (f x) / (g x)) at_bot l := begin have hdf : ∀ x ∈ Iio a, differentiable_at ℝ f x, from λ x hx, (hdf x hx).differentiable_at (Iio_mem_nhds hx), have hdg : ∀ x ∈ Iio a, differentiable_at ℝ g x, from λ x hx, classical.by_contradiction (λ h, hg' x hx (deriv_zero_of_not_differentiable_at h)), exact has_deriv_at.lhopital_zero_at_bot_on_Iio (λ x hx, (hdf x hx).has_deriv_at) (λ x hx, (hdg x hx).has_deriv_at) hg' hfbot hgbot hdiv, end end deriv /-! ## Generic versions The following statements no longer any explicit interval, as they only require conditions holding eventually. -/ namespace has_deriv_at /-- L'Hôpital's rule for approaching a real from the right, `has_deriv_at` version -/ theorem lhopital_zero_nhds_right (hff' : ∀ᶠ x in 𝓝[>] a, has_deriv_at f (f' x) x) (hgg' : ∀ᶠ x in 𝓝[>] a, has_deriv_at g (g' x) x) (hg' : ∀ᶠ x in 𝓝[>] a, g' x ≠ 0) (hfa : tendsto f (𝓝[>] a) (𝓝 0)) (hga : tendsto g (𝓝[>] a) (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[>] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[>] a) l := begin rw eventually_iff_exists_mem at *, rcases hff' with ⟨s₁, hs₁, hff'⟩, rcases hgg' with ⟨s₂, hs₂, hgg'⟩, rcases hg' with ⟨s₃, hs₃, hg'⟩, let s := s₁ ∩ s₂ ∩ s₃, have hs : s ∈ 𝓝[>] a := inter_mem (inter_mem hs₁ hs₂) hs₃, rw mem_nhds_within_Ioi_iff_exists_Ioo_subset at hs, rcases hs with ⟨u, hau, hu⟩, refine lhopital_zero_right_on_Ioo hau _ _ _ hfa hga hdiv; intros x hx; apply_assumption; exact (hu hx).1.1 <|> exact (hu hx).1.2 <|> exact (hu hx).2 end /-- L'Hôpital's rule for approaching a real from the left, `has_deriv_at` version -/ theorem lhopital_zero_nhds_left (hff' : ∀ᶠ x in 𝓝[<] a, has_deriv_at f (f' x) x) (hgg' : ∀ᶠ x in 𝓝[<] a, has_deriv_at g (g' x) x) (hg' : ∀ᶠ x in 𝓝[<] a, g' x ≠ 0) (hfa : tendsto f (𝓝[<] a) (𝓝 0)) (hga : tendsto g (𝓝[<] a) (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[<] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[<] a) l := begin rw eventually_iff_exists_mem at *, rcases hff' with ⟨s₁, hs₁, hff'⟩, rcases hgg' with ⟨s₂, hs₂, hgg'⟩, rcases hg' with ⟨s₃, hs₃, hg'⟩, let s := s₁ ∩ s₂ ∩ s₃, have hs : s ∈ 𝓝[<] a := inter_mem (inter_mem hs₁ hs₂) hs₃, rw mem_nhds_within_Iio_iff_exists_Ioo_subset at hs, rcases hs with ⟨l, hal, hl⟩, refine lhopital_zero_left_on_Ioo hal _ _ _ hfa hga hdiv; intros x hx; apply_assumption; exact (hl hx).1.1 <|> exact (hl hx).1.2 <|> exact (hl hx).2 end /-- L'Hôpital's rule for approaching a real, `has_deriv_at` version. This does not require anything about the situation at `a` -/ theorem lhopital_zero_nhds' (hff' : ∀ᶠ x in 𝓝[univ \ {a}] a, has_deriv_at f (f' x) x) (hgg' : ∀ᶠ x in 𝓝[univ \ {a}] a, has_deriv_at g (g' x) x) (hg' : ∀ᶠ x in 𝓝[univ \ {a}] a, g' x ≠ 0) (hfa : tendsto f (𝓝[univ \ {a}] a) (𝓝 0)) (hga : tendsto g (𝓝[univ \ {a}] a) (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) (𝓝[univ \ {a}] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[univ \ {a}] a) l := begin have : univ \ {a} = Iio a ∪ Ioi a, { ext, rw [mem_diff_singleton, eq_true_intro $ mem_univ x, true_and, ne_iff_lt_or_gt], refl }, simp only [this, nhds_within_union, tendsto_sup, eventually_sup] at *, exact ⟨lhopital_zero_nhds_left hff'.1 hgg'.1 hg'.1 hfa.1 hga.1 hdiv.1, lhopital_zero_nhds_right hff'.2 hgg'.2 hg'.2 hfa.2 hga.2 hdiv.2⟩ end /-- **L'Hôpital's rule** for approaching a real, `has_deriv_at` version -/ theorem lhopital_zero_nhds (hff' : ∀ᶠ x in 𝓝 a, has_deriv_at f (f' x) x) (hgg' : ∀ᶠ x in 𝓝 a, has_deriv_at g (g' x) x) (hg' : ∀ᶠ x in 𝓝 a, g' x ≠ 0) (hfa : tendsto f (𝓝 a) (𝓝 0)) (hga : tendsto g (𝓝 a) (𝓝 0)) (hdiv : tendsto (λ x, f' x / g' x) (𝓝 a) l) : tendsto (λ x, f x / g x) (𝓝[univ \ {a}] a) l := begin apply @lhopital_zero_nhds' _ _ _ f' _ g'; apply eventually_nhds_within_of_eventually_nhds <|> apply tendsto_nhds_within_of_tendsto_nhds; assumption end /-- L'Hôpital's rule for approaching +∞, `has_deriv_at` version -/ theorem lhopital_zero_at_top (hff' : ∀ᶠ x in at_top, has_deriv_at f (f' x) x) (hgg' : ∀ᶠ x in at_top, has_deriv_at g (g' x) x) (hg' : ∀ᶠ x in at_top, g' x ≠ 0) (hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) at_top l) : tendsto (λ x, (f x) / (g x)) at_top l := begin rw eventually_iff_exists_mem at *, rcases hff' with ⟨s₁, hs₁, hff'⟩, rcases hgg' with ⟨s₂, hs₂, hgg'⟩, rcases hg' with ⟨s₃, hs₃, hg'⟩, let s := s₁ ∩ s₂ ∩ s₃, have hs : s ∈ at_top := inter_mem (inter_mem hs₁ hs₂) hs₃, rw mem_at_top_sets at hs, rcases hs with ⟨l, hl⟩, have hl' : Ioi l ⊆ s := λ x hx, hl x (le_of_lt hx), refine lhopital_zero_at_top_on_Ioi _ _ (λ x hx, hg' x $ (hl' hx).2) hftop hgtop hdiv; intros x hx; apply_assumption; exact (hl' hx).1.1 <|> exact (hl' hx).1.2 end /-- L'Hôpital's rule for approaching -∞, `has_deriv_at` version -/ theorem lhopital_zero_at_bot (hff' : ∀ᶠ x in at_bot, has_deriv_at f (f' x) x) (hgg' : ∀ᶠ x in at_bot, has_deriv_at g (g' x) x) (hg' : ∀ᶠ x in at_bot, g' x ≠ 0) (hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0)) (hdiv : tendsto (λ x, (f' x) / (g' x)) at_bot l) : tendsto (λ x, (f x) / (g x)) at_bot l := begin rw eventually_iff_exists_mem at *, rcases hff' with ⟨s₁, hs₁, hff'⟩, rcases hgg' with ⟨s₂, hs₂, hgg'⟩, rcases hg' with ⟨s₃, hs₃, hg'⟩, let s := s₁ ∩ s₂ ∩ s₃, have hs : s ∈ at_bot := inter_mem (inter_mem hs₁ hs₂) hs₃, rw mem_at_bot_sets at hs, rcases hs with ⟨l, hl⟩, have hl' : Iio l ⊆ s := λ x hx, hl x (le_of_lt hx), refine lhopital_zero_at_bot_on_Iio _ _ (λ x hx, hg' x $ (hl' hx).2) hfbot hgbot hdiv; intros x hx; apply_assumption; exact (hl' hx).1.1 <|> exact (hl' hx).1.2 end end has_deriv_at namespace deriv /-- **L'Hôpital's rule** for approaching a real from the right, `deriv` version -/ theorem lhopital_zero_nhds_right (hdf : ∀ᶠ x in 𝓝[>] a, differentiable_at ℝ f x) (hg' : ∀ᶠ x in 𝓝[>] a, deriv g x ≠ 0) (hfa : tendsto f (𝓝[>] a) (𝓝 0)) (hga : tendsto g (𝓝[>] a) (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[>] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[>] a) l := begin have hdg : ∀ᶠ x in 𝓝[>] a, differentiable_at ℝ g x, from hg'.mp (eventually_of_forall $ λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))), have hdf' : ∀ᶠ x in 𝓝[>] a, has_deriv_at f (deriv f x) x, from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), have hdg' : ∀ᶠ x in 𝓝[>] a, has_deriv_at g (deriv g x) x, from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), exact has_deriv_at.lhopital_zero_nhds_right hdf' hdg' hg' hfa hga hdiv end /-- **L'Hôpital's rule** for approaching a real from the left, `deriv` version -/ theorem lhopital_zero_nhds_left (hdf : ∀ᶠ x in 𝓝[<] a, differentiable_at ℝ f x) (hg' : ∀ᶠ x in 𝓝[<] a, deriv g x ≠ 0) (hfa : tendsto f (𝓝[<] a) (𝓝 0)) (hga : tendsto g (𝓝[<] a) (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[<] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[<] a) l := begin have hdg : ∀ᶠ x in 𝓝[<] a, differentiable_at ℝ g x, from hg'.mp (eventually_of_forall $ λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))), have hdf' : ∀ᶠ x in 𝓝[<] a, has_deriv_at f (deriv f x) x, from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), have hdg' : ∀ᶠ x in 𝓝[<] a, has_deriv_at g (deriv g x) x, from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), exact has_deriv_at.lhopital_zero_nhds_left hdf' hdg' hg' hfa hga hdiv end /-- **L'Hôpital's rule** for approaching a real, `deriv` version. This does not require anything about the situation at `a` -/ theorem lhopital_zero_nhds' (hdf : ∀ᶠ x in 𝓝[univ \ {a}] a, differentiable_at ℝ f x) (hg' : ∀ᶠ x in 𝓝[univ \ {a}] a, deriv g x ≠ 0) (hfa : tendsto f (𝓝[univ \ {a}] a) (𝓝 0)) (hga : tendsto g (𝓝[univ \ {a}] a) (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝[univ \ {a}] a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[univ \ {a}] a) l := begin have : univ \ {a} = Iio a ∪ Ioi a, { ext, rw [mem_diff_singleton, eq_true_intro $ mem_univ x, true_and, ne_iff_lt_or_gt], refl }, simp only [this, nhds_within_union, tendsto_sup, eventually_sup] at *, exact ⟨lhopital_zero_nhds_left hdf.1 hg'.1 hfa.1 hga.1 hdiv.1, lhopital_zero_nhds_right hdf.2 hg'.2 hfa.2 hga.2 hdiv.2⟩, end /-- **L'Hôpital's rule** for approaching a real, `deriv` version -/ theorem lhopital_zero_nhds (hdf : ∀ᶠ x in 𝓝 a, differentiable_at ℝ f x) (hg' : ∀ᶠ x in 𝓝 a, deriv g x ≠ 0) (hfa : tendsto f (𝓝 a) (𝓝 0)) (hga : tendsto g (𝓝 a) (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) (𝓝 a) l) : tendsto (λ x, (f x) / (g x)) (𝓝[univ \ {a}] a) l := begin apply lhopital_zero_nhds'; apply eventually_nhds_within_of_eventually_nhds <|> apply tendsto_nhds_within_of_tendsto_nhds; assumption end /-- **L'Hôpital's rule** for approaching +∞, `deriv` version -/ theorem lhopital_zero_at_top (hdf : ∀ᶠ (x : ℝ) in at_top, differentiable_at ℝ f x) (hg' : ∀ᶠ (x : ℝ) in at_top, deriv g x ≠ 0) (hftop : tendsto f at_top (𝓝 0)) (hgtop : tendsto g at_top (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_top l) : tendsto (λ x, (f x) / (g x)) at_top l := begin have hdg : ∀ᶠ x in at_top, differentiable_at ℝ g x, from hg'.mp (eventually_of_forall $ λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))), have hdf' : ∀ᶠ x in at_top, has_deriv_at f (deriv f x) x, from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), have hdg' : ∀ᶠ x in at_top, has_deriv_at g (deriv g x) x, from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), exact has_deriv_at.lhopital_zero_at_top hdf' hdg' hg' hftop hgtop hdiv end /-- **L'Hôpital's rule** for approaching -∞, `deriv` version -/ theorem lhopital_zero_at_bot (hdf : ∀ᶠ (x : ℝ) in at_bot, differentiable_at ℝ f x) (hg' : ∀ᶠ (x : ℝ) in at_bot, deriv g x ≠ 0) (hfbot : tendsto f at_bot (𝓝 0)) (hgbot : tendsto g at_bot (𝓝 0)) (hdiv : tendsto (λ x, ((deriv f) x) / ((deriv g) x)) at_bot l) : tendsto (λ x, (f x) / (g x)) at_bot l := begin have hdg : ∀ᶠ x in at_bot, differentiable_at ℝ g x, from hg'.mp (eventually_of_forall $ λ _ hg', classical.by_contradiction (λ h, hg' (deriv_zero_of_not_differentiable_at h))), have hdf' : ∀ᶠ x in at_bot, has_deriv_at f (deriv f x) x, from hdf.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), have hdg' : ∀ᶠ x in at_bot, has_deriv_at g (deriv g x) x, from hdg.mp (eventually_of_forall $ λ _, differentiable_at.has_deriv_at), exact has_deriv_at.lhopital_zero_at_bot hdf' hdg' hg' hfbot hgbot hdiv end end deriv
73fed0128822edfed6e2dba97c8bab3f30e744c8
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/constfolding.lean
841625e0471f76c2522c56ca3a03c7911146e272
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
6,883
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.expr init.platform import init.lean.compiler.util /- Constant folding for primitives that have special runtime support. -/ namespace Lean namespace Compiler def BinFoldFn := Bool → Expr → Expr → Option Expr def UnFoldFn := Bool → Expr → Option Expr def mkUIntTypeName (nbytes : Nat) : Name := mkSimpleName ("UInt" ++ toString nbytes) structure NumScalarTypeInfo := (nbits : Nat) (id : Name := mkUIntTypeName nbits) (ofNatFn : Name := Name.mkString id "ofNat") (toNatFn : Name := Name.mkString id "toNat") (size : Nat := 2^nbits) def numScalarTypes : List NumScalarTypeInfo := [{nbits := 8}, {nbits := 16}, {nbits := 32}, {nbits := 64}, {id := `USize, nbits := System.platform.nbits}] def isOfNat (fn : Name) : Bool := numScalarTypes.any (fun info => info.ofNatFn = fn) def isToNat (fn : Name) : Bool := numScalarTypes.any (fun info => info.toNatFn = fn) def getInfoFromFn (fn : Name) : List NumScalarTypeInfo → Option NumScalarTypeInfo | [] := none | (info::infos) := if info.ofNatFn = fn then some info else getInfoFromFn infos def getInfoFromVal : Expr → Option NumScalarTypeInfo | (Expr.app (Expr.const fn _) _) := getInfoFromFn fn numScalarTypes | _ := none @[export lean.get_num_lit_core] def getNumLit : Expr → Option Nat | (Expr.lit (Literal.natVal n)) := some n | (Expr.app (Expr.const fn _) a) := if isOfNat fn then getNumLit a else none | _ := none def mkUIntLit (info : NumScalarTypeInfo) (n : Nat) : Expr := Expr.app (Expr.const info.ofNatFn []) (Expr.lit (Literal.natVal (n%info.size))) def mkUInt32Lit (n : Nat) : Expr := mkUIntLit {nbits := 32} n def foldBinUInt (fn : NumScalarTypeInfo → Bool → Nat → Nat → Nat) (beforeErasure : Bool) (a₁ a₂ : Expr) : Option Expr := do n₁ ← getNumLit a₁; n₂ ← getNumLit a₂; info ← getInfoFromVal a₁; pure $ mkUIntLit info (fn info beforeErasure n₁ n₂) def foldUIntAdd := foldBinUInt $ fun _ _ => HasAdd.add def foldUIntMul := foldBinUInt $ fun _ _ => HasMul.mul def foldUIntDiv := foldBinUInt $ fun _ _ => HasDiv.div def foldUIntMod := foldBinUInt $ fun _ _ => HasMod.mod def foldUIntSub := foldBinUInt $ fun info _ a b => (a + (info.size - b)) def preUIntBinFoldFns : List (Name × BinFoldFn) := [(`add, foldUIntAdd), (`mul, foldUIntMul), (`div, foldUIntDiv), (`mod, foldUIntMod), (`sub, foldUIntSub)] def uintBinFoldFns : List (Name × BinFoldFn) := numScalarTypes.foldl (fun r info => r ++ (preUIntBinFoldFns.map (fun ⟨suffix, fn⟩ => (info.id ++ suffix, fn)))) [] def foldNatBinOp (fn : Nat → Nat → Nat) (a₁ a₂ : Expr) : Option Expr := do n₁ ← getNumLit a₁; n₂ ← getNumLit a₂; pure $ Expr.lit (Literal.natVal (fn n₁ n₂)) def foldNatAdd (_ : Bool) := foldNatBinOp HasAdd.add def foldNatMul (_ : Bool) := foldNatBinOp HasMul.mul def foldNatDiv (_ : Bool) := foldNatBinOp HasDiv.div def foldNatMod (_ : Bool) := foldNatBinOp HasMod.mod def foldNatPow (_ : Bool) := foldNatBinOp HasPow.pow def mkNatEq (a b : Expr) : Expr := mkBinApp (Expr.app (Expr.const `Eq [Level.one]) (Expr.const `Nat [])) a b def mkNatLt (a b : Expr) : Expr := mkBinApp (mkBinApp (Expr.const `HasLt.lt [Level.zero]) (Expr.const `Nat []) (Expr.const `Nat.HasLt [])) a b def mkNatLe (a b : Expr) : Expr := mkBinApp (mkBinApp (Expr.const `HasLt.le [Level.zero]) (Expr.const `Nat []) (Expr.const `Nat.HasLe [])) a b def toDecidableExpr (beforeErasure : Bool) (pred : Expr) (r : Bool) : Expr := match beforeErasure, r with | false, true => mkDecIsTrue neutralExpr neutralExpr | false, false => mkDecIsFalse neutralExpr neutralExpr | true, true => mkDecIsTrue pred (mkLcProof pred) | true, false => mkDecIsFalse pred (mkLcProof pred) def foldNatBinPred (mkPred : Expr → Expr → Expr) (fn : Nat → Nat → Bool) (beforeErasure : Bool) (a₁ a₂ : Expr) : Option Expr := do n₁ ← getNumLit a₁; n₂ ← getNumLit a₂; pure $ toDecidableExpr beforeErasure (mkPred a₁ a₂) (fn n₁ n₂) def foldNatDecEq := foldNatBinPred mkNatEq (fun a b => a = b) def foldNatDecLt := foldNatBinPred mkNatLt (fun a b => a < b) def foldNatDecLe := foldNatBinPred mkNatLe (fun a b => a ≤ b) def natFoldFns : List (Name × BinFoldFn) := [(`Nat.add, foldNatAdd), (`Nat.mul, foldNatMul), (`Nat.div, foldNatDiv), (`Nat.mod, foldNatMod), (`Nat.pow, foldNatPow), (`Nat.pow._main, foldNatPow), (`Nat.decEq, foldNatDecEq), (`Nat.decLt, foldNatDecLt), (`Nat.decLe, foldNatDecLe)] def getBoolLit : Expr → Option Bool | (Expr.const `Bool.true _) := some true | (Expr.const `Bool.false _) := some false | _ := none def foldStrictAnd (_ : Bool) (a₁ a₂ : Expr) : Option Expr := let v₁ := getBoolLit a₁; let v₂ := getBoolLit a₂; match v₁, v₂ with | some true, _ => a₂ | some false, _ => a₁ | _, some true => a₁ | _, some false => a₂ | _, _ => none def foldStrictOr (_ : Bool) (a₁ a₂ : Expr) : Option Expr := let v₁ := getBoolLit a₁; let v₂ := getBoolLit a₂; match v₁, v₂ with | some true, _ => a₁ | some false, _ => a₂ | _, some true => a₂ | _, some false => a₁ | _, _ => none def boolFoldFns : List (Name × BinFoldFn) := [(`strictOr, foldStrictOr), (`strictAnd, foldStrictAnd)] def binFoldFns : List (Name × BinFoldFn) := boolFoldFns ++ uintBinFoldFns ++ natFoldFns def foldNatSucc (_ : Bool) (a : Expr) : Option Expr := do n ← getNumLit a; pure $ Expr.lit (Literal.natVal (n+1)) def foldCharOfNat (beforeErasure : Bool) (a : Expr) : Option Expr := do guard (!beforeErasure); n ← getNumLit a; pure $ if isValidChar (UInt32.ofNat n) then mkUInt32Lit n else mkUInt32Lit 0 def foldToNat (_ : Bool) (a : Expr) : Option Expr := do n ← getNumLit a; pure $ Expr.lit (Literal.natVal n) def uintFoldToNatFns : List (Name × UnFoldFn) := numScalarTypes.foldl (fun r info => (info.toNatFn, foldToNat) :: r) [] def unFoldFns : List (Name × UnFoldFn) := [(`Nat.succ, foldNatSucc), (`Char.ofNat, foldCharOfNat)] ++ uintFoldToNatFns def findBinFoldFn (fn : Name) : Option BinFoldFn := binFoldFns.lookup fn def findUnFoldFn (fn : Name) : Option UnFoldFn := unFoldFns.lookup fn @[export lean.fold_bin_op_core] def foldBinOp (beforeErasure : Bool) (f : Expr) (a : Expr) (b : Expr) : Option Expr := match f with | Expr.const fn _ => do foldFn ← findBinFoldFn fn; foldFn beforeErasure a b | _ => none @[export lean.fold_un_op_core] def foldUnOp (beforeErasure : Bool) (f : Expr) (a : Expr) : Option Expr := match f with | Expr.const fn _ => do foldFn ← findUnFoldFn fn; foldFn beforeErasure a | _ => none end Compiler end Lean
cb2d03fd887b2e627e4211779d18d1c5c13b998d
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/UnificationHint.lean
098a977a0d084cd4d1b1867202d0504cf6a94c0e
[ "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
5,259
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.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.DiscrTree import Lean.Meta.SynthInstance namespace Lean.Meta structure UnificationHintEntry where keys : Array DiscrTree.Key val : Name deriving Inhabited structure UnificationHints where discrTree : DiscrTree Name := DiscrTree.empty deriving Inhabited instance : ToFormat UnificationHints where format h := format h.discrTree def UnificationHints.add (hints : UnificationHints) (e : UnificationHintEntry) : UnificationHints := { hints with discrTree := hints.discrTree.insertCore e.keys e.val } builtin_initialize unificationHintExtension : SimpleScopedEnvExtension UnificationHintEntry UnificationHints ← registerSimpleScopedEnvExtension { name := `unifHints addEntry := UnificationHints.add initial := {} } structure UnificationConstraint where lhs : Expr rhs : Expr structure UnificationHint where pattern : UnificationConstraint constraints : List UnificationConstraint private partial def decodeUnificationHint (e : Expr) : ExceptT MessageData Id UnificationHint := do decode e #[] where decodeConstraint (e : Expr) : ExceptT MessageData Id UnificationConstraint := match e.eq? with | some (_, lhs, rhs) => return UnificationConstraint.mk lhs rhs | none => throw m!"invalid unification hint constraint, unexpected term{indentExpr e}" decode (e : Expr) (cs : Array UnificationConstraint) : ExceptT MessageData Id UnificationHint := do match e with | Expr.forallE _ d b _ => do let c ← decodeConstraint d if b.hasLooseBVars then throw m!"invalid unification hint constraint, unexpected dependency{indentExpr e}" decode b (cs.push c) | _ => do let p ← decodeConstraint e return { pattern := p, constraints := cs.toList } private partial def validateHint (hint : UnificationHint) : MetaM Unit := do hint.constraints.forM fun c => do unless (← isDefEq c.lhs c.rhs) do throwError "invalid unification hint, failed to unify constraint left-hand-side{indentExpr c.lhs}\nwith right-hand-side{indentExpr c.rhs}" unless (← isDefEq hint.pattern.lhs hint.pattern.rhs) do throwError "invalid unification hint, failed to unify pattern left-hand-side{indentExpr hint.pattern.lhs}\nwith right-hand-side{indentExpr hint.pattern.rhs}" def addUnificationHint (declName : Name) (kind : AttributeKind) : MetaM Unit := withNewMCtxDepth do let info ← getConstInfo declName match info.value? with | none => throwError "invalid unification hint, it must be a definition" | some val => let (_, _, body) ← lambdaMetaTelescope val match decodeUnificationHint body with | Except.error msg => throwError msg | Except.ok hint => let keys ← DiscrTree.mkPath hint.pattern.lhs validateHint hint unificationHintExtension.add { keys := keys, val := declName } kind builtin_initialize registerBuiltinAttribute { name := `unificationHint descr := "unification hint" add := fun declName stx kind => do Attribute.Builtin.ensureNoArgs stx discard <| addUnificationHint declName kind |>.run } def tryUnificationHints (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.hint] "{t} =?= {s}" unless (← read).config.unificationHints do return false if t.isMVar then return false let hints := unificationHintExtension.getState (← getEnv) let candidates ← hints.discrTree.getMatch t for candidate in candidates do if (← tryCandidate candidate) then return true return false where isDefEqPattern p e := withReducible <| Meta.isExprDefEqAux p e tryCandidate candidate : MetaM Bool := traceCtx `Meta.isDefEq.hint <| checkpointDefEq do trace[Meta.isDefEq.hint] "trying hint {candidate} at {t} =?= {s}" let cinfo ← getConstInfo candidate let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar let val ← instantiateValueLevelParams cinfo us let (xs, bis, body) ← lambdaMetaTelescope val let hint? ← withConfig (fun cfg => { cfg with unificationHints := false }) do match decodeUnificationHint body with | Except.error _ => return none | Except.ok hint => if (← isDefEqPattern hint.pattern.lhs t <&&> isDefEqPattern hint.pattern.rhs s) then return some hint else return none match hint? with | none => return false | some hint => trace[Meta.isDefEq.hint] "{candidate} succeeded, applying constraints" for c in hint.constraints do unless (← Meta.isExprDefEqAux c.lhs c.rhs) do return false for x in xs, bi in bis do if bi == BinderInfo.instImplicit then match (← trySynthInstance (← inferType x)) with | LOption.some val => unless (← isDefEq x val) do return false | _ => return false return true builtin_initialize registerTraceClass `Meta.isDefEq.hint end Lean.Meta
ec094762257886c82db90c959032075fe88f4630
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Compiler/IR/Boxing.lean
1e923ca99a58bd9a049239275fb91435c3c0858c
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,241
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.Runtime import Lean.Compiler.ClosedTermCache import Lean.Compiler.ExternAttr import Lean.Compiler.IR.Basic import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.FreeVars import Lean.Compiler.IR.ElimDeadVars namespace Lean.IR.ExplicitBoxing /- Add explicit boxing and unboxing instructions. Recall that the Lean to λ_pure compiler produces code without these instructions. Assumptions: - This transformation is applied before explicit RC instructions (`inc`, `dec`) are inserted. - This transformation is applied before `FnBody.case` has been simplified and `Alt.default` is used. Reason: if there is no `Alt.default` branch, then we can decide whether `x` at `FnBody.case x alts` is an enumeration type by simply inspecting the `CtorInfo` values at `alts`. - This transformation is applied before lower level optimizations are applied which use `Expr.isShared`, `Expr.isTaggedPtr`, and `FnBody.set`. - This transformation is applied after `reset` and `reuse` instructions have been added. Reason: `resetreuse.lean` ignores `box` and `unbox` instructions. -/ open Std (AssocList) def mkBoxedName (n : Name) : Name := Name.mkStr n "_boxed" def isBoxedName : Name → Bool | Name.str _ "_boxed" _ => true | _ => false abbrev N := StateM Nat private def N.mkFresh : N VarId := modifyGet fun n => ({ idx := n }, n + 1) def requiresBoxedVersion (env : Environment) (decl : Decl) : Bool := let ps := decl.params (ps.size > 0 && (decl.resultType.isScalar || ps.any (fun p => p.ty.isScalar || p.borrow) || isExtern env decl.name)) || ps.size > closureMaxArgs def mkBoxedVersionAux (decl : Decl) : N Decl := do let ps := decl.params let qs ← ps.mapM fun _ => do let x ← N.mkFresh; pure { x := x, ty := IRType.object, borrow := false : Param } let (newVDecls, xs) ← qs.size.foldM (init := (#[], #[])) fun i (newVDecls, xs) => do let p := ps[i] let q := qs[i] if !p.ty.isScalar then pure (newVDecls, xs.push (Arg.var q.x)) else let x ← N.mkFresh pure (newVDecls.push (FnBody.vdecl x p.ty (Expr.unbox q.x) arbitrary), xs.push (Arg.var x)) let r ← N.mkFresh let newVDecls := newVDecls.push (FnBody.vdecl r decl.resultType (Expr.fap decl.name xs) arbitrary) let body ← if !decl.resultType.isScalar then pure $ reshape newVDecls (FnBody.ret (Arg.var r)) else let newR ← N.mkFresh let newVDecls := newVDecls.push (FnBody.vdecl newR IRType.object (Expr.box decl.resultType r) arbitrary) pure $ reshape newVDecls (FnBody.ret (Arg.var newR)) pure $ Decl.fdecl (mkBoxedName decl.name) qs IRType.object body def mkBoxedVersion (decl : Decl) : Decl := (mkBoxedVersionAux decl).run' 1 def addBoxedVersions (env : Environment) (decls : Array Decl) : Array Decl := let boxedDecls := decls.foldl (init := #[]) fun newDecls decl => if requiresBoxedVersion env decl then newDecls.push (mkBoxedVersion decl) else newDecls decls ++ boxedDecls /- Infer scrutinee type using `case` alternatives. This can be done whenever `alts` does not contain an `Alt.default _` value. -/ def getScrutineeType (alts : Array Alt) : IRType := let isScalar := alts.size > 1 && -- Recall that we encode Unit and PUnit using `object`. alts.all fun | Alt.ctor c _ => c.isScalar | Alt.default _ => false match isScalar with | false => IRType.object | true => let n := alts.size if n < 256 then IRType.uint8 else if n < 65536 then IRType.uint16 else if n < 4294967296 then IRType.uint32 else IRType.object -- in practice this should be unreachable def eqvTypes (t₁ t₂ : IRType) : Bool := (t₁.isScalar == t₂.isScalar) && (!t₁.isScalar || t₁ == t₂) structure BoxingContext := (f : FunId := arbitrary) (localCtx : LocalContext := {}) (resultType : IRType := IRType.irrelevant) (decls : Array Decl) (env : Environment) structure BoxingState := (nextIdx : Index) /- We create auxiliary declarations when boxing constant and literals. The idea is to avoid code such as ``` let x1 := Uint64.inhabited; let x2 := box x1; ... ``` We currently do not cache these declarations in an environment extension, but we use auxDeclCache to avoid creating equivalent auxiliary declarations more than once when processing the same IR declaration. -/ (auxDecls : Array Decl := #[]) (auxDeclCache : AssocList FnBody Expr := Std.AssocList.empty) (nextAuxId : Nat := 1) abbrev M := ReaderT BoxingContext (StateT BoxingState Id) private def M.mkFresh : M VarId := do let oldS ← getModify fun s => { s with nextIdx := s.nextIdx + 1 } pure { idx := oldS.nextIdx } def getEnv : M Environment := BoxingContext.env <$> read def getLocalContext : M LocalContext := BoxingContext.localCtx <$> read def getResultType : M IRType := BoxingContext.resultType <$> read def getVarType (x : VarId) : M IRType := do let localCtx ← getLocalContext match localCtx.getType x with | some t => pure t | none => pure IRType.object -- unreachable, we assume the code is well formed def getJPParams (j : JoinPointId) : M (Array Param) := do let localCtx ← getLocalContext match localCtx.getJPParams j with | some ys => pure ys | none => pure #[] -- unreachable, we assume the code is well formed def getDecl (fid : FunId) : M Decl := do let ctx ← read match findEnvDecl' ctx.env fid ctx.decls with | some decl => pure decl | none => pure arbitrary -- unreachable if well-formed @[inline] def withParams {α : Type} (xs : Array Param) (k : M α) : M α := withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addParams xs }) k @[inline] def withVDecl {α : Type} (x : VarId) (ty : IRType) (v : Expr) (k : M α) : M α := withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addLocal x ty v }) k @[inline] def withJDecl {α : Type} (j : JoinPointId) (xs : Array Param) (v : FnBody) (k : M α) : M α := withReader (fun ctx => { ctx with localCtx := ctx.localCtx.addJP j xs v }) k /- If `x` declaration is of the form `x := Expr.lit _` or `x := Expr.fap c #[]`, and `x`'s type is not cheap to box (e.g., it is `UInt64), then return its value. -/ private def isExpensiveConstantValueBoxing (x : VarId) (xType : IRType) : M (Option Expr) := if !xType.isScalar then pure none -- We assume unboxing is always cheap else match xType with | IRType.uint8 => pure none | IRType.uint16 => pure none | _ => do let localCtx ← getLocalContext match localCtx.getValue x with | some val => match val with | Expr.lit _ => pure $ some val | Expr.fap _ args => pure $ if args.size == 0 then some val else none | _ => pure none | _ => pure none /- Auxiliary function used by castVarIfNeeded. It is used when the expected type does not match `xType`. If `xType` is scalar, then we need to "box" it. Otherwise, we need to "unbox" it. -/ def mkCast (x : VarId) (xType : IRType) (expectedType : IRType) : M Expr := do match (← isExpensiveConstantValueBoxing x xType) with | some v => do let ctx ← read let s ← get /- Create auxiliary FnBody ``` let x_1 : xType := v; let x_2 : expectedType := Expr.box xType x_1; ret x_2 ``` -/ let body : FnBody := FnBody.vdecl { idx := 1 } xType v $ FnBody.vdecl { idx := 2 } expectedType (Expr.box xType { idx := 1 }) $ FnBody.ret (mkVarArg { idx := 2 }) match s.auxDeclCache.find? body with | some v => pure v | none => do let auxName := ctx.f ++ ((`_boxed_const).appendIndexAfter s.nextAuxId) let auxConst := Expr.fap auxName #[] let auxDecl := Decl.fdecl auxName #[] expectedType body modify fun s => { s with auxDecls := s.auxDecls.push auxDecl, auxDeclCache := s.auxDeclCache.cons body auxConst, nextAuxId := s.nextAuxId + 1 } pure auxConst | none => pure $ if xType.isScalar then Expr.box xType x else Expr.unbox x @[inline] def castVarIfNeeded (x : VarId) (expected : IRType) (k : VarId → M FnBody) : M FnBody := do let xType ← getVarType x if eqvTypes xType expected then k x else let y ← M.mkFresh let v ← mkCast x xType expected FnBody.vdecl y expected v <$> k y @[inline] def castArgIfNeeded (x : Arg) (expected : IRType) (k : Arg → M FnBody) : M FnBody := match x with | Arg.var x => castVarIfNeeded x expected (fun x => k (Arg.var x)) | _ => k x @[specialize] def castArgsIfNeededAux (xs : Array Arg) (typeFromIdx : Nat → IRType) : M (Array Arg × Array FnBody) := do let mut xs' := #[] let mut bs := #[] let mut i := 0 for x in xs do let expected := typeFromIdx i match x with | Arg.irrelevant => xs' := xs'.push x | Arg.var x => let xType ← getVarType x if eqvTypes xType expected then xs' := xs'.push (Arg.var x) else let y ← M.mkFresh let v ← mkCast x xType expected let b := FnBody.vdecl y expected v FnBody.nil xs' := xs'.push (Arg.var y) bs := bs.push b i := i + 1 return (xs', bs) @[inline] def castArgsIfNeeded (xs : Array Arg) (ps : Array Param) (k : Array Arg → M FnBody) : M FnBody := do let (ys, bs) ← castArgsIfNeededAux xs fun i => ps[i].ty let b ← k ys pure (reshape bs b) @[inline] def boxArgsIfNeeded (xs : Array Arg) (k : Array Arg → M FnBody) : M FnBody := do let (ys, bs) ← castArgsIfNeededAux xs (fun _ => IRType.object) let b ← k ys pure (reshape bs b) def unboxResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody := do if ty.isScalar then let y ← M.mkFresh pure $ FnBody.vdecl y IRType.object e (FnBody.vdecl x ty (Expr.unbox y) b) else pure $ FnBody.vdecl x ty e b def castResultIfNeeded (x : VarId) (ty : IRType) (e : Expr) (eType : IRType) (b : FnBody) : M FnBody := do if eqvTypes ty eType then pure $ FnBody.vdecl x ty e b else let y ← M.mkFresh let v ← mkCast y eType ty pure $ FnBody.vdecl y eType e (FnBody.vdecl x ty v b) def visitVDeclExpr (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : M FnBody := match e with | Expr.ctor c ys => if c.isScalar && ty.isScalar then pure $ FnBody.vdecl x ty (Expr.lit (LitVal.num c.cidx)) b else boxArgsIfNeeded ys fun ys => pure $ FnBody.vdecl x ty (Expr.ctor c ys) b | Expr.reuse w c u ys => boxArgsIfNeeded ys fun ys => pure $ FnBody.vdecl x ty (Expr.reuse w c u ys) b | Expr.fap f ys => do let decl ← getDecl f castArgsIfNeeded ys decl.params fun ys => castResultIfNeeded x ty (Expr.fap f ys) decl.resultType b | Expr.pap f ys => do let env ← getEnv let decl ← getDecl f let f := if requiresBoxedVersion env decl then mkBoxedName f else f boxArgsIfNeeded ys fun ys => pure $ FnBody.vdecl x ty (Expr.pap f ys) b | Expr.ap f ys => boxArgsIfNeeded ys fun ys => unboxResultIfNeeded x ty (Expr.ap f ys) b | other => pure $ FnBody.vdecl x ty e b partial def visitFnBody : FnBody → M FnBody | FnBody.vdecl x t v b => do let b ← withVDecl x t v (visitFnBody b) visitVDeclExpr x t v b | FnBody.jdecl j xs v b => do let v ← withParams xs (visitFnBody v) let b ← withJDecl j xs v (visitFnBody b) pure $ FnBody.jdecl j xs v b | FnBody.uset x i y b => do let b ← visitFnBody b castVarIfNeeded y IRType.usize fun y => pure $ FnBody.uset x i y b | FnBody.sset x i o y ty b => do let b ← visitFnBody b castVarIfNeeded y ty fun y => pure $ FnBody.sset x i o y ty b | FnBody.mdata d b => FnBody.mdata d <$> visitFnBody b | FnBody.case tid x _ alts => do let expected := getScrutineeType alts let alts ← alts.mapM fun alt => alt.mmodifyBody visitFnBody castVarIfNeeded x expected fun x => do pure $ FnBody.case tid x expected alts | FnBody.ret x => do let expected ← getResultType castArgIfNeeded x expected (fun x => pure $ FnBody.ret x) | FnBody.jmp j ys => do let ps ← getJPParams j castArgsIfNeeded ys ps fun ys => pure $ FnBody.jmp j ys | other => pure other def run (env : Environment) (decls : Array Decl) : Array Decl := let ctx : BoxingContext := { decls := decls, env := env } let decls := decls.foldl (init := #[]) fun newDecls decl => match decl with | Decl.fdecl f xs t b => let nextIdx := decl.maxIndex + 1 let (b, s) := (withParams xs (visitFnBody b) { ctx with f := f, resultType := t }).run { nextIdx := nextIdx } let newDecls := newDecls ++ s.auxDecls let newDecl := Decl.fdecl f xs t b let newDecl := newDecl.elimDead newDecls.push newDecl | d => newDecls.push d addBoxedVersions env decls end ExplicitBoxing def explicitBoxing (decls : Array Decl) : CompilerM (Array Decl) := do let env ← getEnv pure $ ExplicitBoxing.run env decls end Lean.IR
3260bcd109c5657d9ca2b14e7de25f72cce98520
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Meta/Tactic/Induction.lean
e3182050c1013ea3795d0f75fad9a2a759a04faa
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,622
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.RecursorInfo import Lean.Meta.SynthInstance import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean.Meta private partial def getTargetArity : Expr → Nat | Expr.mdata _ b _ => getTargetArity b | Expr.forallE _ _ b _ => getTargetArity b + 1 | e => if e.isHeadBetaTarget then getTargetArity e.headBeta else 0 private def addRecParams (mvarId : MVarId) (majorTypeArgs : Array Expr) : List (Option Nat) → Expr → MetaM Expr | [], recursor => pure recursor | some pos :: rest, recursor => if h : pos < majorTypeArgs.size then addRecParams mvarId majorTypeArgs rest (mkApp recursor (majorTypeArgs.get ⟨pos, h⟩)) else throwTacticEx `induction mvarId "ill-formed recursor" | none :: rest, recursor => do let recursorType ← inferType recursor let recursorType ← whnfForall recursorType match recursorType with | Expr.forallE _ d _ _ => do let param ← try synthInstance d catch _ => throwTacticEx `induction mvarId "failed to generate type class instance parameter" addRecParams mvarId majorTypeArgs rest (mkApp recursor param) | _ => throwTacticEx `induction mvarId "ill-formed recursor" structure InductionSubgoal := (mvarId : MVarId) (fields : Array Expr := #[]) (subst : FVarSubst := {}) instance : Inhabited InductionSubgoal := ⟨{ mvarId := arbitrary _ }⟩ private def getTypeBody (mvarId : MVarId) (type : Expr) (x : Expr) : MetaM Expr := do let type ← whnfForall type match type with | Expr.forallE _ _ b _ => pure $ b.instantiate1 x | _ => throwTacticEx `induction mvarId "ill-formed recursor" private partial def finalize (mvarId : MVarId) (givenNames : Array (List Name)) (recursorInfo : RecursorInfo) (reverted : Array FVarId) (major : Expr) (indices : Array Expr) (baseSubst : FVarSubst) (recursor : Expr) : MetaM (Array InductionSubgoal) := do let target ← getMVarType mvarId let initialArity := getTargetArity target let recursorType ← inferType recursor let numMinors := recursorInfo.produceMotive.length let rec loop (pos : Nat) (minorIdx : Nat) (recursor recursorType : Expr) (consumedMajor : Bool) (subgoals : Array InductionSubgoal) := do let recursorType ← whnfForall recursorType if recursorType.isForall && pos < recursorInfo.numArgs then if pos == recursorInfo.firstIndexPos then let (recursor, recursorType) ← indices.foldlM (init := (recursor, recursorType)) fun (recursor, recursorType) index => do let recursor := mkApp recursor index let recursorType ← getTypeBody mvarId recursorType index pure (recursor, recursorType) let recursor := mkApp recursor major let recursorType ← getTypeBody mvarId recursorType major loop (pos+1+indices.size) minorIdx recursor recursorType true subgoals else -- consume motive let tag ← getMVarTag mvarId if minorIdx ≥ numMinors then throwTacticEx `induction mvarId "ill-formed recursor" match recursorType with | Expr.forallE n d b c => let d := d.headBeta -- Remark is givenNames is not empty, then user provided explicit alternatives for each minor premise if c.binderInfo.isInstImplicit && givenNames.isEmpty then match (← synthInstance? d) with | some inst => let recursor := mkApp recursor inst let recursorType ← getTypeBody mvarId recursorType inst loop (pos+1) (minorIdx+1) recursor recursorType consumedMajor subgoals | none => do -- Add newSubgoal if type class resolution failed let mvar ← mkFreshExprSyntheticOpaqueMVar d (tag ++ n) let recursor := mkApp recursor mvar let recursorType ← getTypeBody mvarId recursorType mvar loop (pos+1) (minorIdx+1) recursor recursorType consumedMajor (subgoals.push { mvarId := mvar.mvarId! }) else let arity := getTargetArity d if arity < initialArity then throwTacticEx `induction mvarId "ill-formed recursor" let nparams := arity - initialArity -- number of fields due to minor premise let nextra := reverted.size - indices.size - 1 -- extra dependencies that have been reverted let minorGivenNames := if h : minorIdx < givenNames.size then givenNames.get ⟨minorIdx, h⟩ else [] let mvar ← mkFreshExprSyntheticOpaqueMVar d (tag ++ n) let recursor := mkApp recursor mvar let recursorType ← getTypeBody mvarId recursorType mvar -- Try to clear major premise from new goal let mvarId' ← tryClear mvar.mvarId! major.fvarId! let (fields, mvarId') ← introN mvarId' nparams minorGivenNames let (extra, mvarId') ← introNP mvarId' nextra let subst := reverted.size.fold (init := baseSubst) fun i (subst : FVarSubst) => if i < indices.size + 1 then subst else let revertedFVarId := reverted[i] let newFVarId := extra[i - indices.size - 1] subst.insert revertedFVarId (mkFVar newFVarId) let fields := fields.map mkFVar loop (pos+1) (minorIdx+1) recursor recursorType consumedMajor (subgoals.push { mvarId := mvarId', fields := fields, subst := subst }) | _ => unreachable! else unless consumedMajor do throwTacticEx `induction mvarId "ill-formed recursor" assignExprMVar mvarId recursor pure subgoals loop (recursorInfo.paramsPos.length + 1) 0 recursor recursorType false #[] private def throwUnexpectedMajorType {α} (mvarId : MVarId) (majorType : Expr) : MetaM α := throwTacticEx `induction mvarId msg!"unexpected major premise type{indentExpr majorType}" def induction (mvarId : MVarId) (majorFVarId : FVarId) (recursorName : Name) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array InductionSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `induction let majorLocalDecl ← getLocalDecl majorFVarId let recursorInfo ← mkRecursorInfo recursorName let some majorType ← whnfUntil majorLocalDecl.type recursorInfo.typeName | throwUnexpectedMajorType mvarId majorLocalDecl.type majorType.withApp fun _ majorTypeArgs => do recursorInfo.paramsPos.forM fun paramPos? => do match paramPos? with | none => pure () | some paramPos => if paramPos ≥ majorTypeArgs.size then throwTacticEx `induction mvarId msg!"major premise type is ill-formed{indentExpr majorType}" let mctx ← getMCtx let indices ← recursorInfo.indicesPos.toArray.mapM fun idxPos => do if idxPos ≥ majorTypeArgs.size then throwTacticEx `induction mvarId msg!"major premise type is ill-formed{indentExpr majorType}" let idx := majorTypeArgs.get! idxPos unless idx.isFVar do throwTacticEx `induction mvarId msg!"major premise type index {idx} is not a variable{indentExpr majorType}" majorTypeArgs.size.forM fun i => do let arg := majorTypeArgs[i] if i != idxPos && arg == idx then throwTacticEx `induction mvarId msg!"'{idx}' is an index in major premise, but it occurs more than once{indentExpr majorType}" if i < idxPos && mctx.exprDependsOn arg idx.fvarId! then throwTacticEx `induction mvarId msg!"'{idx}' is an index in major premise, but it occurs in previous arguments{indentExpr majorType}" -- If arg is also and index and a variable occurring after `idx`, we need to make sure it doesn't depend on `idx`. -- Note that if `arg` is not a variable, we will fail anyway when we visit it. if i > idxPos && recursorInfo.indicesPos.contains i && arg.isFVar then let idxDecl ← getLocalDecl idx.fvarId! if mctx.localDeclDependsOn idxDecl arg.fvarId! then throwTacticEx `induction mvarId msg!"'{idx}' is an index in major premise, but it depends on index occurring at position #{i+1}" pure idx let target ← getMVarType mvarId if !recursorInfo.depElim && mctx.exprDependsOn target majorFVarId then throwTacticEx `induction mvarId msg!"recursor '{recursorName}' does not support dependent elimination, but conclusion depends on major premise" -- Revert indices and major premise preserving variable order let (reverted, mvarId) ← revert mvarId ((indices.map Expr.fvarId!).push majorFVarId) true -- Re-introduce indices and major let (indices', mvarId) ← introNP mvarId indices.size let (majorFVarId', mvarId) ← intro1P mvarId -- Create FVarSubst with indices let baseSubst := do let mut subst : FVarSubst := {} let mut i := 0 for index in indices do subst := subst.insert index.fvarId! (mkFVar indices'[i]) i := i + 1 pure subst trace[Meta.Tactic.induction]! "after revert&intro\n{MessageData.ofGoal mvarId}" -- Update indices and major let indices := indices'.map mkFVar let majorFVarId := majorFVarId' let major := mkFVar majorFVarId withMVarContext mvarId do let target ← getMVarType mvarId let targetLevel ← getLevel target let targetLevel ← normalizeLevel targetLevel let majorLocalDecl ← getLocalDecl majorFVarId let some majorType ← whnfUntil majorLocalDecl.type recursorInfo.typeName | throwUnexpectedMajorType mvarId majorLocalDecl.type majorType.withApp fun majorTypeFn majorTypeArgs => do match majorTypeFn with | Expr.const majorTypeFnName majorTypeFnLevels _ => do let majorTypeFnLevels := majorTypeFnLevels.toArray let (recursorLevels, foundTargetLevel) ← recursorInfo.univLevelPos.foldlM (init := (#[], false)) fun (recursorLevels, foundTargetLevel) (univPos : RecursorUnivLevelPos) => do match univPos with | RecursorUnivLevelPos.motive => pure (recursorLevels.push targetLevel, true) | RecursorUnivLevelPos.majorType idx => if idx ≥ majorTypeFnLevels.size then throwTacticEx `induction mvarId "ill-formed recursor" pure (recursorLevels.push (majorTypeFnLevels.get! idx), foundTargetLevel) if !foundTargetLevel && !targetLevel.isZero then throwTacticEx `induction mvarId msg!"recursor '{recursorName}' can only eliminate into Prop" let recursor := mkConst recursorName recursorLevels.toList let recursor ← addRecParams mvarId majorTypeArgs recursorInfo.paramsPos recursor -- Compute motive let motive := target let motive ← if recursorInfo.depElim then mkLambdaFVars #[major] motive else pure motive let motive ← mkLambdaFVars indices motive let recursor := mkApp recursor motive finalize mvarId givenNames recursorInfo reverted major indices baseSubst recursor | _ => throwTacticEx `induction mvarId "major premise is not of the form (C ...)" builtin_initialize registerTraceClass `Meta.Tactic.induction end Lean.Meta
ba89c2e9352e9dd4a5443c0675ffe2c2522e1c73
1437b3495ef9020d5413178aa33c0a625f15f15f
/analysis/normed_space.lean
bf505e3f8e0f9b41ec22b400b5c6b1ce0ab07256
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,897
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import analysis.nnreal variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter local notation f `→_{`:50 a `}`:0 b := tendsto f (nhds a) (nhds b) lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) := begin apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0; simp [*]; exact filter.univ_mem_sets end class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_pos_iff (g : α) : ∥ g ∥ > 0 ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by rw ←norm_neg; simp section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group [normed_group β] : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : α → Type*} [fintype α] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma lim_norm (x : α) : ((λ g, ∥g - x∥) : α → ℝ) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_tendsto.1 continuous_id x) lemma lim_norm_zero : ((λ g, ∥g∥) : α → ℝ) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous ((λ g, ∥g∥) : α → ℝ) := begin rw continuous_iff_tendsto, intro x, rw tendsto_iff_dist_tendsto_zero, exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end instance normed_top_monoid : topological_add_monoid α := ⟨continuous_iff_tendsto.2 $ λ ⟨x₁, x₂⟩, tendsto_iff_norm_tendsto_zero.2 begin refine squeeze_zero (by simp) _ (by simpa using tendsto_add (lim_norm (x₁, x₂)) (lim_norm (x₁, x₂))), exact λ ⟨e₁, e₂⟩, calc ∥(e₁ + e₂) - (x₁ + x₂)∥ = ∥(e₁ - x₁) + (e₂ - x₂)∥ : by simp ... ≤ ∥e₁ - x₁∥ + ∥e₂ - x₂∥ : norm_triangle _ _ ... ≤ max (∥e₁ - x₁∥) (∥e₂ - x₂∥) + max (∥e₁ - x₁∥) (∥e₂ - x₂∥) : add_le_add (le_max_left _ _) (le_max_right _ _) end⟩ instance normed_top_group : topological_add_group α := ⟨continuous_iff_tendsto.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 begin have : ∀ (e : α), ∥-e - -x∥ = ∥e - x∥, { intro, simpa using norm_neg (e - x) }, rw funext this, exact lim_norm x, end⟩ end normed_group section normed_ring 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) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, n > 0 → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) instance prod.normed_ring [normed_ring α] [normed_ring β] : 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 (x.1) (y.1)) (norm_mul (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.normed_group } end normed_ring instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_tendsto.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_triangle }, { rw ←zero_add (0 : ℝ), apply tendsto_add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul }, { rw ←mul_zero (∥x.fst∥), apply tendsto_mul, { apply continuous_iff_tendsto.1, apply continuous.comp, { apply continuous_fst }, { apply continuous_norm }}, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_tendsto.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul }, { rw ←zero_mul (∥x.snd∥), apply tendsto_mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_tendsto.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_tendsto.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ section normed_field class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) = norm a * norm b) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul], ..i } @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma normed_field.norm_pow {α : Type*} [normed_field α] (a : α) : ∀ n : ℕ, ∥a^n∥ = ∥a∥^n | 0 := by simp | (k+1) := calc ∥a ^ (k + 1)∥ = ∥a*(a^k)∥ : rfl ... = ∥a∥*∥a^k∥ : by rw normed_field.norm_mul ... = ∥a∥ ^ (k + 1) : by rw normed_field.norm_pow; simp [pow, monoid.pow] instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul := abs_mul } lemma real.norm_eq_abs (r : ℝ): norm r = abs r := rfl end normed_field section normed_space class normed_space (α : out_param $ Type*) (β : Type*) [out_param $ normed_field α] extends normed_group β, vector_space α β := (norm_smul : ∀ a b, norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] instance normed_field.to_normed_space : normed_space α α := { dist_eq := normed_field.dist_eq, norm_smul := normed_field.norm_mul } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp limg (continuous_iff_tendsto.1 continuous_norm _), have lim1 : tendsto (λ x, ∥f x - s∥ * ∥g x∥) e (nhds 0), by simpa using tendsto_mul limf' limg', have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 : tendsto (λ x, ∥s∥ * ∥g x - b∥) e (nhds 0), by simpa using tendsto_mul tendsto_const_nhds limg3, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, exact calc ∥s • (x₁, x₂)∥ = ∥ (s • x₁, s• x₂)∥ : rfl ... = max (∥s • x₁∥) (∥ s• x₂∥) : rfl ... = max (∥s∥ * ∥x₁∥) (∥s∥ * ∥x₂∥) : by simp [norm_smul s x₁, norm_smul s x₂] ... = ∥s∥ * max (∥x₁∥) (∥x₂∥) : by simp [mul_max_of_nonneg] end, add_smul := by simp[add_smul], -- I have no idea why by simp[smul_add] is not enough for the next goal smul_add := assume r x y, show (r•(x+y).fst, r•(x+y).snd) = (r•x.fst+r•y.fst, r•x.snd+r•y.snd), by simp[smul_add], ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {ι : Type*} {E : ι → Type*} [fintype ι] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm := λf, ((finset.univ.sup (λb, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume f g, congr_arg coe $ congr_arg (finset.sup finset.univ) $ by funext i; exact nndist_eq_nnnorm _ _, norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul], ..metric_space_pi, ..pi.vector_space α } end normed_space
6b3a5ab18783b67fefd471f49b51d60af2430570
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Elab/Match.lean
e20fe28289ee2d708f19f5e222c3d97d1fb5e78c
[ "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
39,511
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.MatchPatternAttr import Lean.Meta.Match.Match import Lean.Elab.SyntheticMVars import Lean.Elab.App import Lean.Parser.Term namespace Lean.Elab.Term open Meta open Lean.Parser.Term /- This modules assumes "match"-expressions use the following syntax. ```lean def matchDiscr := parser! optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView where ref : Syntax patterns : Array Syntax rhs : Syntax deriving Inhabited private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def expandSimpleMatchWithType (stx discr lhsVar type rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar : $type := $discr; $rhs) withMacroExpansion stx newStx $ elabTerm newStx expectedType? private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq $ elabTermEnsuringType discrStx[1] d trace[Elab.match]! "discr #{i} {discr} : {d}" matchType ← b.instantiate1 discr discrs := discrs.push discr | _ => throwError! "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected" pure discrs private def mkUserNameFor (e : Expr) : TermElabM Name := match e with | Expr.fvar fvarId _ => do pure (← getLocalDecl fvarId).userName | _ => mkFreshBinderName -- `expandNonAtomicDiscrs?` create auxiliary variables with base name `_discr` private def isAuxDiscrName (n : Name) : Bool := n.eraseMacroScopes == `_discr -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] match (← isLocalIdent? term) with | some e@(Expr.fvar fvarId _) => let localDecl ← getLocalDecl fvarId if !isAuxDiscrName localDecl.userName then pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?` else pure localDecl.value | _ => throwErrorAt discr "unexpected discriminant" private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM (Array Expr × Expr × Array MatchAltView) := do let numDiscrs := discrStxs.size if matchOptType.isNone then let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (matchAltViews : Array MatchAltView) := do match i with | 0 => pure (discrs.reverse, matchType, matchAltViews) | i+1 => let discrStx := discrStxs[i] let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let discrType ← inferType discr let discrType ← instantiateMVars discrType let matchTypeBody ← kabstract matchType discr let userName ← mkUserNameFor discr if discrStx[0].isNone then loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) matchAltViews else let identStx := discrStx[0][0] withLocalDeclD userName discrType fun x => do let eqType ← mkEq discr x withLocalDeclD identStx.getId eqType fun h => do let matchTypeBody := matchTypeBody.instantiate1 x let matchType ← mkForallFVars #[x, h] matchTypeBody let refl ← mkEqRefl discr let discrs := (discrs.push refl).push discr let matchAltViews := matchAltViews.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx } loop i discrs matchType matchAltViews loop discrStxs.size #[] expectedType matchAltViews else let matchTypeStx := matchOptType[0][1] let matchType ← elabType matchTypeStx let discrs ← elabDiscrsWitMatchType discrStxs matchType expectedType pure (discrs, matchType, matchAltViews) def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } /- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $discrs,* $[: $ty?]? with $alts:matchAlt*) => alts.map fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => { ref := alt, patterns := patterns, rhs := rhs } | _ => unreachable! | _ => unreachable! /-- Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and `_` in patterns. -/ def mkInaccessible (e : Expr) : Expr := mkAnnotation `_inaccessible e def inaccessible? (e : Expr) : Option Expr := annotation? `_inaccessible e inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId pure $ Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ private def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind /-- The elaboration function for `Syntax` created using `mkMVarSyntax`. It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/ @[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? => pure $ mkInaccessible $ mkMVar (getMVarSyntaxMVarId stx) @[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? pure $ mkInaccessible e /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" namespace CtorApp /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array LocalDecl paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) pure $ Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.binderInfo.isExplicit else false private def getNextParam (ctx : Context) : LocalDecl × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def pushNewArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := match arg with | Arg.stx stx => do let stx ← if accessible then collect stx else pure stx pure { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! private def processExplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := match ctx.args with | [] => if ctx.ellipsis then do let hole ← `(_) pushNewArg collect accessible ctx (Arg.stx hole) else throwError! "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => do let ctx := { ctx with args := args } pushNewArg collect accessible ctx arg private def processImplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context := if ctx.explicit then processExplicitArg collect accessible ctx else do let hole ← `(_) pushNewArg collect accessible ctx (Arg.stx hole) private partial def processCtorAppAux (collect : Syntax → M Syntax) (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.userName with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg collect accessible ctx arg.val processCtorAppAux collect ctx | none => let ctx ← match d.binderInfo with | BinderInfo.implicit => processImplicitArg collect accessible ctx | BinderInfo.instImplicit => processImplicitArg collect accessible ctx | _ => processExplicitArg collect accessible ctx processCtorAppAux collect ctx def processCtorApp (collect : Syntax → M Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" | throwCtorExpected let fInfo ← getConstInfo fName forallTelescopeReducing fInfo.type fun xs _ => do let paramDecls ← xs.mapM (getFVarLocalDecl ·) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => let env ← getEnv if hasMatchPatternAttribute env fName then processCtorAppAux collect { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected end CtorApp def processCtorApp (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← liftM $ expandApp stx true CtorApp.processCtorApp collect f namedArgs args ellipsis def processCtor (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do CtorApp.processCtorApp collect stx #[] #[] false private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" let s ← get if s.found.contains id then throwError! "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } pure idStx /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ private def processId (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do let env ← getEnv match (← resolveId? stx "pattern") with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match env.find? fName with | some (ConstantInfo.ctorInfo _) => processCtor collect stx | some _ => if hasMatchPatternAttribute env fName then processCtor collect stx else processVar stx | none => throwCtorExpected | _ => processVar stx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax partial def collect : Syntax → M Syntax | stx@(Syntax.node k args) => withRef stx $ withFreshMacroScope do if k == `Lean.Parser.Term.app then processCtorApp collect stx else if k == `Lean.Parser.Term.anonymousCtor then let elems ← args[1].getArgs.mapSepElemsM collect pure $ Syntax.node k (args.set! 1 $ mkNullNode elems) else if k == `Lean.Parser.Term.structInst then /- ``` parser! "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := args[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← args[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- parser! structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field pure <| Syntax.node k (args.set! 2 <| mkNullNode fields) else if k == `Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push $ PatternVar.anonymousVar $ getMVarSyntaxMVarId r } pure r else if k == `Lean.Parser.Term.paren then let arg := args[1] if arg.isNone then pure stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == `Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t pure $ Syntax.node k (args.set! 1 arg) else -- Tuple literal is a constructor let t ← collect t let arg := arg.setArg 0 t let tupleTail := s[0] let tupleTailElems := tupleTail[1].getArgs let tupleTailElems ← tupleTailElems.mapSepElemsM collect let tupleTail := tupleTail.setArg 1 $ mkNullNode tupleTailElems let s := s.setArg 0 tupleTail let arg := arg.setArg 1 s pure $ Syntax.node k (args.set! 1 arg) else if k == `Lean.Parser.Term.explicitUniv then processCtor collect stx[0] else if k == `Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> tparser! "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == `Lean.Parser.Term.inaccessible then pure stx else if k == strLitKind then pure stx else if k == numLitKind then pure stx else if k == scientificLitKind then pure stx else if k == charLitKind then pure stx else if k == `Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern | stx@(Syntax.ident _ _ _ _) => processId collect stx | stx => throwInvalidPattern def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match]! "collecting variables at pattern: {p}" collect p pure { alt with patterns := patterns } end CollectPatternVars private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} pure (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM $ expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} pure s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM $ expandMacros pattern) let (_, s) ← collect.run {} pure s.vars /- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ inductive PatternVarDecl where /- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable when it is not assigned during pattern elaboration. -/ | anonymousVar (mvarId : MVarId) (fvarId : FVarId) | localVar (fvarId : FVarId) private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) := do if h : i < pVars.size then match pVars.get ⟨i, h⟩ with | PatternVar.anonymousVar mvarId => let type ← mkFreshTypeMVar let userName ← mkFreshBinderName withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!)) | PatternVar.localVar userName => let type ← mkFreshTypeMVar withLocalDecl userName BinderInfo.default type fun x => loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!)) else /- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`. Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/ decls.forM fun decl => match decl with | PatternVarDecl.anonymousVar mvarId fvarId => do let type ← inferType (mkFVar fvarId) discard <| mkFreshExprMVarWithId mvarId type | _ => pure () k decls loop 0 #[] private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : TermElabM (Array Expr × Expr) := do let mut patterns := #[] let mut matchType := matchType for patternStx in patternStxs do matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← elabTermEnsuringType patternStx d matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" pure (patterns, matchType) def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do let mut decls := #[] for pdecl in patternVarDecls do match pdecl with | PatternVarDecl.localVar fvarId => let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | PatternVarDecl.anonymousVar mvarId fvarId => let e ← instantiateMVars (mkMVar mvarId); trace[Elab.match]! "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}" match e with | Expr.mvar newMVarId _ => /- Metavariable was not assigned, or assigned to another metavariable. So, we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/ assignExprMVar newMVarId (mkFVar fvarId) trace[Elab.match]! "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}" let decl ← getLocalDecl fvarId let decl ← instantiateLocalDeclMVars decl decls := decls.push decl | _ => pure () pure decls open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern structure State where found : NameSet := {} localDecls : Array LocalDecl newLocals : NameSet := {} abbrev M := StateRefT State TermElabM private def alreadyVisited (fvarId : FVarId) : M Bool := do let s ← get pure $ s.found.contains fvarId private def markAsVisited (fvarId : FVarId) : M Unit := modify fun s => { s with found := s.found.insert fvarId } private def throwInvalidPattern {α} (e : Expr) : M α := throwError! "invalid pattern {indentExpr e}" /- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/ private def mkLocalDeclFor (mvar : Expr) : M Pattern := do let mvarId := mvar.mvarId! let s ← get match (← getExprMVarAssignment? mvarId) with | some val => pure $ Pattern.inaccessible val | none => let fvarId ← mkFreshId let type ← inferType mvar /- HACK: `fvarId` is not in the scope of `mvarId` If this generates problems in the future, we should update the metavariable declarations. -/ assignExprMVar mvarId (mkFVar fvarId) let userName ← liftM $ mkFreshBinderName let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default; modify fun s => { s with newLocals := s.newLocals.insert fvarId, localDecls := match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with | none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar` | some i => s.localDecls.insertAt i newDecl } pure $ Pattern.var fvarId partial def main (e : Expr) : M Pattern := do let isLocalDecl (fvarId : FVarId) : M Bool := do let s ← get pure $ s.localDecls.any fun d => d.fvarId == fvarId let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do if (← alreadyVisited fvarId) then pure $ Pattern.inaccessible e else markAsVisited fvarId pure $ Pattern.var e.fvarId! let mkInaccessible (e : Expr) : M Pattern := do match e with | Expr.fvar fvarId _ => if (← isLocalDecl fvarId) then mkPatternVar fvarId e else pure $ Pattern.inaccessible e | _ => pure $ Pattern.inaccessible e match inaccessible? e with | some t => mkInaccessible t | none => match e.arrayLit? with | some (α, lits) => let ps ← lits.mapM main; pure $ Pattern.arrayLit α ps | none => if e.isAppOfArity `namedPattern 3 then let p ← main $ e.getArg! 2; match e.getArg! 1 with | Expr.fvar fvarId _ => pure $ Pattern.as fvarId p | _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if e.isNatLit || e.isStringLit || e.isCharLit then pure $ Pattern.val e else if e.isFVar then let fvarId := e.fvarId! unless(← isLocalDecl fvarId) do throwInvalidPattern e mkPatternVar fvarId e else if e.isMVar then mkLocalDeclFor e else let newE ← whnf e if newE != e then main newE else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM main pure $ Pattern.ctor v.name us params.toList fields.toList end ToDepElimPattern def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls } let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d /- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/ let lctx ← getLCtx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) $ k localDecls patterns private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : TermElabM α := do let (patterns, matchType) ← withSynthesize $ elabPatterns patternStxs matchType let localDecls ← finalizePatternDecls patternVarDecls let patterns ← patterns.mapM (instantiateMVars ·) withDepElimPatterns localDecls patterns fun localDecls patterns => k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match]! "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do let rhs ← elabTermEnsuringType alt.rhs matchType let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr let rhs ← if xs.isEmpty then pure $ mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match]! "rhs: {rhs}" pure (altLHS, rhs) def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult := liftMetaM $ Meta.Match.mkMatcher elimName matchType numDiscrs lhss register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| throwError! "missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr) : TermElabM Expr := do let (discrs, matchType, altLHSS, rhss) ← commitIfDidNotPostpone do let (discrs, matchType, altViews) ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType let matchAlts ← liftMacroM $ expandMacrosInPatterns altViews trace[Elab.match]! "matchType: {matchType}" let alts ← matchAlts.mapM $ fun alt => elabMatchAltView alt matchType /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if p.hasExprMVar then withExistingLocalDecls altLHS.fvarDecls do tryPostpone throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, rhss) let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType reportMatcherResultErrors altLHSS matcherResult let r := mkApp matcherResult.matcher motive let r := mkAppN r discrs let r := mkAppN r rhss trace[Elab.match]! "result: {r}" pure r private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[1].getSepArgs private def getMatchOptType (matchStx : Syntax) : Syntax := matchStx[2] private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptType := getMatchOptType matchStx; if matchOptType.isNone then do let discrs := getDiscrs matchStx; let allLocal ← discrs.allM fun discr => Option.isSome <$> isLocalIdent? discr[1] if allLocal then pure none else let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", "); pure (matchStx.setArg 1 discrs) | discr :: discrs => -- Recall that -- matchDiscr := parser! optional (ident >> ":") >> termParser let term := discr[1] match (← isLocalIdent? term) with | some _ => loop discrs (discrsNew.push discr) | none => withFreshMacroScope do let d ← `(_discr); unless isAuxDiscrName d.getId do -- Use assertion? throwError "unexpected internal auxiliary discriminant name" let discrNew := discr.setArg 1 d; let r ← loop discrs (discrsNew.push discrNew) `(let _discr := $term; $r) pure (some (← loop discrs.toList #[])) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user pure none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptType matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] match (← isLocalIdent? term) with | none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs? | some d => let dType ← inferType d trace[Elab.match]! "discr {d} : {dType}" tryPostponeIfMVar dType /- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let _discr := g x match _discr with | ... => ... ``` Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`. Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`. This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar /- ``` parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let altViews := getMatchAlts stx let matchOptType := getMatchOptType stx elabMatchAux discrStxs altViews matchOptType expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => isAtomicIdent stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | _ => isAtomicIdent stx | _ => isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic -- parser! "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts @[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | `(match $discr:term : $type with | $y:ident => $rhs:term) => if (← isPatternVar y) then expandSimpleMatchWithType stx discr y type rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx; let matchOptType := getMatchOptType stx; if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? @[builtinInit] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.match; pure () -- parser!:leadPrec "nomatch " >> termParser @[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => match stx with | `(nomatch $discrExpr) => do let expectedType ← waitExpectedType expectedType? let discr := Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux #[discr] #[] mkNullNode expectedType | _ => throwUnsupportedSyntax end Lean.Elab.Term
893ffe4ea984deb7299023a2a4d66ac3d1a348ad
26b290e100179c46233060ff9972c0758106c196
/src/mini_crush/default.lean
a7bfc50c1b949896c2c7cf20f5f817f8807ae34d
[]
no_license
seanpm2001/LeanProver_Mini_Crush
f95f9e06230b171dd84cc49808f5b2f8378c5e03
cea4166b1b2970fba47907798e7fe0511e426cfd
refs/heads/master
1,688,908,222,650
1,547,825,246,000
1,547,825,246,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,780
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 We implement a crush-like strategy using simplifier, SMT gadgets, and robust simplifier. This is just a demo. -/ declare_trace mini_crush namespace mini_crush open tactic meta def size (e : expr) : nat := e.fold 1 (λ e _ n, n+1) /- Collect relevant functions -/ meta def is_auto_construction : name → bool | (name.mk_string "brec_on" p) := tt | (name.mk_string "cases_on" p) := tt | (name.mk_string "rec_on" p) := tt | (name.mk_string "no_confusion" p) := tt | (name.mk_string "below" p) := tt | _ := ff meta def is_relevant_fn (n : name) : tactic bool := do env ← get_env, if ¬env.is_definition n ∨ is_auto_construction n then return ff else if env.in_current_file n then return tt else in_open_namespaces n meta def collect_revelant_fns_aux : name_set → expr → tactic name_set | s e := e.mfold s $ λ t _ s, match t with | expr.const c _ := if s.contains c then return s else mcond (is_relevant_fn c) (do new_s ← return $ if c.is_internal then s else s.insert c, d ← get_decl c, collect_revelant_fns_aux new_s d.value) (return s) | _ := return s end meta def collect_revelant_fns : tactic name_set := do ctx ← local_context, s₁ ← ctx.mfoldl (λ s e, infer_type e >>= collect_revelant_fns_aux s) mk_name_set, target >>= collect_revelant_fns_aux s₁ meta def add_relevant_eqns (s : simp_lemmas) : tactic simp_lemmas := do fns ← collect_revelant_fns, fns.mfold s (λ fn s, get_eqn_lemmas_for tt fn >>= mfoldl simp_lemmas.add_simp s) meta def add_relevant_eqns_h (hs : hinst_lemmas) : tactic hinst_lemmas := do fns ← collect_revelant_fns, fns.mfold hs (λ fn hs, get_eqn_lemmas_for tt fn >>= mfoldl (λ hs d, hs.add <$> hinst_lemma.mk_from_decl d) hs) /- Collect terms that are inductive datatypes -/ meta def is_inductive (e : expr) : tactic bool := do type ← infer_type e, C ← return type.get_app_fn, env ← get_env, return $ C.is_constant && env.is_inductive C.const_name meta def collect_inductive_aux : expr_set → expr → tactic expr_set | S e := if S.contains e then return S else do new_S ← mcond (is_inductive e) (return $ S.insert e) (return S), match e with | expr.app _ _ := fold_explicit_args e new_S collect_inductive_aux | expr.pi _ _ d b := if e.is_arrow then collect_inductive_aux S d >>= flip collect_inductive_aux b else return new_S | _ := return new_S end meta def collect_inductive : expr → tactic expr_set := collect_inductive_aux mk_expr_set meta def collect_inductive_from_target : tactic (list expr) := do S ← target >>= collect_inductive, return $ list.qsort (λ e₁ e₂, size e₁ < size e₂) $ S.to_list meta def collect_inductive_hyps : tactic (list expr) := local_context >>= mfoldl (λ r h, mcond (is_inductive h) (return $ h::r) (return r)) [] /- Induction -/ meta def try_induction_aux (cont : expr → tactic unit) : list expr → tactic unit | [] := failed | (e::es) := (step (induction e); cont e; done) <|> try_induction_aux es meta def try_induction (cont : expr → tactic unit) : tactic unit := focus1 $ collect_inductive_hyps >>= try_induction_aux cont /- Trace messages -/ meta def report {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := when_tracing `mini_crush $ trace a meta def report_failure (s : name) (e : option expr := none) : tactic unit := when_tracing `mini_crush $ match e with | none := trace ("FAILED '" ++ to_string s ++ "' at") | some e := (do p ← pp e, trace (to_fmt "FAILED '" ++ to_fmt s ++ "' processing '" ++ p ++ to_fmt "' at")) <|> trace ("FAILED '" ++ to_string s ++ "' at") end >> trace_state >> trace "--------------" /- Simple tactic -/ meta def close_aux (hs : hinst_lemmas) : tactic unit := triv <|> reflexivity reducible <|> contradiction <|> try_for 2000 (rsimp {} hs >> done) <|> try_for 1000 reflexivity meta def close (hs : hinst_lemmas) (s : name) (e : option expr) : tactic unit := done <|> close_aux hs <|> report_failure s e >> failed meta def simph_intros (s : simp_lemmas) (cfg : simp_config) := do ctx ← collect_ctx_simps, s ← s.append ctx, simp_intros s [] [] {to_simp_config := cfg, use_hyps := tt} meta def simple (s : simp_lemmas) (hs : hinst_lemmas) (cfg : simp_config) (s_name : name) (h : option expr) : tactic unit := simph_intros s cfg >> close hs s_name h /- Best first search -/ meta def snapshot := tactic_state meta def save : tactic snapshot := tactic.read meta def restore : snapshot → tactic unit := tactic.write meta def try_snapshots {α} (cont : α → tactic unit) : list (α × snapshot) → tactic unit | [] := failed | ((a, s)::ss) := (restore s >> cont a >> done) <|> try_snapshots ss meta def search {α} (max_depth : nat) (act : nat → α → tactic (list (α × snapshot))) : nat → α → tactic unit | n s := do done <|> if n > max_depth then when_tracing `mini_crush (trace "max depth reached" >> trace_state) >> failed else all_goals $ try intros >> act n s >>= try_snapshots (search (n+1)) meta def try_and_save {α} (t : tactic α) : tactic (option (α × nat × snapshot)) := do { s ← save, a ← t, new_s ← save, n ← num_goals, restore s, return (a, n, new_s) } <|> return none meta def try_all_aux {α β : Type} (ts : α → tactic β) : list α → list (α × β × nat × snapshot) → tactic (list (α × β × nat × snapshot)) | [] [] := failed | [] rs := return rs.reverse | (v::vs) rs := do r ← try_and_save (ts v), match r with | some (b, 0, s) := return [(v, b, 0, s)] | some (b, n, s) := try_all_aux vs ((v, b, n, s)::rs) | none := try_all_aux vs rs end meta def try_all {α β : Type} (ts : α → tactic β) (vs : list α) : tactic (list (α × β × nat × snapshot)) := try_all_aux ts vs [] /- Destruct and simplify -/ meta def try_cases (s : simp_lemmas) (hs : hinst_lemmas) (cfg : simp_config) (s_name : name) : tactic (list (unit × snapshot)) := do es ← collect_inductive_from_target, rs ← try_all (λ e, do when_tracing `mini_crush (do p ← pp e, trace (to_fmt "Splitting on '" ++ p ++ to_fmt "'")), cases e >> skip; simph_intros s cfg; try (close_aux hs)) es, rs ← return $ flip list.qsort rs (λ ⟨e₁, _, n₁, _⟩ ⟨e₂, _, n₂, _⟩, if n₁ ≠ n₂ then n₁ < n₂ else size e₁ < size e₂), return $ rs.map (λ ⟨_, _, _, s⟩, ((), s)) meta def search_cases (max_depth : nat) (s : simp_lemmas) (hs : hinst_lemmas) (cfg : simp_config) (s_name : name) : tactic unit := search max_depth (λ d _, do when_tracing `mini_crush (trace ("Depth #" ++ to_string d)), try_cases s hs cfg s_name) 0 () /- Strategies -/ meta def mk_simp_lemmas (s : option simp_lemmas := none) : tactic simp_lemmas := match s with | some s := return s | none := simp_lemmas.mk_default >>= add_relevant_eqns end meta def mk_hinst_lemmas (s : option hinst_lemmas := none) : tactic hinst_lemmas := match s with | some s := return s | none := add_relevant_eqns_h hinst_lemmas.mk end meta def strategy_1 (cfg : simp_config := {}) (s : option simp_lemmas := none) (hs : option hinst_lemmas := none) (s_name : name := "strategy 1") : tactic unit := do s ← mk_simp_lemmas s, hs ← mk_hinst_lemmas hs, try_induction (λ h, simple s hs cfg s_name (some h)) meta def strategy_2_aux (cfg : simp_config) (hs : hinst_lemmas) : simp_lemmas → tactic unit | s := do s ← simp_intros_aux cfg tt [] s tt [`_], h ← list.ilast <$> local_context, try $ solve1 (mwhen (is_inductive h) $ induction' h; simple s hs cfg "strategy 2" (some h)), done <|> strategy_2_aux s meta def strategy_2 (cfg : simp_config := {}) (s : option simp_lemmas := none) (hs : option hinst_lemmas := none) : tactic unit := do s ← mk_simp_lemmas s, hs ← mk_hinst_lemmas hs, strategy_2_aux cfg hs s meta def strategy_3 (cfg : simp_config := {}) (max_depth : nat := 1) (s : option simp_lemmas := none) (hs : option hinst_lemmas := none) : tactic unit := do s ← mk_simp_lemmas s, hs ← mk_hinst_lemmas hs, try_induction (λ h, try (simph_intros s cfg); try (close_aux hs); (done <|> search_cases max_depth s hs cfg "strategy 3")) end mini_crush open tactic mini_crush meta def mini_crush (cfg : simp_config := {}) (max_depth : nat := 1) := do s ← mk_simp_lemmas, hs ← mk_hinst_lemmas, strategy_1 cfg (some s) (some hs) <|> strategy_2 cfg (some s) (some hs) <|> strategy_3 cfg max_depth (some s) (some hs)
3b71163541c6593aa093530664125097d695b464
4727251e0cd73359b15b664c3170e5d754078599
/src/data/int/nat_prime.lean
ad6fae2fe0bd1f09613a8ad05cc38022b541434c
[ "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
483
lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker, Bryan Gin-ge Chen -/ import data.nat.prime import data.int.basic /-! # Lemmas about nat.prime using `int`s -/ open nat namespace int lemma not_prime_of_int_mul {a b : ℤ} {c : ℕ} (ha : 1 < a.nat_abs) (hb : 1 < b.nat_abs) (hc : a*b = (c : ℤ)) : ¬ nat.prime c := not_prime_mul' (nat_abs_mul_nat_abs_eq hc) ha hb end int
fb476d4d9bb1b50e252466777fb10a5ede97dced
7571914d3f4d9677288f35ab1a53a2ad70a62bd7
/library/init/meta/interactive.lean
6aaa9d327337faacd8b897c974550165de634a47
[ "Apache-2.0" ]
permissive
picrin/lean-1
a395fed5287995f09a15a190bb24609919a0727f
b50597228b42a7eaa01bf8cb7a4fb1a98e7a8aab
refs/heads/master
1,610,757,735,162
1,502,008,413,000
1,502,008,413,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,745
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators import init.meta.interactive_base open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit /-- This tactic applies to a goal that is either a Pi/forall or starts with a let binder. If the current goal is a Pi/forall `∀ x:T, U` (resp `let x:=t in U`) then intro puts `x:T` (resp `x:=t`) in the local context. The new subgoal target is `U`. If the goal is an arrow `T → U`, then it puts in the local context either `h:T`, and the new goal target is `U`. If the goal is neither a Pi/forall nor starting with a let definition, the tactic `intro` applies the tactic `whnf` until the tactic `intro` can be applied or the goal is not `head-reducible`. -/ meta def intro : parse ident_? → tactic unit | none := intro1 >> skip | (some h) := tactic.intro h >> skip /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h_1 ... h_n` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := tactic.intros >> skip | hs := intro_lst hs >> skip /-- The tactic introv allows to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := tactic.introv ns >> return () /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` into `h₂` in the current local context. -/ meta def rename : parse ident → parse ident → tactic unit := tactic.rename /-- This tactic applies to any goal. The argument term is a term well-formed in the local context of the main goal. The tactic apply tries to match the current goal against the conclusion of the type of term. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non dependent premises are added before dependent ones. The tactic `apply` uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := i_to_expr_for_apply q >>= tactic.apply /-- Similar to the `apply` tactic, but it also creates subgoals for dependent premises that have not been fixed by type inference or type class resolution. -/ meta def fapply (q : parse texpr) : tactic unit := i_to_expr_for_apply q >>= tactic.fapply /-- Similar to the `apply` tactic, but it only creates subgoals for non dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := i_to_expr_for_apply q >>= tactic.eapply /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := do e ← i_to_expr_for_apply q, tactic.apply e cfg /-- This tactic tries to close the main goal `... |- U` using type class resolution. It succeeds if it generates a term of type `U` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic applies to any goal. It behaves like `exact` with a big difference: the user can leave some holes `_` in the term. `refine` will generate as many subgoals as there are holes in the term. Note that some holes may be implicit. The type of holes must be either synthesized by the system or declared by an explicit type ascription like (e.g., `(_ : nat → Prop)`). -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for an hypothesis which type is equal to the goal target. If it is the case, the subgoal is proved. Otherwise, it fails. -/ meta def assumption : tactic unit := tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- This tactic applies to any goal. `change U` replaces the main goal target `T` with `U` providing that `U` is well-formed with respect to the main goal local context, and `T` and `U` are definitionally equal. `change U at h` will change a local hypothesis with `U`. `change A with B at h1 h2 ...` will replace `A` with `B` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `A` and `B` are definitionally equal. -/ meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic applies to any goal. It gives directly the exact proof term of the goal. Let `T` be our goal, let `p` be a term of type `U` then `exact p` succeeds iff `T` and `U` are definitionally equal. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and its dependencies to the goal target. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := do hs ← mmap tactic.get_local ids, revert_lst hs, skip private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta instance rw_rule.reflect : has_reflect rw_rule := λ ⟨p, s, r⟩, `(_) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {cfg with symm := r.symm}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {cfg with symm := r.symm}) (eq_lemmas.empty) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_hyp e hyp {cfg with symm := r.symm} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {cfg with symm := r.symm} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) meta instance rw_rules_t.reflect : has_reflect rw_rules_t := λ ⟨rs, p⟩, `(_) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rw_core q l cfg meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rw_core q l cfg /- rewrite followed by assumption -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := rw_core q l cfg meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := rw_core q l cfg private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type, return I precedence `generalizing` : 0 meta def induction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do e ← i_to_expr p, -- generalize major premise e ← if e.is_local_constant then pure e else generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, -- TODO(Kha): `t ← whnf_ginductive t,` const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst, tactic.induction e ids rec_name, all_goals $ do { intron n, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear) } meta def cases (p : parse texpr) (ids : parse with_ident_list) : tactic unit := do e ← i_to_expr p, tactic.cases e ids private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr) | case e := if e.has_meta_var then match e with | (mvar _ _ _) := do case ← case, guard $ e ∈ goals, pure (case, e) | (app _ _) := let idx := match e.get_app_fn with | const (name.mk_string rec ty') _ := guard (ty' = ty) >> match mk_simple_name rec with | `drec := some idx | `rec := some idx -- indices + major premise | `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1) | _ := none end | _ := none end in match idx with | none := list.foldl (<|>) (find_case case e.get_app_fn) $ e.get_app_args.map (find_case case) | some idx := let args := e.get_app_args in do arg ← args.nth idx, args.enum.foldl (λ acc ⟨i, arg⟩, match acc with | some _ := acc | _ := if i ≠ idx then find_case none arg else none end) -- start recursion with likely case (find_case (some arg) arg) end | (lam _ _ _ e) := find_case case e | (macro n args) := list.foldl (<|>) none $ args.map (find_case case) | _ := none end else none private meta def rename_lams : expr → list name → tactic unit | (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns) | _ _ := skip /-- Focuses on the `induction`/`cases` subgoal corresponding to the given introduction rule, optionally renaming introduced locals. -/ meta def case (ctor : parse ident) (ids : parse ident_*) (tac : itactic) : tactic unit := do r ← result, env ← get_env, ctor ← resolve_constant ctor <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), ty ← (env.inductive_type_of ctor).to_monad <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), let ctors := env.constructors_of ty, let idx := env.inductive_num_params ty + /- motive -/ 1 + list.index_of ctor ctors, gs ← get_goals, (case, g) ← (find_case gs ty idx (env.inductive_num_indices ty) none r ).to_monad <|> fail "could not find open goal of given case", set_goals $ g :: gs.filter (≠ g), rename_lams case ids, solve1 tac meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct private meta def generalize_arg_p : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ meta def generalize (h : parse ident?) (p : parse $ tk ":" *> with_desc "expr = id" (parser.pexpr 0 >>= generalize_arg_p)) : tactic unit := do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize e x >> intro1 >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h meta def ginduction (p : parse texpr) (rec_name : parse using_ident) (ids : parse with_ident_list) : tactic unit := do x ← mk_fresh_name, let (h, hs) := (match ids with | [] := (`_h, []) | (h :: hs) := (h, hs) end : name × list name), generalize h (p, x), t ← get_local x, induction (to_pexpr t) rec_name hs ([] : list name) meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := tactic.admit /-- This tactic applies to any goal. The contradiction tactic attempts to find in the current local context an hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction meta def repeat : itactic → tactic unit := tactic.repeat meta def try : itactic → tactic unit := tactic.try meta def skip : tactic unit := tactic.skip meta def solve1 : itactic → tactic unit := tactic.solve1 meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id meta def all_goals : itactic → tactic unit := tactic.all_goals meta def any_goals : itactic → tactic unit := tactic.any_goals meta def focus (tac : itactic) : tactic unit := tactic.focus [tac] private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- This tactic applies to any goal. - `have h : T := p` adds the hypothesis `h : T` to the current goal if `p` a term of type `T`. If `T` is omitted, it will be inferred. - `have h : T` adds the hypothesis `h : T` to the current goal and opens a new subgoal with target `T`. The new subgoal becomes the main goal. If `T` is omitted, it will be replaced by a fresh meta variable. If `h` is omitted, it defaults to `this`. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr e >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- This tactic applies to any goal. - `let h : T := p` adds the hypothesis `h : T := p` to the current goal if `p` a term of type `T`. If `T` is omitted, it will be inferred. - `let h : T` adds the hypothesis `h : T := ?M` to the current goal and opens a new subgoal `?M : T`. The new subgoal becomes the main goal. If `T` is omitted, it will be replaced by a fresh meta variable. If `h` is omitted, it defaults to `this`. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr e >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := tactic.constructor /-- Similar to `constructor`, but only non dependent premises are added as new goals. -/ meta def econstructor : tactic unit := tactic.econstructor meta def left : tactic unit := tactic.left meta def right : tactic unit := tactic.right meta def split : tactic unit := tactic.split meta def exfalso : tactic unit := tactic.exfalso /-- The injection tactic is based on the fact that constructors of inductive datatypes are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds to new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` an `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type meta instance : has_reflect simp_arg_type | simp_arg_type.all_hyps := `(_) | (simp_arg_type.except _) := `(_) | (simp_arg_type.expr _) := `(_) meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /- Return (hs, gex, hex, all) -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := (e::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail ("invalid simplification lemma '" ++ to_string n ++ "' (use command 'set_option trace.simp_lemmas true' for more details)") private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) := do p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (clear h)) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- This tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. - `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. - `simp [h_1, ..., h_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `h_i`s. The `h_i`'s are terms. If a `h_i` is a definition `f`, then the equational lemmas associated with `f` are used. This is a convenient way to "unfold" `f`. - `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. Remark: `simp *` is a shorthand for `simp [*]`. - `simp only [h_1, ..., h_n]` is like `simp [h_1, ..., h_n]` but does not use `[simp]` lemmas - `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `id_i`s. - `simp at h_1 ... h_n` simplifies the non dependent hypotheses `h_1 : T_1` ... `h_n : T : n`. The tactic fails if the target or another hypothesis depends on one of them. - `simp at *` simplifies all the hypotheses and the target. - `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. - `simp with attr_1 ... attr_n` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr_1]`, ..., `[attr_n]` or `[simp]`. -/ meta def simp (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat /-- Just construct the simp set and trace it -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (es : list pexpr) : list simp_arg_type := es.map simp_arg_type.expr meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := do ls ← local_context, n ← revert_lst ls, dsimp_target s u cfg, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal that has the form `t ~ u` where `~` is a reflexive relation. That is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity meta def symmetry : tactic unit := tactic.symmetry meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end meta def ac_reflexivity : tactic unit := tactic.ac_refl meta def ac_refl : tactic unit := tactic.ac_refl meta def cc : tactic unit := tactic.cc meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) namespace interactive open interactive interactive.types expr meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg meta def apply_opt_param : tactic unit := tactic.apply_opt_param meta def apply_auto_param : tactic unit := tactic.apply_auto_param meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p meta def by_cases (q : parse texpr) (n : parse (tk "with" *> ident)?): tactic unit := do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h) meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () meta def by_contra (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] /-- The tactic `specialize (h a_1 ... a_n)` works on local hypothesis `h`. The premises of this hypothesis (either universal quantifications or non-dependent implications) are instantiated by concrete terms coming either from arguments `a_1` ... `a_n`. It adds a new hypothesis with the same name `h := h a_1 ... a_n`, and (tries to) clear the previous one. -/ meta def specialize (p : parse texpr) : tactic unit := do e ← i_to_expr p, let h := expr.get_app_fn e, if h.is_local_constant then tactic.note h.local_pp_name none e >> try (tactic.clear h) else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := `tactic.interactive <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns end add_interactive
b6e05cc382444ecb1c2cc17b6ea28d6446f6d6b3
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/finset/fold.lean
73eb9a3ba1ff285334eb245868d8182ec50ea0ce
[ "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
5,803
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.basic import data.multiset.fold /-! # The fold operation for a commutative associative operation over a finset. -/ namespace finset open multiset variables {α β γ : Type*} /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : finset α).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := begin by_cases (a ∈ s), { rw [← insert_erase h], simp [← ha.assoc, hi.idempotent] }, { apply fold_insert h }, end lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha @[simp] lemma fold_union_empty_singleton [decidable_eq α] (s : finset α) : finset.fold (∪) ∅ singleton s = s := begin apply finset.induction_on s, { simp only [fold_empty], }, { intros a s has ih, rw [fold_insert has, ih, insert_eq], } end @[simp] lemma fold_sup_bot_singleton [decidable_eq α] (s : finset α) : finset.fold (⊔) ⊥ singleton s = s := fold_union_empty_singleton s section order variables [decidable_linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff end order end fold end finset
3e012bac66bd3a7774b38aaa6747b0bd8b7f4c10
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/hom/complete_lattice.lean
d40a85a082fe991004b7f239371e4741e1ac79b9
[ "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
24,988
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.complete_lattice import order.hom.lattice /-! # Complete lattice homomorphisms This file defines frame homorphisms and complete lattice homomorphisms. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `Sup_hom`: Maps which preserve `⨆`. * `Inf_hom`: Maps which preserve `⨅`. * `frame_hom`: Frame homomorphisms. Maps which preserve `⨆`, `⊓` and `⊤`. * `complete_lattice_hom`: Complete lattice homomorphisms. Maps which preserve `⨆` and `⨅`. ## Typeclasses * `Sup_hom_class` * `Inf_hom_class` * `frame_hom_class` * `complete_lattice_hom_class` ## Concrete homs * `complete_lattice.set_preimage`: `set.preimage` as a complete lattice homomorphism. ## TODO Frame homs are Heyting homs. -/ open function order_dual set variables {F α β γ δ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The type of `⨆`-preserving functions from `α` to `β`. -/ structure Sup_hom (α β : Type*) [has_Sup α] [has_Sup β] := (to_fun : α → β) (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) /-- The type of `⨅`-preserving functions from `α` to `β`. -/ structure Inf_hom (α β : Type*) [has_Inf α] [has_Inf β] := (to_fun : α → β) (map_Inf' (s : set α) : to_fun (Inf s) = Inf (to_fun '' s)) /-- The type of frame homomorphisms from `α` to `β`. They preserve finite meets and arbitrary joins. -/ structure frame_hom (α β : Type*) [complete_lattice α] [complete_lattice β] extends inf_top_hom α β := (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) /-- The type of complete lattice homomorphisms from `α` to `β`. -/ structure complete_lattice_hom (α β : Type*) [complete_lattice α] [complete_lattice β] extends Inf_hom α β := (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) section set_option old_structure_cmd true /-- `Sup_hom_class F α β` states that `F` is a type of `⨆`-preserving morphisms. You should extend this class when you extend `Sup_hom`. -/ class Sup_hom_class (F : Type*) (α β : out_param $ Type*) [has_Sup α] [has_Sup β] extends fun_like F α (λ _, β) := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) /-- `Inf_hom_class F α β` states that `F` is a type of `⨅`-preserving morphisms. You should extend this class when you extend `Inf_hom`. -/ class Inf_hom_class (F : Type*) (α β : out_param $ Type*) [has_Inf α] [has_Inf β] extends fun_like F α (λ _, β) := (map_Inf (f : F) (s : set α) : f (Inf s) = Inf (f '' s)) /-- `frame_hom_class F α β` states that `F` is a type of frame morphisms. They preserve `⊓` and `⨆`. You should extend this class when you extend `frame_hom`. -/ class frame_hom_class (F : Type*) (α β : out_param $ Type*) [complete_lattice α] [complete_lattice β] extends inf_top_hom_class F α β := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) /-- `complete_lattice_hom_class F α β` states that `F` is a type of complete lattice morphisms. You should extend this class when you extend `complete_lattice_hom`. -/ class complete_lattice_hom_class (F : Type*) (α β : out_param $ Type*) [complete_lattice α] [complete_lattice β] extends Inf_hom_class F α β := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) end export Sup_hom_class (map_Sup) export Inf_hom_class (map_Inf) attribute [simp] map_Sup map_Inf lemma map_supr [has_Sup α] [has_Sup β] [Sup_hom_class F α β] (f : F) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, supr, map_Sup, set.range_comp] lemma map_supr₂ [has_Sup α] [has_Sup β] [Sup_hom_class F α β] (f : F) (g : Π i, κ i → α) : f (⨆ i j, g i j) = ⨆ i j, f (g i j) := by simp_rw map_supr lemma map_infi [has_Inf α] [has_Inf β] [Inf_hom_class F α β] (f : F) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := by rw [infi, infi, map_Inf, set.range_comp] lemma map_infi₂ [has_Inf α] [has_Inf β] [Inf_hom_class F α β] (f : F) (g : Π i, κ i → α) : f (⨅ i j, g i j) = ⨅ i j, f (g i j) := by simp_rw map_infi @[priority 100] -- See note [lower instance priority] instance Sup_hom_class.to_sup_bot_hom_class [complete_lattice α] [complete_lattice β] [Sup_hom_class F α β] : sup_bot_hom_class F α β := { map_sup := λ f a b, by rw [←Sup_pair, map_Sup, set.image_pair, Sup_pair], map_bot := λ f, by rw [←Sup_empty, map_Sup, set.image_empty, Sup_empty], ..‹Sup_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance Inf_hom_class.to_inf_top_hom_class [complete_lattice α] [complete_lattice β] [Inf_hom_class F α β] : inf_top_hom_class F α β := { map_inf := λ f a b, by rw [←Inf_pair, map_Inf, set.image_pair, Inf_pair], map_top := λ f, by rw [←Inf_empty, map_Inf, set.image_empty, Inf_empty], ..‹Inf_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance frame_hom_class.to_Sup_hom_class [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : Sup_hom_class F α β := { .. ‹frame_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance frame_hom_class.to_bounded_lattice_hom_class [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : bounded_lattice_hom_class F α β := { .. ‹frame_hom_class F α β›, ..Sup_hom_class.to_sup_bot_hom_class } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_frame_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : frame_hom_class F α β := { .. ‹complete_lattice_hom_class F α β›, ..Inf_hom_class.to_inf_top_hom_class } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_bounded_lattice_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : bounded_lattice_hom_class F α β := { ..Sup_hom_class.to_sup_bot_hom_class, ..Inf_hom_class.to_inf_top_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_Sup_hom_class [complete_lattice α] [complete_lattice β] [order_iso_class F α β] : Sup_hom_class F α β := { map_Sup := λ f s, eq_of_forall_ge_iff $ λ c, by simp only [←le_map_inv_iff, Sup_le_iff, set.ball_image_iff], .. show order_hom_class F α β, from infer_instance } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_Inf_hom_class [complete_lattice α] [complete_lattice β] [order_iso_class F α β] : Inf_hom_class F α β := { map_Inf := λ f s, eq_of_forall_le_iff $ λ c, by simp only [←map_inv_le_iff, le_Inf_iff, set.ball_image_iff], .. show order_hom_class F α β, from infer_instance } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_complete_lattice_hom_class [complete_lattice α] [complete_lattice β] [order_iso_class F α β] : complete_lattice_hom_class F α β := { ..order_iso_class.to_Sup_hom_class, ..order_iso_class.to_lattice_hom_class, .. show Inf_hom_class F α β, from infer_instance } instance [has_Sup α] [has_Sup β] [Sup_hom_class F α β] : has_coe_t F (Sup_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ instance [has_Inf α] [has_Inf β] [Inf_hom_class F α β] : has_coe_t F (Inf_hom α β) := ⟨λ f, ⟨f, map_Inf f⟩⟩ instance [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : has_coe_t F (frame_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ instance [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : has_coe_t F (complete_lattice_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ /-! ### Supremum homomorphisms -/ namespace Sup_hom variables [has_Sup α] section has_Sup variables [has_Sup β] [has_Sup γ] [has_Sup δ] instance : Sup_hom_class (Sup_hom α β) α β := { coe := Sup_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_Sup := Sup_hom.map_Sup' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (Sup_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : Sup_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : Sup_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `Sup_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : Sup_hom α β) (f' : α → β) (h : f' = f) : Sup_hom α β := { to_fun := f', map_Sup' := h.symm ▸ f.map_Sup' } @[simp] lemma coe_copy (f : Sup_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : Sup_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `Sup_hom`. -/ protected def id : Sup_hom α α := ⟨id, λ s, by rw [id, set.image_id]⟩ instance : inhabited (Sup_hom α α) := ⟨Sup_hom.id α⟩ @[simp] lemma coe_id : ⇑(Sup_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : Sup_hom.id α a = a := rfl /-- Composition of `Sup_hom`s as a `Sup_hom`. -/ def comp (f : Sup_hom β γ) (g : Sup_hom α β) : Sup_hom α γ := { to_fun := f ∘ g, map_Sup' := λ s, by rw [comp_apply, map_Sup, map_Sup, set.image_image] } @[simp] lemma coe_comp (f : Sup_hom β γ) (g : Sup_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : Sup_hom β γ) (g : Sup_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : Sup_hom γ δ) (g : Sup_hom β γ) (h : Sup_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : Sup_hom α β) : f.comp (Sup_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : Sup_hom α β) : (Sup_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : Sup_hom β γ} {f : Sup_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : Sup_hom β γ} {f₁ f₂ : Sup_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_Sup variables [complete_lattice β] instance : partial_order (Sup_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_bot (Sup_hom α β) := ⟨⟨λ _, ⊥, λ s, begin obtain rfl | hs := s.eq_empty_or_nonempty, { rw [set.image_empty, Sup_empty] }, { rw [hs.image_const, Sup_singleton] } end⟩⟩ instance : order_bot (Sup_hom α β) := ⟨⊥, λ f a, bot_le⟩ @[simp] lemma coe_bot : ⇑(⊥ : Sup_hom α β) = ⊥ := rfl @[simp] lemma bot_apply (a : α) : (⊥ : Sup_hom α β) a = ⊥ := rfl end Sup_hom /-! ### Infimum homomorphisms -/ namespace Inf_hom variables [has_Inf α] section has_Inf variables [has_Inf β] [has_Inf γ] [has_Inf δ] instance : Inf_hom_class (Inf_hom α β) α β := { coe := Inf_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_Inf := Inf_hom.map_Inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (Inf_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : Inf_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : Inf_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `Inf_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : Inf_hom α β) (f' : α → β) (h : f' = f) : Inf_hom α β := { to_fun := f', map_Inf' := h.symm ▸ f.map_Inf' } @[simp] lemma coe_copy (f : Inf_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : Inf_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as an `Inf_hom`. -/ protected def id : Inf_hom α α := ⟨id, λ s, by rw [id, set.image_id]⟩ instance : inhabited (Inf_hom α α) := ⟨Inf_hom.id α⟩ @[simp] lemma coe_id : ⇑(Inf_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : Inf_hom.id α a = a := rfl /-- Composition of `Inf_hom`s as a `Inf_hom`. -/ def comp (f : Inf_hom β γ) (g : Inf_hom α β) : Inf_hom α γ := { to_fun := f ∘ g, map_Inf' := λ s, by rw [comp_apply, map_Inf, map_Inf, set.image_image] } @[simp] lemma coe_comp (f : Inf_hom β γ) (g : Inf_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : Inf_hom β γ) (g : Inf_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : Inf_hom γ δ) (g : Inf_hom β γ) (h : Inf_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : Inf_hom α β) : f.comp (Inf_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : Inf_hom α β) : (Inf_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : Inf_hom β γ} {f : Inf_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : Inf_hom β γ} {f₁ f₂ : Inf_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_Inf variables [complete_lattice β] instance : partial_order (Inf_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_top (Inf_hom α β) := ⟨⟨λ _, ⊤, λ s, begin obtain rfl | hs := s.eq_empty_or_nonempty, { rw [set.image_empty, Inf_empty] }, { rw [hs.image_const, Inf_singleton] } end⟩⟩ instance : order_top (Inf_hom α β) := ⟨⊤, λ f a, le_top⟩ @[simp] lemma coe_top : ⇑(⊤ : Inf_hom α β) = ⊤ := rfl @[simp] lemma top_apply (a : α) : (⊤ : Inf_hom α β) a = ⊤ := rfl end Inf_hom /-! ### Frame homomorphisms -/ namespace frame_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] [complete_lattice δ] instance : frame_hom_class (frame_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := f, obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := g, congr' }, map_Sup := λ f, f.map_Sup', map_inf := λ f, f.map_inf', map_top := λ f, f.map_top' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (frame_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun /-- Reinterpret a `frame_hom` as a `lattice_hom`. -/ def to_lattice_hom (f : frame_hom α β) : lattice_hom α β := f @[simp] lemma to_fun_eq_coe {f : frame_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : frame_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `frame_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : frame_hom α β) (f' : α → β) (h : f' = f) : frame_hom α β := { to_inf_top_hom := f.to_inf_top_hom.copy f' h, ..(f : Sup_hom α β).copy f' h } @[simp] lemma coe_copy (f : frame_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : frame_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `frame_hom`. -/ protected def id : frame_hom α α := { to_inf_top_hom := inf_top_hom.id α, ..Sup_hom.id α } instance : inhabited (frame_hom α α) := ⟨frame_hom.id α⟩ @[simp] lemma coe_id : ⇑(frame_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : frame_hom.id α a = a := rfl /-- Composition of `frame_hom`s as a `frame_hom`. -/ def comp (f : frame_hom β γ) (g : frame_hom α β) : frame_hom α γ := { to_inf_top_hom := f.to_inf_top_hom.comp g.to_inf_top_hom, ..(f : Sup_hom β γ).comp (g : Sup_hom α β) } @[simp] lemma coe_comp (f : frame_hom β γ) (g : frame_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : frame_hom β γ) (g : frame_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : frame_hom γ δ) (g : frame_hom β γ) (h : frame_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : frame_hom α β) : f.comp (frame_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : frame_hom α β) : (frame_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : frame_hom β γ} {f : frame_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : frame_hom β γ} {f₁ f₂ : frame_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ instance : partial_order (frame_hom α β) := partial_order.lift _ fun_like.coe_injective end frame_hom /-! ### Complete lattice homomorphisms -/ namespace complete_lattice_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] [complete_lattice δ] instance : complete_lattice_hom_class (complete_lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_Sup := λ f, f.map_Sup', map_Inf := λ f, f.map_Inf' } /-- Reinterpret a `complete_lattice_hom` as a `Sup_hom`. -/ def to_Sup_hom (f : complete_lattice_hom α β) : Sup_hom α β := f /-- Reinterpret a `complete_lattice_hom` as a `bounded_lattice_hom`. -/ def to_bounded_lattice_hom (f : complete_lattice_hom α β) : bounded_lattice_hom α β := f /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (complete_lattice_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : complete_lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : complete_lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `complete_lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : complete_lattice_hom α β := { to_Inf_hom := f.to_Inf_hom.copy f' h, .. f.to_Sup_hom.copy f' h } @[simp] lemma coe_copy (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `complete_lattice_hom`. -/ protected def id : complete_lattice_hom α α := { to_fun := id, ..Sup_hom.id α, ..Inf_hom.id α } instance : inhabited (complete_lattice_hom α α) := ⟨complete_lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(complete_lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : complete_lattice_hom.id α a = a := rfl /-- Composition of `complete_lattice_hom`s as a `complete_lattice_hom`. -/ def comp (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) : complete_lattice_hom α γ := { to_Inf_hom := f.to_Inf_hom.comp g.to_Inf_hom, ..f.to_Sup_hom.comp g.to_Sup_hom } @[simp] lemma coe_comp (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : complete_lattice_hom γ δ) (g : complete_lattice_hom β γ) (h : complete_lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : complete_lattice_hom α β) : f.comp (complete_lattice_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : complete_lattice_hom α β) : (complete_lattice_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : complete_lattice_hom β γ} {f : complete_lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : complete_lattice_hom β γ} {f₁ f₂ : complete_lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end complete_lattice_hom /-! ### Dual homs -/ namespace Sup_hom variables [has_Sup α] [has_Sup β] [has_Sup γ] /-- Reinterpret a `⨆`-homomorphism as an `⨅`-homomorphism between the dual orders. -/ @[simps] protected def dual : Sup_hom α β ≃ Inf_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨to_dual ∘ f ∘ of_dual, f.map_Sup'⟩, inv_fun := λ f, ⟨of_dual ∘ f ∘ to_dual, f.map_Inf'⟩, left_inv := λ f, Sup_hom.ext $ λ a, rfl, right_inv := λ f, Inf_hom.ext $ λ a, rfl } @[simp] lemma dual_id : (Sup_hom.id α).dual = Inf_hom.id _ := rfl @[simp] lemma dual_comp (g : Sup_hom β γ) (f : Sup_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : Sup_hom.dual.symm (Inf_hom.id _) = Sup_hom.id α := rfl @[simp] lemma symm_dual_comp (g : Inf_hom βᵒᵈ γᵒᵈ) (f : Inf_hom αᵒᵈ βᵒᵈ) : Sup_hom.dual.symm (g.comp f) = (Sup_hom.dual.symm g).comp (Sup_hom.dual.symm f) := rfl end Sup_hom namespace Inf_hom variables [has_Inf α] [has_Inf β] [has_Inf γ] /-- Reinterpret an `⨅`-homomorphism as a `⨆`-homomorphism between the dual orders. -/ @[simps] protected def dual : Inf_hom α β ≃ Sup_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, { to_fun := to_dual ∘ f ∘ of_dual, map_Sup' := λ _, congr_arg to_dual (map_Inf f _) }, inv_fun := λ f, { to_fun := of_dual ∘ f ∘ to_dual, map_Inf' := λ _, congr_arg of_dual (map_Sup f _) }, left_inv := λ f, Inf_hom.ext $ λ a, rfl, right_inv := λ f, Sup_hom.ext $ λ a, rfl } @[simp] lemma dual_id : (Inf_hom.id α).dual = Sup_hom.id _ := rfl @[simp] lemma dual_comp (g : Inf_hom β γ) (f : Inf_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : Inf_hom.dual.symm (Sup_hom.id _) = Inf_hom.id α := rfl @[simp] lemma symm_dual_comp (g : Sup_hom βᵒᵈ γᵒᵈ) (f : Sup_hom αᵒᵈ βᵒᵈ) : Inf_hom.dual.symm (g.comp f) = (Inf_hom.dual.symm g).comp (Inf_hom.dual.symm f) := rfl end Inf_hom namespace complete_lattice_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] /-- Reinterpret a complete lattice homomorphism as a complete lattice homomorphism between the dual lattices. -/ @[simps] protected def dual : complete_lattice_hom α β ≃ complete_lattice_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_Sup_hom.dual, f.map_Inf'⟩, inv_fun := λ f, ⟨f.to_Sup_hom.dual, f.map_Inf'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (complete_lattice_hom.id α).dual = complete_lattice_hom.id _ := rfl @[simp] lemma dual_comp (g : complete_lattice_hom β γ) (f : complete_lattice_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : complete_lattice_hom.dual.symm (complete_lattice_hom.id _) = complete_lattice_hom.id α := rfl @[simp] lemma symm_dual_comp (g : complete_lattice_hom βᵒᵈ γᵒᵈ) (f : complete_lattice_hom αᵒᵈ βᵒᵈ) : complete_lattice_hom.dual.symm (g.comp f) = (complete_lattice_hom.dual.symm g).comp (complete_lattice_hom.dual.symm f) := rfl end complete_lattice_hom /-! ### Concrete homs -/ namespace complete_lattice_hom /-- `set.preimage` as a complete lattice homomorphism. -/ def set_preimage (f : α → β) : complete_lattice_hom (set β) (set α) := { to_fun := preimage f, map_Sup' := λ s, preimage_sUnion.trans $ by simp only [set.Sup_eq_sUnion, set.sUnion_image], map_Inf' := λ s, preimage_sInter.trans $ by simp only [set.Inf_eq_sInter, set.sInter_image] } @[simp] lemma coe_set_preimage (f : α → β) : ⇑(set_preimage f) = preimage f := rfl @[simp] lemma set_preimage_apply (f : α → β) (s : set β) : set_preimage f s = s.preimage f := rfl @[simp] lemma set_preimage_id : set_preimage (id : α → α) = complete_lattice_hom.id _ := rfl -- This lemma can't be `simp` because `g ∘ f` matches anything (`id ∘ f = f` synctatically) lemma set_preimage_comp (g : β → γ) (f : α → β) : set_preimage (g ∘ f) = (set_preimage f).comp (set_preimage g) := rfl end complete_lattice_hom
4260018a68c4f92d460cb1d870b4d6d5296e20a0
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/measure_theory/set_integral.lean
31caea2aa7f33807511db8bb116666037fe898f0
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
35,260
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.bochner_integration import analysis.normed_space.indicator_function /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation `∫ a in s, f a` is `measure_theory.integral (s.indicator f)` ## TODO The file ends with over a hundred lines of commented out code. This is the old contents of this file using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be migrated to the new definition. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter variables {α β E F : Type*} [measurable_space α] section piecewise variables {μ : measure α} {s : set α} {f g : α → β} lemma piecewise_ae_eq_restrict (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict s] f := begin rw [ae_restrict_eq hs], exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right end lemma piecewise_ae_eq_restrict_compl (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict sᶜ] g := begin rw [ae_restrict_eq hs.compl], exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right end end piecewise section indicator_function variables [has_zero β] {μ : measure α} {s : set α} {f : α → β} lemma indicator_ae_eq_restrict (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs lemma indicator_ae_eq_restrict_compl (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 := piecewise_ae_eq_restrict_compl hs end indicator_function namespace measure_theory section normed_group variables [normed_group E] {f : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ⊤ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_union s.finite_to_set lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma integrable_indicator_iff (hs : is_measurable s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp only [integrable_on, integrable, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : is_measurable s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable_on_of_bounded {C} (hs : μ s < ⊤) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : integrable_on f s μ := by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact integrable_of_bounded hf /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin rcases hμ with ⟨s, hsl, hsμ⟩, rcases hf with ⟨C, hC⟩, simp only [eventually_map] at hC, rcases hC.exists_measurable_mem with ⟨t, htl, htm, hC⟩, refine ⟨t ∩ s, inter_mem_sets htl hsl, _⟩, refine integrable_on_of_bounded (lt_of_le_of_lt (measure_mono $ inter_subset_right _ _) hsμ) _, exact C, suffices : ∀ᵐ x ∂μ.restrict t, ∥f x∥ ≤ C, from ae_mono (measure.restrict_mono (inter_subset_left _ _) (le_refl _)) this, rw [ae_restrict_eq htm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [measurable_space E] lemma integrable_add [opens_measurable_space E] {f g : α → E} (h : univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0}) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, _, λ h, h.1.add hf hg h.2⟩, rw [← indicator_add_eq_left h], conv { congr, skip, rw [← indicator_add_eq_right h] }, rw [integrable_indicator_iff (hf (is_measurable_singleton 0)).compl], rw [integrable_indicator_iff (hg (is_measurable_singleton 0)).compl], exact ⟨hfg.integrable_on, hfg.integrable_on⟩ end variables [borel_space E] [second_countable_topology E] /-- To prove something for an arbitrary measurable + integrable function in a second countable Borel normed group, it suffices to show that * the property holds for (multiples of) characteristic functions; * is closed under addition; * the set of functions in the `L¹` space for which the property holds is closed. * the property is closed under the almost-everywhere equal relation. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`). -/ @[elab_as_eliminator] lemma integrable.induction (P : (α → E) → Prop) (h_ind : ∀ (c : E) ⦃s⦄, is_measurable s → μ s < ⊤ → P (s.indicator (λ _, c))) (h_sum : ∀ ⦃f g : α → E⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g → integrable f μ → integrable g μ → P f → P g → P (f + g)) (h_closed : is_closed {f : α →₁[μ] E | P f} ) (h_ae : ∀ ⦃f g⦄, f =ᵐ[μ] g → measurable f → measurable g → integrable f μ → P f → P g) : ∀ ⦃f : α → E⦄ (hf : measurable f) (h2f : integrable f μ), P f := begin have : ∀ (f : simple_func α E), integrable f μ → P f, { refine simple_func.induction _ _, { intros c s hs h, dsimp only [simple_func.coe_const, simple_func.const_zero, piecewise_eq_indicator, simple_func.coe_zero, simple_func.coe_piecewise] at h ⊢, by_cases hc : c = 0, { subst hc, convert h_ind 0 is_measurable.empty (by simp) using 1, simp [const] }, apply h_ind c hs, have : (nnnorm c : ennreal) * μ s < ⊤, { have := @comp_indicator _ _ _ _ (λ x : E, (nnnorm x : ennreal)) (const α c) s, dsimp only at this, simpa [integrable, this, lintegral_indicator, hs] using h }, exact ennreal.lt_top_of_mul_lt_top_right this (by simp [hc]) }, { intros f g hfg hf hg int_fg, rw [simple_func.coe_add, integrable_add hfg f.measurable g.measurable] at int_fg, refine h_sum hfg f.measurable g.measurable int_fg.1 int_fg.2 (hf int_fg.1) (hg int_fg.2) } }, have : ∀ (f : α →₁ₛ[μ] E), P f, { intro f, exact h_ae f.to_simple_func_eq_to_fun f.measurable (l1.measurable _) f.integrable (this f.to_simple_func f.integrable) }, have : ∀ (f : α →₁[μ] E), P f := λ f, l1.simple_func.dense_range.induction_on f h_closed this, exact λ f hf h2f, h_ae (l1.to_fun_of_fun f hf h2f) (l1.measurable _) hf (l1.integrable _) (this (l1.of_fun f hf h2f)) end variables [complete_space E] [normed_space ℝ E] lemma integral_union (hst : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft] lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl (hs : is_measurable s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union (disjoint_compl_right s) hs hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] /-- For a measurable function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hfm : measurable f) (hs : is_measurable s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := have hfms : measurable (indicator s f) := hfm.indicator hs, if hfi : integrable_on f s μ then calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae hfms hfm (indicator_ae_eq_restrict hs)) (integral_congr_ae hfms measurable_const (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp else by { rwa [integral_non_integrable, integral_non_integrable], rwa integrable_indicator_iff hs } lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : is_measurable s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator measurable_const s_meas, ← set_integral_const] lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := by rw [measure.restrict_map hg hs, integral_map_measure hg hf] lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ⊤) (hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ⊤) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : measurable f) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ (ae_restrict_iff $ hfm.norm is_measurable_Iic).2 hC lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ⊤) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : measurable f) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC end normed_group end measure_theory open measure_theory asymptotics metric /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s, f x ∂μ = μ s • b + o(μ s)` as `s` tends to `l.lift' powerset`. Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_group E] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [measurable_space E] [borel_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : measurable f) (hμ : μ.finite_at_filter l) : is_o (λ s : set α, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real) (l.lift' powerset) := begin simp only [is_o_iff], intros ε ε₀, have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), refine hμ.eventually.mp ((h.integrable_at_filter_ae hμ).eventually.mp (this.mono _)), simp only [mem_closed_ball, dist_eq_norm], intros s h_norm h_integrable hμs, rw [← set_integral_const, ← integral_sub hfm h_integrable measurable_const (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub measurable_const) end /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] [normed_group E] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [normed_group E] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within $ λ x hx, by haveI := hs.is_measurable.nhds_within_is_measurably_generated; exact (hf x hx).integrable_at_filter (μ.finite_at_nhds_within _ _) /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [normed_group E] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure that and `f` is a measurable function that is continuous at a point `a`, then `∫ x in s, f x ∂μ = μ s • f a + o(μ s)` as `s` tends to `(𝓝 a).lift' powerset`. Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_group E] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [measurable_space E] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : measurable f) : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • f a) (λ s, (μ s).to_real) ((𝓝 a).lift' powerset) := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. The first step is to prove that, given a function `φ : α → E` which is measurable and integrable, and a continuous linear map `L : E →L[ℝ] F`, the function `λ a, L(φ a)` is also measurable and integrable. Note we cannot write this as `L ∘ φ` since the type of `L` is not an actual function type. The next step is translate this to `l1`, replacing the function `φ` by a term with type `α →₁[μ] E` (an equivalence class of integrable functions). The corresponding "composition" is `L.comp_l1 φ : α →₁[μ] F`. This is then upgraded to a linear map `L.comp_l1ₗ : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F)` and a continuous linear map `L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F)`. Then we can prove the commutation result using continuity of all relevant operations and the result on simple functions. -/ variables {μ : measure α} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] namespace continuous_linear_map lemma integrable_comp {φ : α → E} (L : E →L[ℝ] F) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (eventually_of_forall $ λ a, L.le_op_norm (φ a)) variables [second_countable_topology E] [measurable_space E] [borel_space E] lemma norm_comp_l1_apply_le (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∀ᵐ a ∂μ, ∥L (φ a)∥ ≤ ∥L∥*∥φ a∥ := eventually_of_forall (λ a, L.le_op_norm (φ a)) section variables [measurable_space F] [borel_space F] [second_countable_topology F] /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`. -/ def comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : α →₁[μ] F := l1.of_fun (λ a, L (φ a)) (L.measurable_comp φ.measurable) (L.integrable_comp φ.integrable) lemma comp_l1_apply (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∀ᵐ a ∂μ, (L.comp_l1 φ) a = L (φ a) := l1.to_fun_of_fun _ _ _ end lemma integrable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : integrable (λ a, L (φ a)) μ := L.integrable_comp φ.integrable variables [measurable_space F] lemma measurable_comp_l1 [borel_space F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : measurable (λ a, L (φ a)) := L.measurable.comp φ.measurable variables [borel_space F] [second_countable_topology F] lemma integral_comp_l1 [complete_space F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, (L.comp_l1 φ) a ∂μ = ∫ a, L (φ a) ∂μ := by simp [comp_l1] /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1ₗ (L : E →L[ℝ] F) : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F) := { to_fun := λ φ, L.comp_l1 φ, map_add' := begin intros f g, dsimp [comp_l1], rw [← l1.of_fun_add, l1.of_fun_eq_of_fun], apply (l1.add_to_fun f g).mono, intros a ha, simp only [ha, pi.add_apply, L.map_add] end, map_smul' := begin intros c f, dsimp [comp_l1], rw [← l1.of_fun_smul, l1.of_fun_eq_of_fun], apply (l1.smul_to_fun c f).mono, intros a ha, simp only [ha, pi.smul_apply, continuous_linear_map.map_smul] end } lemma norm_comp_l1_le (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∥L.comp_l1 φ∥ ≤ ∥L∥*∥φ∥ := begin erw l1.norm_of_fun_eq_integral_norm, calc ∫ a, ∥L (φ a)∥ ∂μ ≤ ∫ a, ∥L∥ *∥φ a∥ ∂μ : integral_mono (L.measurable.comp φ.measurable).norm (L.integrable_comp_l1 φ).norm (φ.measurable_norm.const_mul $ ∥L∥) (φ.integrable_norm.const_mul $ ∥L∥) (L.norm_comp_l1_apply_le φ) ... = ∥L∥ * ∥φ∥ : by rw [integral_mul_left, φ.norm_eq_integral_norm] end /-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `α →₁[μ] E`. -/ def comp_l1L (L : E →L[ℝ] F) : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F) := linear_map.mk_continuous L.comp_l1ₗ (∥L∥) (λ φ, L.norm_comp_l1_le φ) lemma norm_compl1L_le (L : E →L[ℝ] F) : ∥(L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F))∥ ≤ ∥L∥ := op_norm_le_bound _ (norm_nonneg _) (λ φ, L.norm_comp_l1_le φ) variables [complete_space F] lemma continuous_integral_comp_l1 (L : E →L[ℝ] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := begin rw ← funext L.integral_comp_l1, exact continuous_integral.comp L.comp_l1L.continuous end variables [complete_space E] lemma integral_comp_comm (L : E →L[ℝ] F) {φ : α → E} (φ_meas : measurable φ) (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, continuous_linear_map.map_smul, ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_meas g_meas f_int g_int hf hg, simp [L.map_add, integral_add f_meas f_int g_meas g_int, integral_add (L.measurable_comp f_meas) (L.integrable_comp f_int) (L.measurable_comp g_meas) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_l1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_meas g_meas f_int hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (L.measurable.comp g_meas) (L.measurable.comp f_meas) (hfg.fun_comp L).symm }, { rw integral_congr_ae g_meas f_meas hfg.symm } }, all_goals { assumption } end lemma integral_comp_l1_comm (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm φ.measurable φ.integrable end continuous_linear_map end /- namespace integrable variables [measurable_space α] [measurable_space β] [normed_group E] protected lemma measure_mono end integrable end measure_theory section integral_on variables [measurable_space α] [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] {s t : set α} {f g : α → β} {μ : measure α} open set lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : is_measurable s) (h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ := integral_congr_ae hf hg $ _ lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f) (h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) := integral_congr_ae hsm htm $ indicator_congr_of_set h lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) := by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi } lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) := by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi } lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ᵐ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := begin apply integral_le_integral_ae hfm hfi hgm hgi, apply indicator_le_indicator_ae, exact h end lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] } lemma integral_on_union_ae (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : ∀ᵐ a, a ∉ s ∩ t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := begin have := integral_congr_ae _ _ (indicator_union_ae h f), rw [this, integral_add hsm hsi htm hti], { exact hsm.union hs ht htm }, { exact measurable.add hsm htm } end lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h } lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_on_nonneg_of_ae $ univ_mem_sets' hf lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h } lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_on_nonpos_of_ae $ univ_mem_sets' hf lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, is_measurable (s i)) (h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) := let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, exact hfm.subset (hsm i) (subset_Union _ _) }, { assumption }, { show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) } end lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, is_measurable (s i)) (h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) := let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) }, { exact hfm.subset (is_measurable.Inter hsm) (Inter_subset _ _) }, { show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) } end -- TODO : prove this for an encodable type -- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat ` lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, is_measurable (s i)) (hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : (∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a := suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)), by { rwa has_sum.tsum_eq }, begin have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a, { funext, rw [← integral_finset_sum, indicator_finset_bUnion], { assume i hi j hj hij, exact hd i j hij }, { assume i, refine hfm.subset (hm _) (subset_Union _ _) }, { assume i, refine hfi.subset (subset_Union _ _) } }, rw this, refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _, { exact indicator (Union s) (λ a, ∥f a∥) }, { exact is_countably_generated_at_top_finset_nat }, { refine univ_mem_sets' (λ n, _), simp only [mem_set_of_eq], refine hfm.subset (is_measurable.Union (λ i, is_measurable.Union_Prop (λh, hm _))) (bUnion_subset_Union _ _), }, { assumption }, { refine univ_mem_sets' (λ n, univ_mem_sets' $ _), simp only [mem_set_of_eq], assume a, rw ← norm_indicator_eq_indicator_norm, refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ }, { rw [← integrable_on, integrable_on_norm_iff], assumption }, { filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) } end end integral_on -/
9673a6e4d1b517e5c2e9483c90d472f1d3b91f16
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/acyclic.lean
5324b67ef9476cef71b440cceec0f1da659ef361
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,853
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.connectivity /-! # Acyclic graphs and trees > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module introduces *acyclic graphs* (a.k.a. *forests*) and *trees*. ## Main definitions * `simple_graph.is_acyclic` is a predicate for a graph having no cyclic walks * `simple_graph.is_tree` is a predicate for a graph being a tree (a connected acyclic graph) ## Main statements * `simple_graph.is_acyclic_iff_path_unique` characterizes acyclicity in terms of uniqueness of paths between pairs of vertices. * `simple_graph.is_acyclic_iff_forall_edge_is_bridge` characterizes acyclicity in terms of every edge being a bridge edge. * `simple_graph.is_tree_iff_exists_unique_path` characterizes trees in terms of existence and uniqueness of paths between pairs of vertices from a nonempty vertex type. ## References The structure of the proofs for `simple_graph.is_acyclic` and `simple_graph.is_tree`, including supporting lemmas about `simple_graph.is_bridge`, generally follows the high-level description for these theorems for multigraphs from [Chou1994]. ## Tags acyclic graphs, trees -/ universes u v namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- A graph is *acyclic* (or a *forest*) if it has no cycles. -/ def is_acyclic : Prop := ∀ (v : V) (c : G.walk v v), ¬c.is_cycle /-- A *tree* is a connected acyclic graph. -/ @[mk_iff, protect_proj] structure is_tree : Prop := (is_connected : G.connected) (is_acyclic : G.is_acyclic) variables {G} lemma is_acyclic_iff_forall_adj_is_bridge : G.is_acyclic ↔ ∀ ⦃v w : V⦄, G.adj v w → G.is_bridge ⟦(v, w)⟧ := begin simp_rw [is_bridge_iff_adj_and_forall_cycle_not_mem], split, { intros ha v w hvw, apply and.intro hvw, intros u p hp, exact absurd hp (ha _ p), }, { rintros hb v (_ | @⟨_, _, _, ha, p⟩) hp, { exact hp.not_of_nil }, { specialize hb ha, apply hb.2 _ hp, rw [walk.edges_cons], apply list.mem_cons_self } }, end lemma is_acyclic_iff_forall_edge_is_bridge : G.is_acyclic ↔ ∀ ⦃e⦄, e ∈ G.edge_set → G.is_bridge e := by simp [is_acyclic_iff_forall_adj_is_bridge, sym2.forall] lemma is_acyclic.path_unique {G : simple_graph V} (h : G.is_acyclic) {v w : V} (p q : G.path v w) : p = q := begin obtain ⟨p, hp⟩ := p, obtain ⟨q, hq⟩ := q, simp only, induction p with u pu pv pw ph p ih generalizing q, { rw walk.is_path_iff_eq_nil at hq, exact hq.symm, }, { rw is_acyclic_iff_forall_adj_is_bridge at h, specialize h ph, rw is_bridge_iff_adj_and_forall_walk_mem_edges at h, replace h := h.2 (q.append p.reverse), simp only [walk.edges_append, walk.edges_reverse, list.mem_append, list.mem_reverse] at h, cases h, { cases q, { simpa [walk.is_path_def] using hp }, { rw walk.cons_is_path_iff at hp hq, simp only [walk.edges_cons, list.mem_cons_iff, sym2.eq_iff] at h, obtain (⟨h,rfl⟩ | ⟨rfl,rfl⟩) | h := h, { rw [ih hp.1 _ hq.1] }, { simpa using hq }, { exact absurd (walk.fst_mem_support_of_mem_edges _ h) hq.2 } } }, { rw walk.cons_is_path_iff at hp, exact absurd (walk.fst_mem_support_of_mem_edges _ h) hp.2 } } end lemma is_acyclic_of_path_unique (h : ∀ (v w : V) (p q : G.path v w), p = q) : G.is_acyclic := begin intros v c hc, simp only [walk.is_cycle_def, ne.def] at hc, cases c, { exact absurd rfl hc.2.1 }, { simp only [walk.cons_is_trail_iff, not_false_iff, walk.support_cons, list.tail_cons, true_and] at hc, specialize h _ _ ⟨c_p, by simp only [walk.is_path_def, hc.2]⟩ (path.singleton (G.symm c_h)), simp only [path.singleton] at h, simpa [-quotient.eq, sym2.eq_swap, h] using hc }, end lemma is_acyclic_iff_path_unique : G.is_acyclic ↔ ∀ ⦃v w : V⦄ (p q : G.path v w), p = q := ⟨is_acyclic.path_unique, is_acyclic_of_path_unique⟩ lemma is_tree_iff_exists_unique_path : G.is_tree ↔ nonempty V ∧ ∀ (v w : V), ∃! (p : G.walk v w), p.is_path := begin classical, rw [is_tree_iff, is_acyclic_iff_path_unique], split, { rintro ⟨hc, hu⟩, refine ⟨hc.nonempty, _⟩, intros v w, let q := (hc v w).some.to_path, use q, simp only [true_and, path.is_path], intros p hp, specialize hu ⟨p, hp⟩ q, exact subtype.ext_iff.mp hu, }, { unfreezingI { rintro ⟨hV, h⟩ }, refine ⟨connected.mk _, _⟩, { intros v w, obtain ⟨p, hp⟩ := h v w, exact p.reachable, }, { rintros v w ⟨p, hp⟩ ⟨q, hq⟩, simp only [unique_of_exists_unique (h v w) hp hq] } }, end end simple_graph
72d4ce3d61ee0aec74705239588dbfae99ae6343
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/group_theory/submonoid.lean
0051911a88d586804e1bdf7c16d54c9c255109cb
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
42,254
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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston -/ import algebra.big_operators import data.finset import tactic.subtype_instance /-! # Submonoids This file defines multiplicative and additive submonoids, first in an unbundled form (deprecated) and then in a bundled form. We prove submonoids of a monoid form a complete lattice, and results about images and preimages of submonoids under monoid homomorphisms. For the unbundled submonoids, these theorems use unbundled monoid homomorphisms (also deprecated), and the bundled versions use bundled monoid homomorphisms. There are also theorems about the submonoids generated by an element or a subset of a monoid, defined both inductively and as the infimum of the set of submonoids containing a given element/subset. ## Implementation notes Unbundled submonoids will slowly be removed from mathlib. (Bundled) submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. ## Tags submonoid, submonoids, is_submonoid -/ variables {α : Type*} [monoid α] {s : set α} variables {β : Type*} [add_monoid β] {t : set β} /-- `s` is an additive submonoid: a set containing 0 and closed under addition. -/ class is_add_submonoid (s : set β) : Prop := (zero_mem : (0:β) ∈ s) (add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s) /-- `s` is a submonoid: a set containing 1 and closed under multiplication. -/ @[to_additive is_add_submonoid] class is_submonoid (s : set α) : Prop := (one_mem : (1:α) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) instance additive.is_add_submonoid (s : set α) : ∀ [is_submonoid s], @is_add_submonoid (additive α) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem additive.is_add_submonoid_iff {s : set α} : @is_add_submonoid (additive α) _ s ↔ is_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by resetI; apply_instance⟩ instance multiplicative.is_submonoid (s : set β) : ∀ [is_add_submonoid s], @is_submonoid (multiplicative β) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem multiplicative.is_submonoid_iff {s : set β} : @is_submonoid (multiplicative β) _ s ↔ is_add_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, λ h, by resetI; apply_instance⟩ /-- The intersection of two submonoids of a monoid `α` is a submonoid of `α`. -/ @[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `α` is an `add_submonoid` of α."] instance is_submonoid.inter (s₁ s₂ : set α) [is_submonoid s₁] [is_submonoid s₂] : is_submonoid (s₁ ∩ s₂) := { one_mem := ⟨is_submonoid.one_mem _, is_submonoid.one_mem _⟩, mul_mem := λ x y hx hy, ⟨is_submonoid.mul_mem hx.1 hy.1, is_submonoid.mul_mem hx.2 hy.2⟩ } /-- The intersection of an indexed set of submonoids of a monoid `α` is a submonoid of `α`. -/ @[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `α` is an `add_submonoid` of `α`."] instance is_submonoid.Inter {ι : Sort*} (s : ι → set α) [h : ∀ y : ι, is_submonoid (s y)] : is_submonoid (set.Inter s) := { one_mem := set.mem_Inter.2 $ λ y, is_submonoid.one_mem (s y), mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $ λ y, is_submonoid.mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) } /-- The union of an indexed, directed, nonempty set of submonoids of a monoid `α` is a submonoid of `α`. -/ @[to_additive is_add_submonoid_Union_of_directed "The union of an indexed, directed, nonempty set of `add_submonoid`s of an `add_monoid` `α` is an `add_submonoid` of `α`. "] lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set α) [∀ i, is_submonoid (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_submonoid (⋃i, s i) := { one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, is_submonoid.one_mem _⟩, mul_mem := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, is_submonoid.mul_mem (hk.1 hi) (hk.2 hj)⟩ } section powers /-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/ def powers (x : α) : set α := {y | ∃ n:ℕ, x^n = y} /-- The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`. -/ def multiples (x : β) : set β := {y | ∃ n:ℕ, add_monoid.smul n x = y} attribute [to_additive multiples] powers /-- 1 is in the set of natural number powers of an element of a monoid. -/ lemma powers.one_mem {x : α} : (1 : α) ∈ powers x := ⟨0, pow_zero _⟩ /-- 0 is in the set of natural number multiples of an element of an `add_monoid`. -/ lemma multiples.zero_mem {x : β} : (0 : β) ∈ multiples x := ⟨0, add_monoid.zero_smul _⟩ attribute [to_additive] powers.one_mem /-- An element of a monoid is in the set of that element's natural number powers. -/ lemma powers.self_mem {x : α} : x ∈ powers x := ⟨1, pow_one _⟩ /-- An element of an `add_monoid` is in the set of that element's natural number multiples. -/ lemma multiples.self_mem {x : β} : x ∈ multiples x := ⟨1, add_monoid.one_smul _⟩ attribute [to_additive] powers.self_mem /-- The set of natural number powers of an element of a monoid is closed under multiplication. -/ lemma powers.mul_mem {x y z : α} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) := λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩ /-- The set of natural number multiples of an element of an `add_monoid` is closed under addition. -/ lemma multiples.add_mem {x y z : β} : (y ∈ multiples x) → (z ∈ multiples x) → (y + z ∈ multiples x) := @powers.mul_mem (multiplicative β) _ _ _ _ attribute [to_additive] powers.mul_mem /-- The set of natural number powers of an element of a monoid `α` is a submonoid of `α`. -/ @[to_additive is_add_submonoid "The set of natural number multiples of an element of an `add_monoid` `α` is an `add_submonoid` of `α`."] instance powers.is_submonoid (x : α) : is_submonoid (powers x) := { one_mem := powers.one_mem, mul_mem := λ y z, powers.mul_mem } /-- A monoid is a submonoid of itself. -/ @[to_additive is_add_submonoid "An `add_monoid` is an `add_submonoid` of itself."] instance univ.is_submonoid : is_submonoid (@set.univ α) := by split; simp /-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/ @[to_additive is_add_submonoid "The preimage of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the domain."] instance preimage.is_submonoid {γ : Type*} [monoid γ] (f : α → γ) [is_monoid_hom f] (s : set γ) [is_submonoid s] : is_submonoid (f ⁻¹' s) := { one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one f; exact is_submonoid.one_mem s, mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s), show f (a * b) ∈ s, by rw is_monoid_hom.map_mul f; exact is_submonoid.mul_mem ha hb } /-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/ @[instance, to_additive is_add_submonoid "The image of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma image.is_submonoid {γ : Type*} [monoid γ] (f : α → γ) [is_monoid_hom f] (s : set α) [is_submonoid s] : is_submonoid (f '' s) := { one_mem := ⟨1, is_submonoid.one_mem s, is_monoid_hom.map_one f⟩, mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, is_submonoid.mul_mem hx.1 hy.1, by rw [is_monoid_hom.map_mul f, hx.2, hy.2]⟩ } /-- The image of a monoid hom is a submonoid of the codomain. -/ @[to_additive is_add_submonoid "The image of an `add_monoid` hom is an `add_submonoid` of the codomain."] instance range.is_submonoid {γ : Type*} [monoid γ] (f : α → γ) [is_monoid_hom f] : is_submonoid (set.range f) := by rw ← set.image_univ; apply_instance /-- Submonoids are closed under natural powers. -/ lemma is_submonoid.pow_mem {a : α} [is_submonoid s] (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s | 0 := is_submonoid.one_mem s | (n + 1) := is_submonoid.mul_mem h is_submonoid.pow_mem /-- An `add_submonoid` is closed under multiplication by naturals. -/ lemma is_add_submonoid.smul_mem {a : β} [is_add_submonoid t] : ∀ (h : a ∈ t) {n : ℕ}, add_monoid.smul n a ∈ t := @is_submonoid.pow_mem (multiplicative β) _ _ _ _ attribute [to_additive smul_mem] is_submonoid.pow_mem /-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/ lemma is_submonoid.power_subset {a : α} [is_submonoid s] (h : a ∈ s) : powers a ⊆ s := assume x ⟨n, hx⟩, hx ▸ is_submonoid.pow_mem h /-- The set of natural number multiples of an element of an `add_submonoid` is a subset of the `add_submonoid`. -/ lemma is_add_submonoid.multiple_subset {a : β} [is_add_submonoid t] : a ∈ t → multiples a ⊆ t := @is_submonoid.power_subset (multiplicative β) _ _ _ _ attribute [to_additive multiple_subset] is_submonoid.power_subset end powers namespace is_submonoid /-- The product of a list of elements of a submonoid is an element of the submonoid. -/ @[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the `add_submonoid`."] lemma list_prod_mem [is_submonoid s] : ∀{l : list α}, (∀x∈l, x ∈ s) → l.prod ∈ s | [] h := one_mem s | (a::l) h := suffices a * l.prod ∈ s, by simpa, have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h, is_submonoid.mul_mem this.1 (list_prod_mem this.2) /-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of the submonoid. -/ @[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid` is an element of the `add_submonoid`. "] lemma multiset_prod_mem {α} [comm_monoid α] (s : set α) [is_submonoid s] (m : multiset α) : (∀a∈m, a ∈ s) → m.prod ∈ s := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact list_prod_mem hl end /-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element of the submonoid. -/ @[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is an element of the `add_submonoid`."] lemma finset_prod_mem {α β} [comm_monoid α] (s : set α) [is_submonoid s] (f : β → α) : ∀(t : finset β), (∀b∈t, f b ∈ s) → t.prod f ∈ s | ⟨m, hm⟩ hs := begin refine multiset_prod_mem s _ _, simp, rintros a b hb rfl, exact hs _ hb end end is_submonoid /-- Submonoids are themselves monoids. -/ @[to_additive add_monoid "An `add_submonoid` is itself an `add_monoid`."] instance subtype.monoid {s : set α} [is_submonoid s] : monoid s := by subtype_instance /-- Submonoids of commutative monoids are themselves commutative monoids. -/ @[to_additive add_comm_monoid "An `add_submonoid` of a commutative `add_monoid` is itself a commutative `add_monoid`. "] instance subtype.comm_monoid {α} [comm_monoid α] {s : set α} [is_submonoid s] : comm_monoid s := by subtype_instance /-- Submonoids inherit the 1 of the monoid. -/ @[simp, to_additive "An `add_submonoid` inherits the 0 of the `add_monoid`. "] lemma is_submonoid.coe_one [is_submonoid s] : ((1 : s) : α) = 1 := rfl /-- Submonoids inherit the multiplication of the monoid. -/ @[simp, to_additive "An `add_submonoid` inherits the addition of the `add_monoid`. "] lemma is_submonoid.coe_mul [is_submonoid s] (a b : s) : ((a * b : s) : α) = a * b := rfl /-- Submonoids inherit the exponentiation by naturals of the monoid. -/ @[simp] lemma is_submonoid.coe_pow [is_submonoid s] (a : s) (n : ℕ) : ((a ^ n : s) : α) = a ^ n := by induction n; simp [*, pow_succ] /-- An `add_submonoid` inherits the multiplication by naturals of the `add_monoid`. -/ @[simp] lemma is_add_submonoid.smul_coe {β : Type*} [add_monoid β] {s : set β} [is_add_submonoid s] (a : s) (n : ℕ) : ((add_monoid.smul n a : s) : β) = add_monoid.smul n a := by {induction n, refl, simp [*, succ_smul]} attribute [to_additive smul_coe] is_submonoid.coe_pow /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance subtype_val.is_monoid_hom [is_submonoid s] : is_monoid_hom (subtype.val : s → α) := { map_one := rfl, map_mul := λ _ _, rfl } /-- The natural injection from a submonoid into the monoid is a monoid hom. -/ @[to_additive is_add_monoid_hom "The natural injection from an `add_submonoid` into the `add_monoid` is an `add_monoid` hom. "] instance coe.is_monoid_hom [is_submonoid s] : is_monoid_hom (coe : s → α) := subtype_val.is_monoid_hom /-- Given a monoid hom `f : γ → α` whose image is contained in a submonoid `s`, the induced map from `γ` to `s` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given an `add_monoid` hom `f : γ → α` whose image is contained in an `add_submonoid` s, the induced map from `γ` to `s` is an `add_monoid` hom."] instance subtype_mk.is_monoid_hom {γ : Type*} [monoid γ] [is_submonoid s] (f : γ → α) [is_monoid_hom f] (h : ∀ x, f x ∈ s) : is_monoid_hom (λ x, (⟨f x, h x⟩ : s)) := { map_one := subtype.eq (is_monoid_hom.map_one f), map_mul := λ x y, subtype.eq (is_monoid_hom.map_mul f x y) } /-- Given two submonoids `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is a monoid hom. -/ @[to_additive is_add_monoid_hom "Given two `add_submonoid`s `s` and `t` such that `s ⊆ t`, the natural injection from `s` into `t` is an `add_monoid` hom."] instance set_inclusion.is_monoid_hom (t : set α) [is_submonoid s] [is_submonoid t] (h : s ⊆ t) : is_monoid_hom (set.inclusion h) := subtype_mk.is_monoid_hom _ _ namespace add_monoid /-- The inductively defined membership predicate for the submonoid generated by a subset of a monoid. -/ inductive in_closure (s : set β) : β → Prop | basic {a : β} : a ∈ s → in_closure a | zero : in_closure 0 | add {a b : β} : in_closure a → in_closure b → in_closure (a + b) end add_monoid namespace monoid /-- The inductively defined membership predicate for the `add_submonoid` generated by a subset of an add_monoid. -/ inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) attribute [to_additive] monoid.in_closure attribute [to_additive] monoid.in_closure.one attribute [to_additive] monoid.in_closure.mul /-- The inductively defined submonoid generated by a subset of a monoid. -/ @[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."] def closure (s : set α) : set α := {a | in_closure s a } @[to_additive is_add_submonoid] instance closure.is_submonoid (s : set α) : is_submonoid (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul } /-- A subset of a monoid is contained in the submonoid it generates. -/ @[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."] theorem subset_closure {s : set α} : s ⊆ closure s := assume a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure_subset {s t : set α} [is_submonoid t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem] /-- Given subsets `t` and `s` of a monoid `α`, if `s ⊆ t`, the submonoid of `α` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid α`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ @[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element."] theorem closure_singleton {x : α} : closure ({x} : set α) = powers x := set.eq_of_subset_of_subset (closure_subset $ set.singleton_subset_iff.2 $ powers.self_mem) $ is_submonoid.power_subset $ set.singleton_subset_iff.1 $ subset_closure /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set under the monoid hom. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set under the `add_monoid` hom."] lemma image_closure {β : Type*} [monoid β] (f : α → β) [is_monoid_hom f] (s : set α) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) /-- Given an element `a` of the submonoid of a monoid `α` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid α` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure {s : set α} {a : α} (h : a ∈ closure s) : (∃l:list α, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `α`, `x ∈ α` is in the submonoid of `α` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid α`, `x ∈ α` is in the `add_submonoid` of `α` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure_union_iff {α : Type*} [comm_monoid α] {s t : set α} {x : α} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸ list.rec_on L (λ _, ⟨1, is_submonoid.one_mem _, 1, is_submonoid.one_mem _, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, is_submonoid.mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, is_submonoid.mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ is_submonoid.mul_mem (closure_mono (set.subset_union_left _ _) hy) (closure_mono (set.subset_union_right _ _) hz)⟩ end monoid -- Bundled submonoids and `add_submonoid`s /-- A submonoid of a monoid `α` is a subset containing 1 and closed under multiplication. -/ structure submonoid (α : Type*) [monoid α] := (carrier : set α) (one_mem' : (1 : α) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `α` is a subset containing 0 and closed under addition. -/ structure add_submonoid (α : Type*) [add_monoid α] := (carrier : set α) (zero_mem' : (0 : α) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid /-- Map from submonoids of monoid `α` to `add_submonoid`s of `additive α`. -/ def submonoid.to_add_submonoid {α : Type*} [monoid α] (S : submonoid α) : add_submonoid (additive α) := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Map from `add_submonoid`s of `additive α` to submonoids of `α`. -/ def submonoid.of_add_submonoid {α : Type*} [monoid α] (S : add_submonoid (additive α)) : submonoid α := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from `add_submonoid`s of `add_monoid α` to submonoids of `multiplicative α`. -/ def add_submonoid.to_submonoid {α : Type*} [add_monoid α] (S : add_submonoid α) : submonoid (multiplicative α) := { carrier := S.carrier, one_mem' := S.zero_mem', mul_mem' := S.add_mem' } /-- Map from submonoids of `multiplicative α` to `add_submonoid`s of `add_monoid α`. -/ def add_submonoid.of_submonoid {α : Type*} [add_monoid α] (S : submonoid (multiplicative α)) : add_submonoid α := { carrier := S.carrier, zero_mem' := S.one_mem', add_mem' := S.mul_mem' } /-- Submonoids of monoid `α` are isomorphic to additive submonoids of `additive α`. -/ def submonoid.add_submonoid_equiv (α : Type*) [monoid α] : submonoid α ≃ add_submonoid (additive α) := { to_fun := submonoid.to_add_submonoid, inv_fun := submonoid.of_add_submonoid, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace submonoid variables {M : Type*} [monoid M] (S : submonoid M) @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ S.carrier⟩ @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, S.carrier ⊆ T.carrier⟩ @[simp, to_additive] lemma mem_coe {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' {S T : submonoid M} (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : (S : set M) = T ↔ S = T := ⟨ext', λ h, h ▸ rfl⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S /-- A finite product of elements of a submonoid of a commutative monoid is in the submonoid. -/ @[to_additive "A finite sum of elements of an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} [decidable_eq ι] {t : finset ι} {f : ι → M} : (∀c ∈ t, f c ∈ S) → t.prod f ∈ S := finset.induction_on t (by simp [S.one_mem]) (by simp [S.mul_mem] {contextual := tt}) /-- A directed union of submonoids is a submonoid. -/ @[to_additive "A directed union of `add_submonoid`s is an `add_submonoid`."] def Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → submonoid M) (directed : ∀ i j, ∃ k, s i ≤ s k ∧ s j ≤ s k) : submonoid M := { carrier := (⋃i, s i), one_mem' := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, submonoid.one_mem _⟩, mul_mem' := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, (s k).mul_mem (hk.1 hi) (hk.2 hj)⟩ } /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive to_add_monoid "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] {S : submonoid M} : monoid S := by refine { mul := (*), one := 1, ..}; by simp [mul_assoc] /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive to_add_comm_monoid "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := { mul_comm := λ _ _, subtype.ext.2 $ mul_comm _ _, ..submonoid.to_monoid} /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] theorem subtype_apply (x : S) : S.subtype x = x := rfl @[to_additive] lemma subtype_eq_val : (S.subtype : S → M) = subtype.val := rfl /-- The powers `1, x, x², ...` of an element `x` of a monoid `M` are a submonoid. -/ def powers (x : M) : submonoid M := { carrier := {y | ∃ n:ℕ, x^n = y}, one_mem' := ⟨0, pow_zero x⟩, mul_mem' := by rintros x₁ x₂ ⟨n₁, rfl⟩ ⟨n₂, rfl⟩; exact ⟨n₁ + n₂, pow_add _ _ _ ⟩ } /-- An element `x` of a monoid is in the submonoid generated by `x`. -/ lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- If `a` is in a submonoid, so are all its natural number powers. -/ lemma pow_mem {a : M} (h : a ∈ S) : ∀ {n : ℕ}, a ^ n ∈ S | 0 := S.one_mem | (n + 1) := S.mul_mem h pow_mem lemma powers_subset {a : M} (h : a ∈ S) : powers a ≤ S := assume x ⟨n, hx⟩, hx ▸ S.pow_mem h @[simp] lemma coe_pow (a : S) (n : ℕ) : ((a ^ n : S) : M) = a ^ n := by induction n; simp [*, pow_succ] end submonoid namespace add_submonoid variables {M : Type*} [add_monoid M] (S : add_submonoid M) /-- The multiples `0, x, 2x, ...` of an element `x` of an `add_monoid M` are an `add_submonoid`. -/ def multiples (x : M) : add_submonoid M := { carrier := {y | ∃ n:ℕ, add_monoid.smul n x = y}, zero_mem' := ⟨0, add_monoid.zero_smul x⟩, add_mem' := by rintros x₁ x₂ ⟨n₁, rfl⟩ ⟨n₂, rfl⟩; exact ⟨n₁ + n₂, add_monoid.add_smul _ _ _ ⟩ } /-- An element `x` of an `add_monoid` is in the `add_submonoid` generated by `x`. -/ lemma multiples.self_mem {x : M} : x ∈ multiples x := ⟨1, add_monoid.one_smul x⟩ lemma smul_mem {a : M} (h : a ∈ S) {n : ℕ} : add_monoid.smul n a ∈ S := submonoid.pow_mem (add_submonoid.to_submonoid S) h lemma multiples_subset {a : M} (h : a ∈ S) : multiples a ≤ S := submonoid.powers_subset (add_submonoid.to_submonoid S) h @[simp] lemma coe_smul (a : S) (n : ℕ) : ((add_monoid.smul n a : S) : M) = add_monoid.smul n a := submonoid.coe_pow (add_submonoid.to_submonoid S) a n end add_submonoid namespace submonoid variables {M : Type*} [monoid M] (S : submonoid M) /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The `add_submonoid M` of the `add_monoid M`."] def univ : submonoid M := { carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ } /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] def bot : submonoid M := { carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by simp * at *} /-- Submonoids of a monoid are partially ordered (by inclusion). -/ @[to_additive "The `add_submonoid`s of an `add_monoid` are partially ordered (by inclusion)."] instance : partial_order (submonoid M) := partial_order.lift (coe : submonoid M → set M) (λ a b, ext') (by apply_instance) @[to_additive] lemma le_def (p p' : submonoid M) : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl open lattice @[to_additive] instance : has_bot (submonoid M) := ⟨submonoid.bot⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[to_additive] instance : order_bot (submonoid M) := { bot := ⊥, bot_le := λ P x hx, by simp * at *; exact P.one_mem, ..submonoid.partial_order } @[to_additive] instance : has_top (submonoid M) := ⟨univ⟩ @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[to_additive] instance : order_top (submonoid M) := { top := ⊤, le_top := λ p x _, mem_top x, ..submonoid.partial_order} /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] def inf (S₁ S₂ : submonoid M) : submonoid M := { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ } @[to_additive] instance : has_inf (submonoid M) := ⟨inf⟩ @[to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := ⟨λ h, ⟨h.1, h.2⟩, λ h, (p ⊓ p').mem_coe.2 ⟨h.1, h.2⟩⟩ @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[to_additive] lemma Inf_le' {S : set (submonoid M)} {p} : p ∈ S → Inf S ≤ p := set.bInter_subset_of_mem @[to_additive] lemma le_Inf' {S : set (submonoid M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := set.subset_bInter @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff /-- Submonoids of a monoid form a lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a lattice."] instance lattice.lattice : lattice (submonoid 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 ha hb, set.subset_inter ha hb, inf_le_left := λ a b, set.inter_subset_left _ _, inf_le_right := λ a b, set.inter_subset_right _ _, ..submonoid.partial_order} /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { 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', ..submonoid.lattice.order_top, ..submonoid.lattice.order_bot, ..submonoid.lattice.lattice} /-- Submonoids of a monoid form an `add_comm_monoid`. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form an `add_comm_monoid`."] instance complete_lattice.add_comm_monoid : add_comm_monoid (submonoid M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } end submonoid namespace monoid_hom variables {M : Type*} [monoid M] (S : submonoid M) open submonoid /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap {N : Type*} [monoid N] (f : M →* N) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw f.map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw f.map_mul; exact S.mul_mem ha hb } /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map {N : Type*} [monoid N] (f : M →* N) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, f.map_one⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw f.map_mul; refl⟩ end } /-- The range of a monoid homomorphism is a submonoid. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def range {N : Type*} [monoid N] (f : M →* N) : submonoid N := map f univ end monoid_hom namespace submonoid variables {M : Type*} [monoid M] (S : submonoid M) /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem : ∀ {l : list M}, (∀x∈l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by simpa, have a ∈ S ∧ (∀ x ∈ l, x ∈ S), by simpa using h, S.mul_mem this.1 (list_prod_mem this.2) /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma finset_prod_mem {M ι} [comm_monoid M] (S : submonoid M) (f : ι → M) : ∀(t : finset ι), (∀b∈t, f b ∈ S) → t.prod f ∈ S | ⟨m, hm⟩ hs := begin refine S.multiset_prod_mem _ _, suffices : ∀ (a : M) (x : ι), x ∈ m → f x = a → a ∈ S, simpa using this, rintros a b hb rfl, exact hs _ hb end end submonoid namespace monoid_hom variables {M : Type*} [monoid M] (S : submonoid M) /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain."] def subtype_mk {N : Type*} [monoid N] (f : N →* M) (h : ∀ x, f x ∈ S) : N →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq (is_monoid_hom.map_one f), map_mul' := λ x y, subtype.eq (is_monoid_hom.map_mul f x y) } /-- Restriction of a monoid hom to its range. -/ @[to_additive "Restriction of an `add_monoid` hom to its range."] def range_mk {N} [monoid N] (f : M →* N) : M →* f.range := subtype_mk f.range f $ λ x, ⟨x, submonoid.mem_top x, rfl⟩ /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma range_top_of_surjective {N} [monoid N] (f : M →* N) (hf : function.surjective f) : f.range = (⊤ : submonoid N) := submonoid.ext'_iff.1 $ (set.ext_iff _ _).2 $ λ x, ⟨λ h, submonoid.mem_top x, λ h, exists.elim (hf x) $ λ w hw, ⟨w, submonoid.mem_top w, hw⟩⟩ /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def set_inclusion (T : submonoid M) (h : S ≤ T) : S →* T := subtype_mk _ S.subtype (λ x, h x.2) end monoid_hom namespace monoid variables {M : Type*} [monoid M] (S : submonoid M) open submonoid /-- The inductively defined submonoid generated by a set. -/ @[to_additive "The inductively defined `add_submonoid` generated by a set. "] def closure' (s : set M) : submonoid M := { carrier := in_closure s, one_mem' := in_closure.one s, mul_mem' := λ _ _, in_closure.mul} /-- The submonoid generated by a set contains the set. -/ @[to_additive "The `add_submonoid` generated by a set contains the set."] theorem le_closure' {s : set M} : s ≤ closure' s := λ a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure'_le {s : set M} {T : submonoid M} (h : s ≤ T) : closure' s ≤ T := λ a ha, begin induction ha with _ hb _ _ _ _ ha hb, {exact h hb }, {exact T.one_mem }, {exact T.mul_mem ha hb } end /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid` `M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure'_mono {s t : set M} (h : s ≤ t) : closure' s ≤ closure' t := closure'_le $ set.subset.trans h le_closure' /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ theorem closure'_singleton {x : M} : closure' ({x} : set M) = powers x := ext' $ set.eq_of_subset_of_subset (closure'_le $ set.singleton_subset_iff.2 powers.self_mem) $ submonoid.powers_subset _ $ in_closure.basic $ set.mem_singleton x /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma image_closure' {N : Type*} [monoid N] (f : M →* N) (s : set M) : f.map (closure' s) = closure' (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [le_closure', set.mem_image_of_mem] }, { rw f.map_one, apply submonoid.one_mem }, { rw f.map_mul, solve_by_elim [submonoid.mul_mem] } end (closure'_le $ set.image_subset _ le_closure') /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid` `M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure' {s : set M} {a : M} (h : a ∈ closure' s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid` `M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure'_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure' (s ∪ t) ↔ ∃ y ∈ closure' s, ∃ z ∈ closure' t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure' hx in HL2 ▸ list.rec_on L (λ _, ⟨1, submonoid.one_mem _, 1, submonoid.one_mem _, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, submonoid.mul_mem _ (le_closure' hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, submonoid.mul_mem _ hz (le_closure' ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ submonoid.mul_mem _ ((closure_mono (set.subset_union_left s t)) hy) ((closure_mono (set.subset_union_right s t)) hz)⟩ end monoid namespace add_monoid open add_submonoid /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ theorem closure'_singleton {x : β} : closure' ({x} : set β) = multiples x := ext' $ set.eq_of_subset_of_subset (closure'_le $ set.singleton_subset_iff.2 multiples.self_mem) $ multiples_subset _ $ in_closure.basic $ set.mem_singleton x end add_monoid
87386bfc6c4272b747e9abaf7020d3adeb06a2c9
1901b51268d21ec7361af7d3534abd9a8fa5cf52
/src/graph_theory/planar.lean
19ff655f50d3cee7ef800b45d35ed70adb4df411
[]
no_license
vbeffara/lean
b9ea4107deeaca6f4da98e5de029b62e4861ab40
0004b1d502ac3f4ccd213dbd23589d4c4f9fece8
refs/heads/main
1,652,050,034,756
1,651,610,858,000
1,651,610,858,000
225,244,535
6
1
null
null
null
null
UTF-8
Lean
false
false
1,624
lean
import tactic import graph_theory.minor graph_theory.product analysis.complex.basic namespace simple_graph def Z : simple_graph ℤ := { adj := λ x y, |x-y| = 1, symm := λ x y h, by { rw ←h, convert abs_neg _, ring }, loopless := λ x, by simp only [sub_self, abs_zero, zero_ne_one, not_false_iff] } variables {V V' : Type*} {G : simple_graph V} {G' : simple_graph V'} def plane : simple_graph (ℤ × ℤ) := Z □ Z namespace plane variables {x x' y y' z z' : ℤ} open walk def flip : plane →g plane := { to_fun := prod.swap, map_rel' := by { rintros ⟨x,y⟩ ⟨x',y'⟩ h, cases h, { right, exact and.symm h }, { left, exact and.symm h } } } lemma horiz_path_aux : ∀ (n : ℕ), reachable plane (x,y) (x+n,y) | 0 := by simp | (n+1) := by { refine reachable.trans (horiz_path_aux n) (reachable.step (or.inr _)), simp [Z] } lemma horiz_path : reachable plane (x,y) (x',y) := begin by_cases (x'-x>=0), { obtain ⟨n,hn⟩ := int.eq_coe_of_zero_le h, convert horiz_path_aux n, linarith }, { replace h : x-x' ≥ 0, by linarith, obtain ⟨n,hn⟩ := int.eq_coe_of_zero_le h, symmetry, convert (@horiz_path_aux x' y n), linarith } end lemma vert_path : reachable plane (x,y) (x,y') := by { obtain ⟨p⟩ := horiz_path, use p.map flip } lemma connected_plane : connected plane := ⟨λ ⟨x,y⟩ ⟨x',y'⟩, reachable.trans horiz_path vert_path, ⟨(0,0)⟩⟩ end plane def K5 := complete_graph (finset.range 5) def K33 := complete_bipartite_graph (finset.range 3) (finset.range 3) -- theorem kuratowski [fintype V] : G ≼ plane ↔ K5 ⋠ G ∧ K33 ⋠ G end simple_graph
982de0f0dd7d4974003d05684b7bb41a552d2ef9
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/examples/lean/wf.lean
e798f706cb2eb8c5f559dceb8071268756678e1a
[ "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
2,454
lean
import macros -- Well-founded relation definition -- We are essentially saying that a relation R is well-founded -- if every non-empty "set" P, has a R-minimal element definition wf {A : (Type U)} (R : A → A → Bool) : Bool := ∀ P, (∃ w, P w) → ∃ min, P min ∧ ∀ b, R b min → ¬ P b -- Well-founded induction theorem theorem wf_induction {A : (Type U)} {R : A → A → Bool} {P : A → Bool} (Hwf : wf R) (iH : ∀ x, (∀ y, R y x → P y) → P x) : ∀ x, P x := by_contradiction (assume N : ¬ ∀ x, P x, obtain (w : A) (Hw : ¬ P w), from not_forall_elim N, -- The main "trick" is to define Q x as ¬ P x. -- Since R is well-founded, there must be a R-minimal element r s.t. Q r (which is ¬ P r) let Q : A → Bool := λ x, ¬ P x in have Qw : ∃ w, Q w, from exists_intro w Hw, have Qwf : ∃ min, Q min ∧ ∀ b, R b min → ¬ Q b, from Hwf Q Qw, obtain (r : A) (Hr : Q r ∧ ∀ b, R b r → ¬ Q b), from Qwf, -- Using the inductive hypothesis iH and Hr, we show P r, and derive the contradiction. have s1 : ∀ b, R b r → P b, from take b : A, assume H : R b r, -- We are using Hr to derive ¬ ¬ P b not_not_elim (and_elimr Hr b H), have s2 : P r, from iH r s1, have s3 : ¬ P r, from and_eliml Hr, show false, from absurd s2 s3) -- More compact proof theorem wf_induction2 {A : (Type U)} {R : A → A → Bool} {P : A → Bool} (Hwf : wf R) (iH : ∀ x, (∀ y, R y x → P y) → P x) : ∀ x, P x := by_contradiction (assume N : ¬ ∀ x, P x, obtain (w : A) (Hw : ¬ P w), from not_forall_elim N, -- The main "trick" is to define Q x as ¬ P x. -- Since R is well-founded, there must be a R-minimal element r s.t. Q r (which is ¬ P r) let Q : A → Bool := λ x, ¬ P x in obtain (r : A) (Hr : Q r ∧ ∀ b, R b r → ¬ Q b), from Hwf Q (exists_intro w Hw), -- Using the inductive hypothesis iH and Hr, we show P r, and derive the contradiction. have s1 : ∀ b, R b r → P b, from take b : A, assume H : R b r, -- We are using Hr to derive ¬ ¬ P b not_not_elim (and_elimr Hr b H), absurd (iH r s1) (and_eliml Hr))
b6fe0f69dfe5a7646baded7b70312b0b96a26810
4727251e0cd73359b15b664c3170e5d754078599
/src/data/fun_like/basic.lean
1a315797950823e3d9c4f31662e49c03feb36ebf
[ "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
6,809
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import logic.function.basic import tactic.lint import tactic.norm_cast /-! # Typeclass for a type `F` with an injective map to `A → B` This typeclass is primarily for use by homomorphisms like `monoid_hom` and `linear_map`. ## Basic usage of `fun_like` A typical type of morphisms should be declared as: ``` structure my_hom (A B : Type*) [my_class A] [my_class B] := (to_fun : A → B) (map_op' : ∀ {x y : A}, to_fun (my_class.op x y) = my_class.op (to_fun x) (to_fun y)) namespace my_hom variables (A B : Type*) [my_class A] [my_class B] -- This instance is optional if you follow the "morphism class" design below: instance : fun_like (my_hom A B) A (λ _, B) := { coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (my_hom A B) (λ _, A → B) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : my_hom A B} : f.to_fun = (f : A → B) := rfl @[ext] theorem ext {f g : my_hom A B} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h /-- Copy of a `my_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : my_hom A B) (f' : A → B) (h : f' = ⇑f) : my_hom A B := { to_fun := f', map_op' := h.symm ▸ f.map_op' } end my_hom ``` This file will then provide a `has_coe_to_fun` instance and various extensionality and simp lemmas. ## Morphism classes extending `fun_like` The `fun_like` design provides further benefits if you put in a bit more work. The first step is to extend `fun_like` to create a class of those types satisfying the axioms of your new type of morphisms. Continuing the example above: ``` /-- `my_hom_class F A B` states that `F` is a type of `my_class.op`-preserving morphisms. You should extend this class when you extend `my_hom`. -/ class my_hom_class (F : Type*) (A B : out_param $ Type*) [my_class A] [my_class B] extends fun_like F A (λ _, B) := (map_op : ∀ (f : F) (x y : A), f (my_class.op x y) = my_class.op (f x) (f y)) @[simp] lemma map_op {F A B : Type*} [my_class A] [my_class B] [my_hom_class F A B] (f : F) (x y : A) : f (my_class.op x y) = my_class.op (f x) (f y) := my_hom_class.map_op -- You can replace `my_hom.fun_like` with the below instance: instance : my_hom_class (my_hom A B) A B := { coe := my_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_op := my_hom.map_op' } -- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here] ``` The second step is to add instances of your new `my_hom_class` for all types extending `my_hom`. Typically, you can just declare a new class analogous to `my_hom_class`: ``` structure cooler_hom (A B : Type*) [cool_class A] [cool_class B] extends my_hom A B := (map_cool' : to_fun cool_class.cool = cool_class.cool) class cooler_hom_class (F : Type*) (A B : out_param $ Type*) [cool_class A] [cool_class B] extends my_hom_class F A B := (map_cool : ∀ (f : F), f cool_class.cool = cool_class.cool) @[simp] lemma map_cool {F A B : Type*} [cool_class A] [cool_class B] [cooler_hom_class F A B] (f : F) : f cool_class.cool = cool_class.cool := my_hom_class.map_op -- You can also replace `my_hom.fun_like` with the below instance: instance : cool_hom_class (cool_hom A B) A B := { coe := cool_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_op := cool_hom.map_op', map_cool := cool_hom.map_cool' } -- [Insert `has_coe_to_fun`, `to_fun_eq_coe`, `ext` and `copy` here] ``` Then any declaration taking a specific type of morphisms as parameter can instead take the class you just defined: ``` -- Compare with: lemma do_something (f : my_hom A B) : sorry := sorry lemma do_something {F : Type*} [my_hom_class F A B] (f : F) : sorry := sorry ``` This means anything set up for `my_hom`s will automatically work for `cool_hom_class`es, and defining `cool_hom_class` only takes a constant amount of effort, instead of linearly increasing the work per `my_hom`-related declaration. -/ -- This instance should have low priority, to ensure we follow the chain -- `fun_like → has_coe_to_fun` attribute [instance, priority 10] coe_fn_trans /-- The class `fun_like F α β` expresses that terms of type `F` have an injective coercion to functions from `α` to `β`. This typeclass is used in the definition of the homomorphism typeclasses, such as `zero_hom_class`, `mul_hom_class`, `monoid_hom_class`, .... -/ class fun_like (F : Sort*) (α : out_param Sort*) (β : out_param $ α → Sort*) := (coe : F → Π a : α, β a) (coe_injective' : function.injective coe) section dependent /-! ### `fun_like F α β` where `β` depends on `a : α` -/ variables (F α : Sort*) (β : α → Sort*) namespace fun_like variables {F α β} [i : fun_like F α β] include i @[priority 100, -- Give this a priority between `coe_fn_trans` and the default priority nolint dangerous_instance] -- `α` and `β` are out_params, so this instance should not be dangerous instance : has_coe_to_fun F (λ _, Π a : α, β a) := { coe := fun_like.coe } @[simp] lemma coe_eq_coe_fn : (fun_like.coe : F → Π a : α, β a) = coe_fn := rfl theorem coe_injective : function.injective (coe_fn : F → Π a : α, β a) := fun_like.coe_injective' @[simp, norm_cast] theorem coe_fn_eq {f g : F} : (f : Π a : α, β a) = (g : Π a : α, β a) ↔ f = g := ⟨λ h, @coe_injective _ _ _ i _ _ h, λ h, by cases h; refl⟩ theorem ext' {f g : F} (h : (f : Π a : α, β a) = (g : Π a : α, β a)) : f = g := coe_injective h theorem ext'_iff {f g : F} : f = g ↔ ((f : Π a : α, β a) = (g : Π a : α, β a)) := coe_fn_eq.symm theorem ext (f g : F) (h : ∀ (x : α), f x = g x) : f = g := coe_injective (funext h) theorem ext_iff {f g : F} : f = g ↔ (∀ x, f x = g x) := coe_fn_eq.symm.trans function.funext_iff protected lemma congr_fun {f g : F} (h₁ : f = g) (x : α) : f x = g x := congr_fun (congr_arg _ h₁) x lemma ne_iff {f g : F} : f ≠ g ↔ ∃ a, f a ≠ g a := ext_iff.not.trans not_forall lemma exists_ne {f g : F} (h : f ≠ g) : ∃ x, f x ≠ g x := ne_iff.mp h end fun_like end dependent section non_dependent /-! ### `fun_like F α (λ _, β)` where `β` does not depend on `a : α` -/ variables {F α β : Sort*} [i : fun_like F α (λ _, β)] include i namespace fun_like protected lemma congr {f g : F} {x y : α} (h₁ : f = g) (h₂ : x = y) : f x = g y := congr (congr_arg _ h₁) h₂ protected lemma congr_arg (f : F) {x y : α} (h₂ : x = y) : f x = f y := congr_arg _ h₂ end fun_like end non_dependent
dc5bff5c509fd42d37db123fd6d46a467b4b6db3
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/for_mathlib/normed_group_hom.lean
48e1fd6e4909fcede3621c94fab26b14579d1367
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,368
lean
import analysis.normed_space.normed_group_hom import analysis.specific_limits noncomputable theory open_locale filter topological_space big_operators open set normed_group_hom uniform_space filter finset def normed_group_hom.surjective_on_with {G H : Type*} [semi_normed_group G] [semi_normed_group H] (f : normed_group_hom G H) (K : add_subgroup H) (C : ℝ) : Prop := ∀ h ∈ K, ∃ g, f g = h ∧ ∥g∥ ≤ C*∥h∥ variables {G : Type*} [normed_group G] variables {H : Type*} [normed_group H] lemma controlled_closure_of_complete [complete_space G] {f : normed_group_hom G H} {K : add_subgroup H} {C ε : ℝ} (hC : 0 < C) (hε : 0 < ε) (hyp : f.surjective_on_with K C) : f.surjective_on_with K.topological_closure (C + ε) := begin intros h h_in, by_cases hyp_h : h = 0, { rw hyp_h, use 0, simp }, set b : ℕ → ℝ := λ i, (1/2)^i*(ε*∥h∥/2)/C, have b_pos : ∀ i, 0 < b i, { intro i, field_simp [b, hC], exact div_pos (mul_pos hε (norm_pos_iff.mpr hyp_h)) (mul_pos (by norm_num : (0 : ℝ) < 2^i*2) hC) }, obtain ⟨v : ℕ → H, lim_v : tendsto (λ (n : ℕ), ∑ k in range (n + 1), v k) at_top (𝓝 h), v_in : ∀ n, v n ∈ K, hv₀ : ∥v 0 - h∥ < b 0, hv : ∀ n > 0, ∥v n∥ < b n⟩ := controlled_sum_of_mem_closure h_in b_pos, have : ∀ n, ∃ m' : G, f m' = v n ∧ ∥m'∥ ≤ C * ∥v n∥, exact λ (n : ℕ), hyp (v n) (v_in n), choose u hu hnorm_u using this, set s : ℕ → G := λ n, ∑ k in range (n+1), u k, have : cauchy_seq s, { apply normed_group.cauchy_series_of_le_geometric'' (by norm_num) one_half_lt_one, rintro n (hn : n ≥ 1), calc ∥u n∥ ≤ C*∥v n∥ : hnorm_u n ... ≤ C * b n : mul_le_mul_of_nonneg_left (hv _ $ nat.succ_le_iff.mp hn).le hC.le ... = (1/2)^n * (ε * ∥h∥/2) : by simp [b, mul_div_cancel' _ hC.ne.symm] ... = (ε * ∥h∥/2) * (1/2)^n : mul_comm _ _ }, obtain ⟨g : G, hg⟩ := cauchy_seq_tendsto_of_complete this, refine ⟨g, _, _⟩, { apply tendsto_nhds_unique _ lim_v, convert (f.continuous.tendsto g).comp hg, ext n, simp [f.map_sum, hu] }, { suffices : ∀ n, ∥s n∥ ≤ (C + ε) * ∥h∥, from le_of_tendsto' (continuous_norm.continuous_at.tendsto.comp hg) this, intros n, have hnorm₀ : ∥u 0∥ ≤ C*b 0 + C*∥h∥, { have := calc ∥v 0∥ ≤ ∥h∥ + ∥v 0 - h∥ : norm_le_insert' _ _ ... ≤ ∥h∥ + b 0 : by apply add_le_add_left hv₀.le, calc ∥u 0∥ ≤ C*∥v 0∥ : hnorm_u 0 ... ≤ C*(∥h∥ + b 0) : mul_le_mul_of_nonneg_left this hC.le ... = C * b 0 + C * ∥h∥ : by rw [add_comm, mul_add] }, have : ∑ k in range (n + 1), C * b k ≤ ε * ∥h∥, { calc ∑ k in range (n + 1), C * b k = (∑ k in range (n + 1), (1 / 2) ^ k) * (ε * ∥h∥ / 2) : by simp only [b, mul_div_cancel' _ hC.ne.symm, ← sum_mul] ... ≤ 2 * (ε * ∥h∥ / 2) : mul_le_mul_of_nonneg_right (sum_geometric_two_le _) (by nlinarith [hε, norm_nonneg h]) ... = ε * ∥h∥ : mul_div_cancel' _ two_ne_zero }, calc ∥s n∥ ≤ ∑ k in range (n+1), ∥u k∥ : norm_sum_le _ _ ... = ∑ k in range n, ∥u (k + 1)∥ + ∥u 0∥ : sum_range_succ' _ _ ... ≤ ∑ k in range n, C*∥v (k + 1)∥ + ∥u 0∥ : add_le_add_right (sum_le_sum (λ _ _, hnorm_u _)) _ ... ≤ ∑ k in range n, C*b (k+1) + (C*b 0 + C*∥h∥) : add_le_add (sum_le_sum (λ k _, _)) hnorm₀ ... = ∑ k in range (n+1), C*b k + C*∥h∥ : _ ... ≤ (C+ε)*∥h∥ : _, { exact mul_le_mul_of_nonneg_left (hv _ k.succ_pos).le hC.le }, { rw [← add_assoc, sum_range_succ'] }, { rw [add_comm, add_mul], apply add_le_add_left this } } end lemma controlled_closure_range_of_complete [complete_space G] {f : normed_group_hom G H} {K : Type*} [semi_normed_group K] {j : normed_group_hom K H} (hj : ∀ x, ∥j x∥ = ∥x∥) {C ε : ℝ} (hC : 0 < C) (hε : 0 < ε) (hyp : ∀ k, ∃ g, f g = j k ∧ ∥g∥ ≤ C*∥k∥) : ∀ {h}, h ∈ j.range.topological_closure → ∃ g, f g = h ∧ ∥g∥ ≤ (C + ε)*∥h∥ := begin replace hyp : ∀ h ∈ j.range, ∃ g, f g = h ∧ ∥g∥ ≤ C*∥h∥, { intros h h_in, rcases (j.mem_range _).mp h_in with ⟨k, rfl⟩, rw hj, exact hyp k }, exact controlled_closure_of_complete hC hε hyp end
aae539028999beb9baadff3e66b4167a611117f2
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/occurs_check_bug1.lean
11fdd9d0d81f15874dd3c924b8c89f33e8c54bef
[ "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
478
lean
import logic data.nat data.prod open nat prod open decidable constant modulo (x : ℕ) (y : ℕ) : ℕ infixl `mod` := modulo constant gcd_aux : ℕ × ℕ → ℕ definition gcd (x y : ℕ) : ℕ := gcd_aux (pair x y) theorem gcd_def (x y : ℕ) : gcd x y = @ite (y = 0) (nat.has_decidable_eq (pr2 (pair x y)) 0) nat x (gcd y (x mod y)) := sorry theorem gcd_succ (m n : ℕ) : gcd m (succ n) = gcd (succ n) (m mod succ n) := eq.trans (gcd_def _ _) (if_neg !succ_ne_zero)
4b0af6506266d0a70367d0082e1b49e8a791ad7d
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/seq/wseq.lean
a28b034e48dfd739008e600ddea7ed4637def380
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
55,116
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.seq.seq data.seq.computation data.dlist universes u v w /- coinductive wseq (α : Type u) : Type u | nil : wseq α | cons : α → wseq α → wseq α | think : wseq α → wseq α -/ /-- Weak sequences. While the `seq` structure allows for lists which may not be finite, a weak sequence also allows the computation of each element to involve an indeterminate amount of computation, including possibly an infinite loop. This is represented as a regular `seq` interspersed with `none` elements to indicate that computation is ongoing. This model is appropriate for Haskell style lazy lists, and is closed under most interesting computation patterns on infinite lists, but conversely it is difficult to extract elements from it. -/ def wseq (α) := seq (option α) namespace wseq variables {α : Type u} {β : Type v} {γ : Type w} /-- Turn a sequence into a weak sequence -/ def of_seq : seq α → wseq α := (<$>) some /-- Turn a list into a weak sequence -/ def of_list (l : list α) : wseq α := of_seq l /-- Turn a stream into a weak sequence -/ def of_stream (l : stream α) : wseq α := of_seq l instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩ instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩ instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩ /-- The empty weak sequence -/ def nil : wseq α := seq.nil instance : inhabited (wseq α) := ⟨nil⟩ /-- Prepend an element to a weak sequence -/ def cons (a : α) : wseq α → wseq α := seq.cons (some a) /-- Compute for one tick, without producing any elements -/ def think : wseq α → wseq α := seq.cons none /-- Destruct a weak sequence, to (eventually possibly) produce either `none` for `nil` or `some (a, s)` if an element is produced. -/ def destruct : wseq α → computation (option (α × wseq α)) := computation.corec (λs, match seq.destruct s with | none := sum.inl none | some (none, s') := sum.inr s' | some (some a, s') := sum.inl (some (a, s')) end) def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := seq.cases_on s h1 (λ o, option.cases_on o h3 h2) protected def mem (a : α) (s : wseq α) := seq.mem (some a) s instance : has_mem α (wseq α) := ⟨wseq.mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a /-- Get the head of a weak sequence. This involves a possibly infinite computation. -/ def head (s : wseq α) : computation (option α) := computation.map ((<$>) prod.fst) (destruct s) /-- Encode a computation yielding a weak sequence into additional `think` constructors in a weak sequence -/ def flatten : computation (wseq α) → wseq α := seq.corec (λc, match computation.destruct c with | sum.inl s := seq.omap return (seq.destruct s) | sum.inr c' := some (none, c') end) /-- Get the tail of a weak sequence. This doesn't need a `computation` wrapper, unlike `head`, because `flatten` allows us to hide this in the construction of the weak sequence itself. -/ def tail (s : wseq α) : wseq α := flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s /-- drop the first `n` elements from `s`. -/ def drop (s : wseq α) : ℕ → wseq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Get the nth element of `s`. -/ def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n) /-- Convert `s` to a list (if it is finite and completes in finite time). -/ def to_list (s : wseq α) : computation (list α) := @computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩, match seq.destruct s with | none := sum.inl l.reverse | some (none, s') := sum.inr (l, s') | some (some a, s') := sum.inr (a::l, s') end) ([], s) /-- Get the length of `s` (if it is finite and completes in finite time). -/ def length (s : wseq α) : computation ℕ := @computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s with | none := sum.inl n | some (none, s') := sum.inr (n, s') | some (some a, s') := sum.inr (n+1, s') end) (0, s) /-- A weak sequence is finite if `to_list s` terminates. Equivalently, it is a finite number of `think` and `cons` applied to `nil`. -/ @[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h /-- Get the list corresponding to a finite weak sequence. -/ def get (s : wseq α) [is_finite s] : list α := (to_list s).get /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ @[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0 /-- Replace the `n`th element of `s` with `a`. -/ def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (some a, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Remove the `n`th element of `s`. -/ def remove_nth (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (none, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Map the elements of `s` over `f`, removing any values that yield `none`. -/ def filter_map (f : α → option β) : wseq α → wseq β := seq.corec (λs, match seq.destruct s with | none := none | some (none, s') := some (none, s') | some (some a, s') := some (f a, s') end) /-- Select the elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α := filter_map (λa, if p a then some a else none) -- example of infinite list manipulations /-- Get the first element of `s` satisfying `p`. -/ def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) := head $ filter p s /-- Zip a function over two weak sequences -/ def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ := @seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (none, s1, s2') | some (none, s1'), some (some a2, s2') := some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2') | _, _ := none end) (s1, s2) /-- Zip two weak sequences into a single sequence of pairs -/ def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk /-- Get the list of indexes of elements of `s` satisfying `p` -/ def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ := (zip s (stream.nats : wseq ℕ)).filter_map (λ ⟨a, n⟩, if p a then some n else none) /-- Get the index of the first element of `s` satisfying `p` -/ def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ := (λ o, option.get_or_else o 0) <$> head (find_indexes p s) /-- Get the index of the first occurrence of `a` in `s` -/ def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a) /-- Get the indexes of occurrences of `a` in `s` -/ def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a) /-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in some order (nondeterministically). -/ def union (s1 s2 : wseq α) : wseq α := @seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | none, none := none | some (a1, s1'), none := some (a1, s1', nil) | none, some (a2, s2') := some (a2, nil, s2') | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') := some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2') end) (s1, s2) /-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/ def is_empty (s : wseq α) : computation bool := computation.map option.is_none $ head s /-- Calculate one step of computation -/ def compute (s : wseq α) : wseq α := match seq.destruct s with | some (none, s') := s' | _ := s end /-- Get the first `n` elements of a weak sequence -/ def take (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match n, seq.destruct s with | 0, _ := none | m+1, none := none | m+1, some (none, s') := some (none, m+1, s') | m+1, some (some a, s') := some (some a, m, s') end) (n, s) /-- Split the sequence at position `n` into a finite initial segment and the weak sequence tail -/ def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) := @computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩, match n, seq.destruct s with | 0, _ := sum.inl (l.reverse, s) | m+1, none := sum.inl (l.reverse, s) | m+1, some (none, s') := sum.inr (n, l, s') | m+1, some (some a, s') := sum.inr (m, a::l, s') end) (n, [], s) /-- Returns `tt` if any element of `s` satisfies `p` -/ def any (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl ff | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inl tt else sum.inr s' end) s /-- Returns `tt` if every element of `s` satisfies `p` -/ def all (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl tt | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inr s' else sum.inl ff end) s /-- Apply a function to the elements of the sequence to produce a sequence of partial results. (There is no `scanr` because this would require working from the end of the sequence, which may not exist.) -/ def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α := cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, a, s') | some (some b, s') := let a' := f a b in some (some a', a', s') end) (a, s) /-- Get the weak sequence of initial segments of the input sequence -/ def inits (s : wseq α) : wseq (list α) := cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, l, s') | some (some a, s') := let l' := l.concat a in some (some l'.to_list, l', s') end) (dlist.empty, s) /-- Like take, but does not wait for a result. Calculates `n` steps of computation and returns the sequence computed so far -/ def collect (s : wseq α) (n : ℕ) : list α := (seq.take n s).filter_map id /-- Append two weak sequences. As with `seq.append`, this may not use the second sequence if the first one takes forever to compute -/ def append : wseq α → wseq α → wseq α := seq.append /-- Map a function over a weak sequence -/ def map (f : α → β) : wseq α → wseq β := seq.map (option.map f) /-- Flatten a sequence of weak sequences. (Note that this allows empty sequences, unlike `seq.join`.) -/ def join (S : wseq (wseq α)) : wseq α := seq.join ((λo : option (wseq α), match o with | none := seq1.ret none | some s := (none, s) end) <$> S) /-- Monadic bind operator for weak sequences -/ def bind (s : wseq α) (f : α → wseq β) : wseq β := join (map f s) @[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) : option (α × wseq α) → option (β × wseq β) → Prop | none none := true | (some (a, s)) (some (b, t)) := R a b ∧ C s t | _ _ := false theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p | none none h := trivial | (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h | none (some _) h := false.elim h | (some (_, _)) none h := false.elim h theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p := lift_rel_o.imp (λ _ _, id) H @[simp] def bisim_o (R : wseq α → wseq α → Prop) : option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : bisim_o R o p → bisim_o S o p := lift_rel_o.imp_right _ H /-- Two weak sequences are `lift_rel R` related if they are either both empty, or they are both nonempty and the heads are `R` related and the tails are `lift_rel R` related. (This is a coinductive definition.) -/ def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop := ∃ C : wseq α → wseq β → Prop, C s t ∧ ∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t) /-- If two sequences are equivalent, then they have the same values and the same computational behavior (i.e. if one loops forever then so does the other), although they may differ in the number of `think`s needed to arrive at the answer. -/ def equiv : wseq α → wseq α → Prop := lift_rel (=) theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ := by refine computation.lift_rel.imp _ _ _ (h2 h1); apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩ theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) := ⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), or.inr h, λ s t h, begin have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), { cases h with h h, exact lift_rel_destruct h, assumption }, apply computation.lift_rel.imp _ _ _ h, intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end⟩⟩ infix ~ := equiv theorem destruct_congr {s t : wseq α} : s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct theorem destruct_congr_iff {s t : wseq α} : s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct_iff theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, begin refine ⟨(=), rfl, λ s t (h : s = t), _⟩, rw ←h, apply computation.lift_rel.refl, intro a, cases a with a, simp, cases a; simp, apply H end theorem lift_rel_o.swap (R : α → β → Prop) (C) : function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) := by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl } theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) : lift_rel (function.swap R) s2 s1 := begin refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩, rw [←lift_rel_o.swap, computation.lift_rel.swap], apply lift_rel_destruct h end theorem lift_rel.swap (R : α → β → Prop) : function.swap (lift_rel R) = lift_rel (function.swap R) := funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 (h : function.swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show function.swap R = R, from funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s t u h1 h2, begin refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩, rcases h with ⟨t, h1, h2⟩, have h1 := lift_rel_destruct h1, have h2 := lift_rel_destruct h2, refine computation.lift_rel_def.2 ⟨(computation.terminates_of_lift_rel h1).trans (computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩, rcases h1.left ha with ⟨b, hb, t1⟩, have t2 := computation.rel_of_lift_rel h2 hb hc, cases a with a; cases c with c, { trivial }, { cases b, {cases t2}, {cases t1} }, { cases a, cases b with b, {cases t1}, {cases b, cases t2} }, { cases a with a s, cases b with b, {cases t1}, cases b with b t, cases c with c u, cases t1 with ab st, cases t2 with bc tu, exact ⟨H ab bc, t, st, tu⟩ } end theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ @[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s := lift_rel.refl (=) eq.refl @[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s := lift_rel.symm (=) (@eq.symm _) @[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u := lift_rel.trans (=) (@eq.trans _) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ open computation local notation `return` := computation.return @[simp] theorem destruct_nil : destruct (nil : wseq α) = return none := computation.destruct_eq_ret rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) := computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap] @[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think := computation.destruct_eq_think $ by simp [destruct, think, computation.rmap] @[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none := seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) := seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) := seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl @[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl @[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s := begin refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl, intros s' s h, rw ←h, simp [flatten], cases seq.destruct s, { simp }, { cases val with o s', simp } end @[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) := seq.destruct_eq_cons $ by simp [flatten, think] @[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct := begin refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, (or.inr ⟨c, rfl, rfl⟩) := begin apply c.cases_on (λa, _) (λc', _); repeat {simp}, { cases (destruct a).destruct; simp }, { exact or.inr ⟨c', rfl, rfl⟩ } end end end theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : wseq α) n = nil := by induction n; simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop] @[simp] theorem dropn_think (s : wseq α) (n) : drop (think s) n = (drop s n).think := by induction n; simp [*, drop] theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n := congr_arg head (dropn_add _ _ _) theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil @[simp] theorem join_think (S : wseq (wseq α)) : join (think S) = think (join S) := by { simp [think, join], unfold functor.map, simp [join, seq1.ret] } @[simp] theorem join_cons (s : wseq α) (S) : join (cons s S) = think (append s (join S)) := by { simp [think, join], unfold functor.map, simp [join, cons, append] } @[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _ @[simp] theorem think_append (s t : wseq α) : append (think s) t = think (append s t) := seq.cons_append _ _ _ @[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _ @[simp] theorem append_assoc (s t u : wseq α) : append (append s t) u = append s (append t u) := seq.append_assoc _ _ _ @[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α)) | none := return none | (some (a, s)) := destruct s theorem destruct_tail (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux := begin dsimp [tail], simp, rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc], apply congr_arg, funext o, rcases o with _|⟨a, s⟩; apply (@pure_bind computation _ _ _ _ _ _).trans _; simp end @[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α)) | 0 := return | (n+1) := λ a, tail.aux a >>= drop.aux n theorem drop.aux_none : ∀ n, @drop.aux α n none = return none | 0 := rfl | (n+1) := show computation.bind (return none) (drop.aux n) = return none, by rw [ret_bind, drop.aux_none] theorem destruct_dropn : ∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n | s 0 := (bind_ret' _).symm | s (n+1) := by rw [← dropn_tail, destruct_dropn _ n, destruct_tail, is_lawful_monad.bind_assoc]; refl theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] : terminates (head s) := (head_terminates_iff _).2 $ begin cases (head_terminates_iff _).1 T with a h, simp [tail] at h, rcases exists_of_mem_bind h with ⟨s', h1, h2⟩, unfold functor.map at h1, exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3 end theorem destruct_some_of_destruct_tail_some {s : wseq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := begin unfold tail functor.map at h, simp at h, rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h, rcases exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm, cases t' with t'; rw ←ht2 at td; simp at td, { have := mem_unique td (ret_mem _), contradiction }, { exact ⟨_, ht'⟩ } end theorem head_some_of_head_tail_some {s : wseq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := begin unfold head at h, rcases exists_of_mem_map h with ⟨o, md, e⟩, clear h, cases o with o; injection e with h', clear e h', cases destruct_some_of_destruct_tail_some md with a am, exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩ end theorem head_some_of_nth_some {s : wseq α} {a n} (h : some a ∈ nth s n) : ∃ a', some a' ∈ head s := begin revert a, induction n with n IH; intros, exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h'] end instance productive_tail (s : wseq α) [productive s] : productive (tail s) := λ n, by rw [nth_tail]; apply_instance instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) := λ m, by rw [←nth_add]; apply_instance /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def to_seq (s : wseq α) [productive s] : seq α := ⟨λ n, (nth s n).get, λn h, begin cases e : computation.get (nth s (n + 1)), {assumption}, have := mem_of_get_eq _ e, simp [nth] at this h, cases head_some_of_head_tail_some this with a' h', have := mem_unique h' (@mem_of_get_eq _ _ _ _ h), contradiction end⟩ theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) := by induction h with m' h IH; [exact id, exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) := nth_terminates_le (nat.zero_le n) theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) := (head_terminates_iff _).1 $ head_terminates_of_nth_terminates T theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := begin apply seq.mem_rec_on M, intros o s' h, cases o with b, { apply h2, cases h, {contradiction}, {assumption} }, { apply h1, apply or.imp_left _ h, intro h, injection h } end @[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s := begin cases s with f al, change some (some a) ∈ some none :: f ↔ some (some a) ∈ f, constructor; intro h, { apply (stream.eq_or_mem_of_mem_cons h).resolve_left, intro, injections }, { apply stream.mem_cons_of_mem _ h } end theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := begin generalize e : destruct s = c, intro h, revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s; apply s.cases_on _ (λ x s, _) (λ s, _); intros m; have := congr_arg computation.destruct m; simp at this; cases this with i1 i2, { rw [i1, i2], cases s' with f al, unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp, have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp}, rw [h_a_eq_a'], refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩, { cases o with e m, { rw e, apply stream.mem_cons }, { exact stream.mem_cons_of_mem _ m } } }, { simp, exact IH this } end @[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem $ by simp [ret_mem] theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (or.inr h) theorem mem_cons (s : wseq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (or.inl rfl) theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s := begin intro h, have := h, cases h with n e, revert s, simp [stream.nth], induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _); repeat{simp}; intros m e; injections, { exact or.inr m }, { exact or.inr m }, { apply IH m, rw e, cases tail s, refl } end theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0 h := h | (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h) theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s := begin revert s, induction n with n IH; intros s h, { rcases exists_of_mem_map h with ⟨o, h1, h2⟩, cases o with o; injection h2 with h', cases o with a' s', exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) }, { have := @IH (tail s), rw nth_tail at this, exact mem_of_mem_tail (this h) } end theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n := begin apply mem_rec_on h, { intros a' s' h, cases h with h h, { existsi 0, simp [nth], rw h, apply ret_mem }, { cases h with n h, existsi n+1, simp [nth], exact h } }, { intros s' h, cases h with n h, existsi n, simp [nth], apply think_mem h } end theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin cases (head_terminates_iff _).1 ⟨_, h⟩ with o om, have := mem_unique (mem_map _ om) h, cases o with o; injection this with i, cases o with a' s', dsimp at i, rw i at om, exact ⟨_, om⟩ end⟩ theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) : ∀ n, computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 := lift_rel_destruct H | (n+1) := begin simp [destruct_tail], apply lift_rel_bind, apply lift_rel_dropn_destruct n, exact λ a b o, match a, b, o with | none, none, _ := by simp | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2 end end theorem exists_of_lift_rel_left {R : α → β → Prop} {s t} (H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b := let ⟨n, h⟩ := exists_nth_of_mem h, ⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h, ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in ⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩ theorem exists_of_lift_rel_right {R : α → β → Prop} {s t} (H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b := by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) := let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩ theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := seq.of_mem_append theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := seq.mem_append_left theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ @[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) : lift_rel R (think s) t ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) : lift_rel R s (think t) ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t := by unfold equiv; simp; exact h theorem think_equiv (s : wseq α) : think s ~ s := by unfold equiv; simp; apply equiv.refl theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t := by unfold equiv; simp; exact h theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t := suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from λ s t h o, ⟨this h, this h.symm⟩, begin intros s t h o ho, rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩, rw ←dse, cases destruct_congr h with l r, rcases l dsm with ⟨dt, dtm, dst⟩, cases ds with a; cases dt with b, { apply mem_map _ dtm }, { cases b, cases dst }, { cases a, cases dst }, { cases a with a s', cases b with b t', rw dst.left, exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst) _ (destruct t) dtm } end theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s := begin apply computation.mem_rec_on h, { simp }, { intro s', apply equiv.trans, simp [think_equiv] } end theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)} (h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) := let S := λ s t, ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in ⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h, match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin simp, apply lift_rel_bind _ _ h, intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab), intros a b, apply lift_rel_o.imp_right, intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h] end end⟩ theorem flatten_congr {c1 c2 : computation (wseq α)} : computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t := begin apply flatten_congr, unfold functor.map, rw [←bind_ret, ←bind_ret], apply lift_rel_bind _ _ (destruct_congr h), intros a b h, simp, cases a with a; cases b with b, { trivial }, { cases h }, { cases a, cases h }, { cases a with a s', cases b with b t', exact h.right } end theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n := by induction n; simp [*, tail_congr] theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n := head_congr (dropn_congr h _) theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩, λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in nth_mem ((nth_congr h _ _).1 hn) theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t := forall_congr $ λn, terminates_congr $ nth_congr h _ theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t := ⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin refine lift_rel_def.2 ⟨_, _⟩, { rw [←head_terminates_iff, ←head_terminates_iff], exact terminates_congr (h 0) }, { intros a b ma mb, cases a with a; cases b with b, { trivial }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { cases a with a s', cases b with b t', injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab, refine ⟨ab, λ n, _⟩, refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans ((_ : nth (tail s) n ~ nth (tail t) n).trans (nth_congr (flatten_equiv (mem_map _ mb)) n)), rw [nth_tail, nth_tail], apply h } } end⟩ theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) := begin refine eq_of_bisim (λ c1 c2, ∃ (l : list α) (s : wseq α), c1 = corec length._match_2 (l.length, s) ∧ c2 = computation.map list.length (corec to_list._match_2 (l, s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l, s, _, _⟩; simp }, { refine ⟨l, s, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := show seq.map some (seq.of_list (a :: l)) = seq.cons (some a) (seq.map some (seq.of_list l)), by simp @[simp] theorem to_list'_nil (l : list α) : corec to_list._match_2 (l, nil) = return l.reverse := destruct_eq_ret rfl @[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) : corec to_list._match_2 (l, cons a s) = (corec to_list._match_2 (a::l, s)).think := destruct_eq_think $ by simp [to_list, cons] @[simp] theorem to_list'_think (l : list α) (s : wseq α) : corec to_list._match_2 (l, think s) = (corec to_list._match_2 (l, s)).think := destruct_eq_think $ by simp [to_list, think] theorem to_list'_map (l : list α) (s : wseq α) : corec to_list._match_2 (l, s) = ((++) l.reverse) <$> to_list s := begin refine eq_of_bisim (λ c1 c2, ∃ (l' : list α) (s : wseq α), c1 = corec to_list._match_2 (l' ++ l, s) ∧ c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l', s, _, _⟩; simp }, { refine ⟨l', s, _, _⟩; simp } end @[simp] theorem to_list_cons (a : α) (s) : to_list (cons a s) = (list.cons a <$> to_list s).think := destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl @[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] := destruct_eq_ret rfl theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) := by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH) @[simp] theorem destruct_of_seq (s : seq α) : destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) := destruct_eq_ret $ begin simp [of_seq, head, destruct, seq.destruct, seq.head], rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth], cases seq.nth s 0 with a, { refl }, unfold functor.map, simp [destruct] end @[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head := by simp [head]; cases seq.head s; refl @[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail := begin simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl}, rw [seq.head_cons, seq.tail_cons], refl end @[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n) | 0 := rfl | (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq] theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) := by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn] instance productive_of_seq (s : seq α) : productive (of_seq s) := λ n, by rw nth_of_seq; apply_instance theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s := begin apply subtype.eq, funext n, dsimp [to_seq], apply get_eq_of_mem, rw nth_of_seq, apply ret_mem end /-- The monadic `return a` is a singleton list containing `a`. -/ def ret (a : α) : wseq α := of_list [a] @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _ @[simp] theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) := seq.map_cons _ _ _ @[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := seq.map_append _ _ _ theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) : map (g ∘ f) s = map g (map f s) := begin dsimp [map], rw ←seq.map_comp, apply congr_fun, apply congr_arg, funext o, cases o; refl end theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s := seq.mem_map (option.map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h, (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _), begin intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try {cases this}; try {contradiction}, substs b' ss, simp at m ⊢, cases o with e IH, { simp [e] }, cases m with e m, { simp [e] }, exact or.imp_left or.inr (IH _ _ rfl m) }, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try { try {have := this.1}, contradiction }; subst ss, { apply or.inr, simp at m ⊢, cases IH s S rfl m with as ex, { exact ⟨s, or.inl rfl, as⟩ }, { rcases ex with ⟨s', sS, as⟩, exact ⟨s', or.inr sS, as⟩ } }, { apply or.inr, simp at m, rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩, exact ⟨s, by simp [sS], as⟩ }, { simp at m IH ⊢, apply IH _ _ rfl m } } end theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h, ⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩ theorem destruct_map (f : α → β) (s : wseq α) : destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) := begin apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧ c2 = computation.map (option.map (prod.map f (map f))) (destruct s)), { intros c1 c2 h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp, exact ⟨s, rfl, rfl⟩ }, { exact ⟨s, rfl, rfl⟩ } end theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := ⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t, ⟨s1, s2, rfl, rfl, h1⟩, λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b; simp, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, exact ⟨h2 r, s, rfl, t, rfl, h⟩ } end end⟩ theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t := lift_rel_map _ _ h (λ _ _, congr_arg _) @[simp] def destruct_append.aux (t : wseq α) : option (α × wseq α) → computation (option (α × wseq α)) | none := destruct t | (some (a, s)) := return (some (a, append s t)) theorem destruct_append (s t : wseq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := begin apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩, intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp, { apply t.cases_on _ (λ b t, _) (λ t, _); simp; simp, { refine ⟨nil, t, _, _⟩; simp } }, { exact ⟨s, t, rfl, rfl⟩ } end @[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α)) | none := return none | (some (s, S)) := (destruct (append s (join S))).think theorem destruct_join (S : wseq (wseq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := begin apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, or.inr ⟨S, rfl, rfl⟩ := begin apply S.cases_on _ (λ s S, _) (λ S, _); simp; simp, { refine or.inr ⟨S, rfl, rfl⟩ } end end end theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) : lift_rel R (append s1 s2) (append t1 t2) := ⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1, or.inr ⟨s1, t1, rfl, rfl, h1⟩, λ s t h, match s, t, h with | s, t, or.inl h := begin apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end | ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin simp [destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b, { simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl }, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ } end end⟩ theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b := begin cases exists_results_of_mem ma with n h, clear ma, revert a S T, apply nat.strong_induction_on n _, intros n IH a S T ST ra, simp [destruct_join] at ra, exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra, ⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in by exact match o, p, rop, rs1, rs2, mT with | none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact ⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT := by simp [destruct_append] at rs2; exact let ⟨k1, rs3, ek⟩ := of_results_think rs2, ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3, ⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in by exact match o', p', rop', rs4, rs5, mt with | none, none, _, rs4, rs5', mt := have n1 < n, begin rw [en, ek, ek1], apply lt_of_lt_of_le _ (nat.le_add_right _ _), apply nat.lt_succ_of_le (nat.le_add_right _ _) end, let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩; { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, exact mb } | some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin simp at rs5, refine ⟨some (b, append t' (join T')), _, _⟩, { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, apply ret_mem }, rw eq_of_ret_mem rs5.mem, exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ end end end end theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) := ⟨λ s1 s2, ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin clear _fun_match _x, rw [h1, h2], rw [destruct_append, destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct st), exact λ o p h, match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩ | none, none, _ := begin dsimp [destruct_append.aux, computation.lift_rel], constructor, { intro, apply lift_rel_join.lem _ ST (λ _ _, id) }, { intros b mb, rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R), { rw [←lift_rel.swap R, ←lift_rel.swap], apply ST }, { rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)], exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, ⟨t, s, T, S, h2, h1, st, ST⟩ }, { exact mb } } end end end⟩ theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T := lift_rel_join _ h theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := lift_rel_join _ (lift_rel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2) @[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s := by simp [ret]; apply think_equiv @[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s := begin refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩, intros s' s h, rw ←h, apply lift_rel_rec (λ c1 c2, ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s), { exact λ c1 c2 h, match c1, c2, h with | ._, ._, ⟨s, rfl, rfl⟩ := begin clear h _match, apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret]; simp [ret], { refine ⟨_, ret_mem _, _⟩, simp }, { exact ⟨s, rfl, rfl⟩ } end end }, { exact ⟨s, rfl, rfl⟩ } end @[simp] theorem join_append (S T : wseq (wseq α)) : join (append S T) ~ append (join S) (join T) := begin refine ⟨λ s1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T, c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h in ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp, { apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp; simp, { refine ⟨s, nil, T, _, _⟩; simp }, { refine ⟨nil, nil, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { refine ⟨nil, S, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { exact ⟨s, S, T, rfl, rfl⟩ } end end end @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s := begin dsimp [bind], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], apply join_map_ret end @[simp] theorem ret_bind (a : α) (f : α → wseq β) : bind (ret a) f ~ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := begin apply seq.eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp, { exact ⟨map f s, S, rfl, rfl⟩ }, { refine ⟨nil, S, _, _⟩; simp } }, { exact ⟨_, _, rfl, rfl⟩ }, { exact ⟨_, _, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem join_join (SS : wseq (wseq (wseq α))) : join (join SS) ~ join (map join SS) := begin refine ⟨λ s1 s2, ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp, { apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp; simp, { refine ⟨nil, S, SS, _, _⟩; simp }, { refine ⟨nil, nil, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { refine ⟨nil, S, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { exact ⟨s, S, SS, rfl, rfl⟩ } end end end @[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) : bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) := begin simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join], apply join_join end instance : monad wseq := { map := @map, pure := @ret, bind := @bind } /- Unfortunately, wseq is not a lawful monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance : is_lawful_monad wseq := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq
e2a005b4f1f3a387c25c6583d6dbc7e3b139e19b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/unit_trinomial.lean
0a3957e21121ef58a87a40e043ada1eeebd78a8c
[ "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
16,302
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import analysis.complex.polynomial import data.polynomial.mirror /-! # Unit Trinomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines irreducible trinomials and proves an irreducibility criterion. ## Main definitions - `polynomial.is_unit_trinomial` ## Main results - `polynomial.irreducible_of_coprime`: An irreducibility criterion for unit trinomials. -/ namespace polynomial open_locale polynomial open finset section semiring variables {R : Type*} [semiring R] (k m n : ℕ) (u v w : R) /-- Shorthand for a trinomial -/ noncomputable def trinomial := C u * X ^ k + C v * X ^ m + C w * X ^ n lemma trinomial_def : trinomial k m n u v w = C u * X ^ k + C v * X ^ m + C w * X ^ n := rfl variables {k m n u v w} lemma trinomial_leading_coeff' (hkm : k < m) (hmn : m < n) : (trinomial k m n u v w).coeff n = w := by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow, coeff_C_mul_X_pow, if_neg (hkm.trans hmn).ne', if_neg hmn.ne', if_pos rfl, zero_add, zero_add] lemma trinomial_middle_coeff (hkm : k < m) (hmn : m < n) : (trinomial k m n u v w).coeff m = v := by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow, coeff_C_mul_X_pow, if_neg hkm.ne', if_pos rfl, if_neg hmn.ne, zero_add, add_zero] lemma trinomial_trailing_coeff' (hkm : k < m) (hmn : m < n) : (trinomial k m n u v w).coeff k = u := by rw [trinomial_def, coeff_add, coeff_add, coeff_C_mul_X_pow, coeff_C_mul_X_pow, coeff_C_mul_X_pow, if_pos rfl, if_neg hkm.ne, if_neg (hkm.trans hmn).ne, add_zero, add_zero] lemma trinomial_nat_degree (hkm : k < m) (hmn : m < n) (hw : w ≠ 0) : (trinomial k m n u v w).nat_degree = n := begin refine nat_degree_eq_of_degree_eq_some ((finset.sup_le $ λ i h, _).antisymm $ le_degree_of_ne_zero $ by rwa trinomial_leading_coeff' hkm hmn), replace h := support_trinomial' k m n u v w h, rw [mem_insert, mem_insert, mem_singleton] at h, rcases h with rfl | rfl | rfl, { exact with_bot.coe_le_coe.mpr (hkm.trans hmn).le }, { exact with_bot.coe_le_coe.mpr hmn.le }, { exact le_rfl }, end lemma trinomial_nat_trailing_degree (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) : (trinomial k m n u v w).nat_trailing_degree = k := begin refine nat_trailing_degree_eq_of_trailing_degree_eq_some ((finset.le_inf $ λ i h, _).antisymm $ le_trailing_degree_of_ne_zero $ by rwa trinomial_trailing_coeff' hkm hmn).symm, replace h := support_trinomial' k m n u v w h, rw [mem_insert, mem_insert, mem_singleton] at h, rcases h with rfl | rfl | rfl, { exact le_rfl }, { exact with_top.coe_le_coe.mpr hkm.le }, { exact with_top.coe_le_coe.mpr (hkm.trans hmn).le }, end lemma trinomial_leading_coeff (hkm : k < m) (hmn : m < n) (hw : w ≠ 0) : (trinomial k m n u v w).leading_coeff = w := by rw [leading_coeff, trinomial_nat_degree hkm hmn hw, trinomial_leading_coeff' hkm hmn] lemma trinomial_trailing_coeff (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) : (trinomial k m n u v w).trailing_coeff = u := by rw [trailing_coeff, trinomial_nat_trailing_degree hkm hmn hu, trinomial_trailing_coeff' hkm hmn] lemma trinomial_monic (hkm : k < m) (hmn : m < n) : (trinomial k m n u v 1).monic := begin casesI subsingleton_or_nontrivial R with h h, { apply subsingleton.elim }, { exact trinomial_leading_coeff hkm hmn one_ne_zero }, end lemma trinomial_mirror (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) (hw : w ≠ 0) : (trinomial k m n u v w).mirror = trinomial k (n - m + k) n w v u := by rw [mirror, trinomial_nat_trailing_degree hkm hmn hu, reverse, trinomial_nat_degree hkm hmn hw, trinomial_def, reflect_add, reflect_add, reflect_C_mul_X_pow, reflect_C_mul_X_pow, reflect_C_mul_X_pow, rev_at_le (hkm.trans hmn).le, rev_at_le hmn.le, rev_at_le le_rfl, add_mul, add_mul, mul_assoc, mul_assoc, mul_assoc, ←pow_add, ←pow_add, ←pow_add, nat.sub_add_cancel (hkm.trans hmn).le, nat.sub_self, zero_add, add_comm, add_comm (C u * X ^ n), ←add_assoc, ←trinomial_def] lemma trinomial_support (hkm : k < m) (hmn : m < n) (hu : u ≠ 0) (hv : v ≠ 0) (hw : w ≠ 0) : (trinomial k m n u v w).support = {k, m, n} := support_trinomial hkm hmn hu hv hw end semiring variables (p q : ℤ[X]) /-- A unit trinomial is a trinomial with unit coefficients. -/ def is_unit_trinomial := ∃ {k m n : ℕ} (hkm : k < m) (hmn : m < n) {u v w : units ℤ}, p = trinomial k m n u v w variables {p q} namespace is_unit_trinomial lemma not_is_unit (hp : p.is_unit_trinomial) : ¬ is_unit p := begin obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp, exact λ h, ne_zero_of_lt hmn ((trinomial_nat_degree hkm hmn w.ne_zero).symm.trans (nat_degree_eq_of_degree_eq_some (degree_eq_zero_of_is_unit h))), end lemma card_support_eq_three (hp : p.is_unit_trinomial) : p.support.card = 3 := begin obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp, exact card_support_trinomial hkm hmn u.ne_zero v.ne_zero w.ne_zero, end lemma ne_zero (hp : p.is_unit_trinomial) : p ≠ 0 := begin rintro rfl, exact nat.zero_ne_bit1 1 hp.card_support_eq_three, end lemma coeff_is_unit (hp : p.is_unit_trinomial) {k : ℕ} (hk : k ∈ p.support) : is_unit (p.coeff k) := begin obtain ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩ := hp, have := support_trinomial' k m n ↑u ↑v ↑w hk, rw [mem_insert, mem_insert, mem_singleton] at this, rcases this with rfl | rfl | rfl, { refine ⟨u, by rw trinomial_trailing_coeff' hkm hmn⟩ }, { refine ⟨v, by rw trinomial_middle_coeff hkm hmn⟩ }, { refine ⟨w, by rw trinomial_leading_coeff' hkm hmn⟩ }, end lemma leading_coeff_is_unit (hp : p.is_unit_trinomial) : is_unit p.leading_coeff := hp.coeff_is_unit (nat_degree_mem_support_of_nonzero hp.ne_zero) lemma trailing_coeff_is_unit (hp : p.is_unit_trinomial) : is_unit p.trailing_coeff := hp.coeff_is_unit (nat_trailing_degree_mem_support_of_nonzero hp.ne_zero) end is_unit_trinomial lemma is_unit_trinomial_iff : p.is_unit_trinomial ↔ p.support.card = 3 ∧ ∀ k ∈ p.support, is_unit (p.coeff k) := begin refine ⟨λ hp, ⟨hp.card_support_eq_three, λ k, hp.coeff_is_unit⟩, λ hp, _⟩, obtain ⟨k, m, n, hkm, hmn, x, y, z, hx, hy, hz, rfl⟩ := card_support_eq_three.mp hp.1, rw [support_trinomial hkm hmn hx hy hz] at hp, replace hx := hp.2 k (mem_insert_self k {m, n}), replace hy := hp.2 m (mem_insert_of_mem (mem_insert_self m {n})), replace hz := hp.2 n (mem_insert_of_mem (mem_insert_of_mem (mem_singleton_self n))), simp_rw [coeff_add, coeff_C_mul, coeff_X_pow_self, mul_one, coeff_X_pow] at hx hy hz, rw [if_neg hkm.ne, if_neg (hkm.trans hmn).ne] at hx, rw [if_neg hkm.ne', if_neg hmn.ne] at hy, rw [if_neg (hkm.trans hmn).ne', if_neg hmn.ne'] at hz, simp_rw [mul_zero, zero_add, add_zero] at hx hy hz, exact ⟨k, m, n, hkm, hmn, hx.unit, hy.unit, hz.unit, rfl⟩, end lemma is_unit_trinomial_iff' : p.is_unit_trinomial ↔ (p * p.mirror).coeff (((p * p.mirror).nat_degree + (p * p.mirror).nat_trailing_degree) / 2) = 3 := begin rw [nat_degree_mul_mirror, nat_trailing_degree_mul_mirror, ←mul_add, nat.mul_div_right _ zero_lt_two, coeff_mul_mirror], refine ⟨_, λ hp, _⟩, { rintros ⟨k, m, n, hkm, hmn, u, v, w, rfl⟩, rw [sum_def, trinomial_support hkm hmn u.ne_zero v.ne_zero w.ne_zero, sum_insert (mt mem_insert.mp (not_or hkm.ne (mt mem_singleton.mp (hkm.trans hmn).ne))), sum_insert (mt mem_singleton.mp hmn.ne), sum_singleton, trinomial_leading_coeff' hkm hmn, trinomial_middle_coeff hkm hmn, trinomial_trailing_coeff' hkm hmn], simp_rw [←units.coe_pow, int.units_sq, units.coe_one, ←add_assoc, bit1, bit0] }, { have key : ∀ k ∈ p.support, (p.coeff k) ^ 2 = 1 := λ k hk, int.sq_eq_one_of_sq_le_three ((single_le_sum (λ k hk, sq_nonneg (p.coeff k)) hk).trans hp.le) (mem_support_iff.mp hk), refine is_unit_trinomial_iff.mpr ⟨_, λ k hk, is_unit_of_pow_eq_one (key k hk) two_ne_zero⟩, rw [sum_def, sum_congr rfl key, sum_const, nat.smul_one_eq_coe] at hp, exact nat.cast_injective hp }, end lemma is_unit_trinomial_iff'' (h : p * p.mirror = q * q.mirror) : p.is_unit_trinomial ↔ q.is_unit_trinomial := by rw [is_unit_trinomial_iff', is_unit_trinomial_iff', h] namespace is_unit_trinomial lemma irreducible_aux1 {k m n : ℕ} (hkm : k < m) (hmn : m < n) (u v w : units ℤ) (hp : p = trinomial k m n u v w) : C ↑v * (C ↑u * X ^ (m + n) + C ↑w * X ^ (n - m + k + n)) = ⟨finsupp.filter (set.Ioo (k + n) (n + n)) (p * p.mirror).to_finsupp⟩ := begin have key : n - m + k < n := by rwa [←lt_tsub_iff_right, tsub_lt_tsub_iff_left_of_le hmn.le], rw [hp, trinomial_mirror hkm hmn u.ne_zero w.ne_zero], simp_rw [trinomial_def, C_mul_X_pow_eq_monomial, add_mul, mul_add, monomial_mul_monomial, to_finsupp_add, to_finsupp_monomial, finsupp.filter_add], rw [finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_neg, finsupp.filter_single_of_pos, finsupp.filter_single_of_neg, finsupp.filter_single_of_pos, finsupp.filter_single_of_neg], { simp only [add_zero, zero_add, of_finsupp_add, of_finsupp_single], rw [C_mul_monomial, C_mul_monomial, mul_comm ↑v ↑w, add_comm (n - m + k) n] }, { exact λ h, h.2.ne rfl }, { refine ⟨_, add_lt_add_left key n⟩, rwa [add_comm, add_lt_add_iff_left, lt_add_iff_pos_left, tsub_pos_iff_lt] }, { exact λ h, h.1.ne (add_comm k n) }, { exact ⟨add_lt_add_right hkm n, add_lt_add_right hmn n⟩ }, { rw [←add_assoc, add_tsub_cancel_of_le hmn.le, add_comm], exact λ h, h.1.ne rfl }, { intro h, have := h.1, rw [add_comm, add_lt_add_iff_right] at this, exact asymm this hmn }, { exact λ h, h.1.ne rfl }, { exact λ h, asymm ((add_lt_add_iff_left k).mp h.1) key }, { exact λ h, asymm ((add_lt_add_iff_left k).mp h.1) (hkm.trans hmn) }, end lemma irreducible_aux2 {k m m' n : ℕ} (hkm : k < m) (hmn : m < n) (hkm' : k < m') (hmn' : m' < n) (u v w : units ℤ) (hp : p = trinomial k m n u v w) (hq : q = trinomial k m' n u v w) (h : p * p.mirror = q * q.mirror) : q = p ∨ q = p.mirror := begin let f : ℤ[X] → ℤ[X] := λ p, ⟨finsupp.filter (set.Ioo (k + n) (n + n)) p.to_finsupp⟩, replace h := congr_arg f h, replace h := (irreducible_aux1 hkm hmn u v w hp).trans h, replace h := h.trans (irreducible_aux1 hkm' hmn' u v w hq).symm, rw (is_unit_C.mpr v.is_unit).mul_right_inj at h, rw binomial_eq_binomial u.ne_zero w.ne_zero at h, simp only [add_left_inj, units.eq_iff] at h, rcases h with ⟨rfl, -⟩ | ⟨rfl, rfl, h⟩ | ⟨-, hm, hm'⟩, { exact or.inl (hq.trans hp.symm) }, { refine or.inr _, rw [←trinomial_mirror hkm' hmn' u.ne_zero u.ne_zero, eq_comm, mirror_eq_iff] at hp, exact hq.trans hp }, { suffices : m = m', { rw this at hp, exact or.inl (hq.trans hp.symm) }, rw [tsub_add_eq_add_tsub hmn.le, eq_tsub_iff_add_eq_of_le, ←two_mul] at hm, rw [tsub_add_eq_add_tsub hmn'.le, eq_tsub_iff_add_eq_of_le, ←two_mul] at hm', exact mul_left_cancel₀ two_ne_zero (hm.trans hm'.symm), exact hmn'.le.trans (nat.le_add_right n k), exact hmn.le.trans (nat.le_add_right n k) }, end lemma irreducible_aux3 {k m m' n : ℕ} (hkm : k < m) (hmn : m < n) (hkm' : k < m') (hmn' : m' < n) (u v w x z : units ℤ) (hp : p = trinomial k m n u v w) (hq : q = trinomial k m' n x v z) (h : p * p.mirror = q * q.mirror) : q = p ∨ q = p.mirror := begin have hmul := congr_arg leading_coeff h, rw [leading_coeff_mul, leading_coeff_mul, mirror_leading_coeff, mirror_leading_coeff, hp, hq, trinomial_leading_coeff hkm hmn w.ne_zero, trinomial_leading_coeff hkm' hmn' z.ne_zero, trinomial_trailing_coeff hkm hmn u.ne_zero, trinomial_trailing_coeff hkm' hmn' x.ne_zero] at hmul, have hadd := congr_arg (eval 1) h, rw [eval_mul, eval_mul, mirror_eval_one, mirror_eval_one, ←sq, ←sq, hp, hq] at hadd, simp only [eval_add, eval_C_mul, eval_pow, eval_X, one_pow, mul_one, trinomial_def] at hadd, rw [add_assoc, add_assoc, add_comm ↑u, add_comm ↑x, add_assoc, add_assoc] at hadd, simp only [add_sq', add_assoc, add_right_inj, ←units.coe_pow, int.units_sq] at hadd, rw [mul_assoc, hmul, ←mul_assoc, add_right_inj, mul_right_inj' (show 2 * (v : ℤ) ≠ 0, from mul_ne_zero two_ne_zero v.ne_zero)] at hadd, replace hadd := (int.is_unit_add_is_unit_eq_is_unit_add_is_unit w.is_unit u.is_unit z.is_unit x.is_unit).mp hadd, simp only [units.eq_iff] at hadd, rcases hadd with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { exact irreducible_aux2 hkm hmn hkm' hmn' u v w hp hq h }, { rw [←mirror_inj, trinomial_mirror hkm' hmn' w.ne_zero u.ne_zero] at hq, rw [mul_comm q, ←q.mirror_mirror, q.mirror.mirror_mirror] at h, rw [←mirror_inj, or_comm, ←mirror_eq_iff], exact irreducible_aux2 hkm hmn (lt_add_of_pos_left k (tsub_pos_of_lt hmn')) ((lt_tsub_iff_right).mp ((tsub_lt_tsub_iff_left_of_le hmn'.le).mpr hkm')) u v w hp hq h }, end lemma irreducible_of_coprime (hp : p.is_unit_trinomial) (h : ∀ q : ℤ[X], q ∣ p → q ∣ p.mirror → is_unit q) : irreducible p := begin refine irreducible_of_mirror hp.not_is_unit (λ q hpq, _) h, have hq : is_unit_trinomial q := (is_unit_trinomial_iff'' hpq).mp hp, obtain ⟨k, m, n, hkm, hmn, u, v, w, hp⟩ := hp, obtain ⟨k', m', n', hkm', hmn', x, y, z, hq⟩ := hq, have hk : k = k', { rw [←mul_right_inj' (show 2 ≠ 0, from two_ne_zero), ←trinomial_nat_trailing_degree hkm hmn u.ne_zero, ←hp, ←nat_trailing_degree_mul_mirror, hpq, nat_trailing_degree_mul_mirror, hq, trinomial_nat_trailing_degree hkm' hmn' x.ne_zero] }, have hn : n = n', { rw [←mul_right_inj' (show 2 ≠ 0, from two_ne_zero), ←trinomial_nat_degree hkm hmn w.ne_zero, ←hp, ←nat_degree_mul_mirror, hpq, nat_degree_mul_mirror, hq, trinomial_nat_degree hkm' hmn' z.ne_zero] }, subst hk, subst hn, rcases eq_or_eq_neg_of_sq_eq_sq ↑y ↑v ((int.is_unit_sq y.is_unit).trans (int.is_unit_sq v.is_unit).symm) with h1 | h1, { rw h1 at *, rcases irreducible_aux3 hkm hmn hkm' hmn' u v w x z hp hq hpq with h2 | h2, { exact or.inl h2 }, { exact or.inr (or.inr (or.inl h2)) } }, { rw h1 at *, rw trinomial_def at hp, rw [←neg_inj, neg_add, neg_add, ←neg_mul, ←neg_mul, ←neg_mul, ←C_neg, ←C_neg, ←C_neg] at hp, rw [←neg_mul_neg, ←mirror_neg] at hpq, rcases irreducible_aux3 hkm hmn hkm' hmn' (-u) (-v) (-w) x z hp hq hpq with rfl | rfl, { exact or.inr (or.inl rfl) }, { exact or.inr (or.inr (or.inr p.mirror_neg)) } }, end /-- A unit trinomial is irreducible if it is coprime with its mirror -/ lemma irreducible_of_is_coprime (hp : p.is_unit_trinomial) (h : is_coprime p p.mirror) : irreducible p := irreducible_of_coprime hp (λ q, h.is_unit_of_dvd') /-- A unit trinomial is irreducible if it has no complex roots in common with its mirror -/ lemma irreducible_of_coprime' (hp : is_unit_trinomial p) (h : ∀ z : ℂ, ¬ (aeval z p = 0 ∧ aeval z (mirror p) = 0)) : irreducible p := begin refine hp.irreducible_of_coprime (λ q hq hq', _), suffices : ¬ (0 < q.nat_degree), { rcases hq with ⟨p, rfl⟩, replace hp := hp.leading_coeff_is_unit, rw leading_coeff_mul at hp, replace hp := is_unit_of_mul_is_unit_left hp, rw [not_lt, le_zero_iff] at this, rwa [eq_C_of_nat_degree_eq_zero this, is_unit_C, ←this] }, intro hq'', rw nat_degree_pos_iff_degree_pos at hq'', rw ← degree_map_eq_of_injective (algebra_map ℤ ℂ).injective_int at hq'', cases complex.exists_root hq'' with z hz, rw [is_root, eval_map, ←aeval_def] at hz, refine h z ⟨_, _⟩, { cases hq with g' hg', rw [hg', aeval_mul, hz, zero_mul] }, { cases hq' with g' hg', rw [hg', aeval_mul, hz, zero_mul] }, end -- TODO: Develop more theory (e.g., it suffices to check that `aeval z p ≠ 0` for `z = 0` -- and `z` a root of unity) end is_unit_trinomial end polynomial
d06aeee6652f35abc668dc624a4042d0d8d97263
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/concrete_category/elementwise.lean
e3a3674edf6024a719fafa4934d721ef2f9ccb10
[ "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
786
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import tactic.elementwise import category_theory.limits.has_limits import category_theory.limits.shapes.kernels /-! In this file we provide various simp lemmas in its elementwise form via `tactic.elementwise`. -/ open category_theory category_theory.limits attribute [elementwise] cone.w limit.lift_π limit.w cocone.w colimit.ι_desc colimit.w kernel.lift_ι cokernel.π_desc kernel.condition cokernel.condition -- Note that the elementwise forms of `iso.hom_inv_id` and `iso.inv_hom_id` are already -- provided as `category_theory.coe_hom_inv_id` and `category_theory.coe_inv_hom_id`. is_iso.hom_inv_id is_iso.inv_hom_id
7818696be624d62333c5501c3c2961fb399c27a0
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/div_wf.lean
9ae7f6bfc1de8625c00445c6e07a84d5c20e1e0b
[ "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
1,641
lean
import data.nat data.prod open nat well_founded decidable prod eq.ops -- Auxiliary lemma used to justify recursive call private definition lt_aux {x y : nat} (H : 0 < y ∧ y ≤ x) : x - y < x := and.rec_on H (λ ypos ylex, sub_lt (lt_of_lt_of_le ypos ylex) ypos) definition wdiv.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if H : 0 < y ∧ y ≤ x then f (x - y) (lt_aux H) y + 1 else zero definition wdiv (x y : nat) := fix wdiv.F x y theorem wdiv_def (x y : nat) : wdiv x y = if 0 < y ∧ y ≤ x then wdiv (x - y) y + 1 else 0 := congr_fun (well_founded.fix_eq wdiv.F x) y example : wdiv 5 2 = 2 := rfl example : wdiv 9 3 = 3 := rfl -- There is a little bit of cheating in the definition above. -- I avoid the packing/unpacking into tuples. -- The actual definitional package would not do that. -- It will always pack things. definition pair_nat.lt := lex lt lt -- Could also be (lex lt empty_rel) definition pair_nat.lt.wf [instance] : well_founded pair_nat.lt := prod.lex.wf lt.wf lt.wf infixl `≺`:50 := pair_nat.lt -- Recursive lemma used to justify recursive call definition plt_aux (x y : nat) (H : 0 < y ∧ y ≤ x) : (x - y, y) ≺ (x, y) := !lex.left (lt_aux H) definition pdiv.F (p₁ : nat × nat) : (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat := prod.cases_on p₁ (λ x y f, if H : 0 < y ∧ y ≤ x then f (x - y, y) (plt_aux x y H) + 1 else zero) definition pdiv (x y : nat) := fix pdiv.F (x, y) theorem pdiv_def (x y : nat) : pdiv x y = if 0 < y ∧ y ≤ x then pdiv (x - y) y + 1 else zero := well_founded.fix_eq pdiv.F (x, y) example : pdiv 17 2 = 8 := rfl
85e667d434127a14d6f85e197b3a7c7765400798
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/tests/lean/PPRoundtrip.lean
8482906bfd73704ad396ea833775e0565a8a05ce
[ "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
3,290
lean
import Lean open Lean open Lean.Elab open Lean.Elab.Term open Lean.Elab.Command open Std.Format open Std open Lean.PrettyPrinter open Lean.PrettyPrinter.Delaborator open Lean.Meta def checkM (stx : TermElabM Syntax) (optionsPerPos : OptionsPerPos := {}) : TermElabM Unit := do let opts ← getOptions let stx ← stx let e ← elabTermAndSynthesize stx none <* throwErrorIfErrors let stx' ← delab Name.anonymous [] e optionsPerPos let f' ← PrettyPrinter.ppTerm stx' let s := f'.pretty' opts IO.println s let env ← getEnv match Parser.runParserCategory env `term s "<input>" with | Except.error e => throwErrorAt stx e | Except.ok stx'' => do let e' ← elabTermAndSynthesize stx'' none <* throwErrorIfErrors unless (← isDefEq e e') do throwErrorAt stx (m!"failed to round-trip" ++ line ++ format e ++ line ++ format e') -- set_option trace.PrettyPrinter.parenthesize true set_option format.width 20 -- #eval checkM `(?m) -- fails round-trip #eval checkM `(Sort) #eval checkM `(Type) #eval checkM `(Type 0) #eval checkM `(Type 1) -- TODO: we need support for parsing `?u` to roundtrip the terms containing universe metavariables. Just pretty printing them as `_` is bad for error and trace messages -- #eval checkM `(Type _) -- #eval checkM `(Type (_ + 2)) #eval checkM `(Nat) #eval checkM `(List Nat) #eval checkM `(id Nat) #eval checkM `(id (id (id Nat))) section set_option pp.explicit true #eval checkM `(List Nat) #eval checkM `(id Nat) end section set_option pp.universes true #eval checkM `(List Nat) #eval checkM `(id Nat) #eval checkM `(Sum Nat Nat) end #eval checkM `(id (id Nat)) (Std.RBMap.empty.insert 5 $ KVMap.empty.insert `pp.explicit true) -- specify the expected type of `a` in a way that is not erased by the delaborator def typeAs.{u} (α : Type u) (a : α) := () set_option pp.analyze.knowsType false in #eval checkM `(fun (a : Nat) => a) #eval checkM `(fun (a : Nat) => a) #eval checkM `(fun (a b : Nat) => a) #eval checkM `(fun (a : Nat) (b : Bool) => a) #eval checkM `(fun {a b : Nat} => a) -- implicit lambdas work as long as the expected type is preserved #eval checkM `(typeAs ({α : Type} → (a : α) → α) fun a => a) section set_option pp.explicit true #eval checkM `(fun {α : Type} [ToString α] (a : α) => toString a) end #eval checkM `((α : Type) → α) #eval checkM `((α β : Type) → α) -- group #eval checkM `((α β : Type) → Type) -- don't group #eval checkM `((α : Type) → (a : α) → α) #eval checkM `({α : Type} → α) #eval checkM `({α : Type} → [ToString α] → α) #eval checkM `(∀ x : Nat, x = x) #eval checkM `(∀ {x : Nat} [ToString Nat], x = x) set_option pp.piBinderTypes false in #eval checkM `(∀ x : Nat, x = x) -- TODO: hide `ofNat` #eval checkM `(0) #eval checkM `(1) #eval checkM `(42) #eval checkM `("hi") set_option pp.structureInstanceTypes true in #eval checkM `({ type := Nat, val := 0 : PointedType }) #eval checkM `((1,2,3)) #eval checkM `((1,2).fst) #eval checkM `(1 < 2 || true) #eval checkM `(id (fun a => a) 0) #eval checkM `(typeAs Nat (do let x := 1 discard <| pure 2 let y := 3 return x + y)) #eval checkM `(typeAs (Id Nat) (pure 1 >>= pure)) #eval checkM `((0 ≤ 1) = False) #eval checkM `((0 = 1) = False) #eval checkM `(-(-0))
bd5fa76b3b843ca38455b9bbdb11df741fd94219
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/independent.lean
146ec06b43de8638ba276b57da6db1516745ea07
[ "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,437
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.combination import analysis.convex.extreme /-! # Convex independence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines convex independent families of points. Convex independence is closely related to affine independence. In both cases, no point can be written as a combination of others. When the combination is affine (that is, any coefficients), this yields affine independence. When the combination is convex (that is, all coefficients are nonnegative), then this yields convex independence. In particular, affine independence implies convex independence. ## Main declarations * `convex_independent p`: Convex independence of the indexed family `p : ι → E`. Every point of the family only belongs to convex hulls of sets of the family containing it. * `convex_independent_iff_finset`: Carathéodory's theorem allows us to only check finsets to conclude convex independence. * `convex.extreme_points_convex_independent`: Extreme points of a convex set are convex independent. ## References * https://en.wikipedia.org/wiki/Convex_position ## TODO Prove `affine_independent.convex_independent`. This requires some glue between `affine_combination` and `finset.center_mass`. ## Tags independence, convex position -/ open_locale affine big_operators classical open finset function variables {𝕜 E ι : Type*} section ordered_semiring variables (𝕜) [ordered_semiring 𝕜] [add_comm_group E] [module 𝕜 E] {s t : set E} /-- An indexed family is said to be convex independent if every point only belongs to convex hulls of sets containing it. -/ def convex_independent (p : ι → E) : Prop := ∀ (s : set ι) (x : ι), p x ∈ convex_hull 𝕜 (p '' s) → x ∈ s variables {𝕜} /-- A family with at most one point is convex independent. -/ lemma subsingleton.convex_independent [subsingleton ι] (p : ι → E) : convex_independent 𝕜 p := λ s x hx, begin have : (convex_hull 𝕜 (p '' s)).nonempty := ⟨p x, hx⟩, rw [convex_hull_nonempty_iff, set.nonempty_image_iff] at this, rwa subsingleton.mem_iff_nonempty, end /-- A convex independent family is injective. -/ protected lemma convex_independent.injective {p : ι → E} (hc : convex_independent 𝕜 p) : function.injective p := begin refine λ i j hij, hc {j} i _, rw [hij, set.image_singleton, convex_hull_singleton], exact set.mem_singleton _, end /-- If a family is convex independent, so is any subfamily given by composition of an embedding into index type with the original family. -/ lemma convex_independent.comp_embedding {ι' : Type*} (f : ι' ↪ ι) {p : ι → E} (hc : convex_independent 𝕜 p) : convex_independent 𝕜 (p ∘ f) := begin intros s x hx, rw ←f.injective.mem_set_image, exact hc _ _ (by rwa set.image_image), end /-- If a family is convex independent, so is any subfamily indexed by a subtype of the index type. -/ protected lemma convex_independent.subtype {p : ι → E} (hc : convex_independent 𝕜 p) (s : set ι) : convex_independent 𝕜 (λ i : s, p i) := hc.comp_embedding (embedding.subtype _) /-- If an indexed family of points is convex independent, so is the corresponding set of points. -/ protected lemma convex_independent.range {p : ι → E} (hc : convex_independent 𝕜 p) : convex_independent 𝕜 (λ x, x : set.range p → E) := begin let f : set.range p → ι := λ x, x.property.some, have hf : ∀ x, p (f x) = x := λ x, x.property.some_spec, let fe : set.range p ↪ ι := ⟨f, λ x₁ x₂ he, subtype.ext (hf x₁ ▸ hf x₂ ▸ he ▸ rfl)⟩, convert hc.comp_embedding fe, ext, rw [embedding.coe_fn_mk, comp_app, hf], end /-- A subset of a convex independent set of points is convex independent as well. -/ protected lemma convex_independent.mono {s t : set E} (hc : convex_independent 𝕜 (λ x, x : t → E)) (hs : s ⊆ t) : convex_independent 𝕜 (λ x, x : s → E) := hc.comp_embedding (s.embedding_of_subset t hs) /-- The range of an injective indexed family of points is convex independent iff that family is. -/ lemma function.injective.convex_independent_iff_set {p : ι → E} (hi : function.injective p) : convex_independent 𝕜 (λ x, x : set.range p → E) ↔ convex_independent 𝕜 p := ⟨λ hc, hc.comp_embedding (⟨λ i, ⟨p i, set.mem_range_self _⟩, λ x y h, hi (subtype.mk_eq_mk.1 h)⟩ : ι ↪ set.range p), convex_independent.range⟩ /-- If a family is convex independent, a point in the family is in the convex hull of some of the points given by a subset of the index type if and only if the point's index is in this subset. -/ @[simp] protected lemma convex_independent.mem_convex_hull_iff {p : ι → E} (hc : convex_independent 𝕜 p) (s : set ι) (i : ι) : p i ∈ convex_hull 𝕜 (p '' s) ↔ i ∈ s := ⟨hc _ _, λ hi, subset_convex_hull 𝕜 _ (set.mem_image_of_mem p hi)⟩ /-- If a family is convex independent, a point in the family is not in the convex hull of the other points. See `convex_independent_set_iff_not_mem_convex_hull_diff` for the `set` version. -/ lemma convex_independent_iff_not_mem_convex_hull_diff {p : ι → E} : convex_independent 𝕜 p ↔ ∀ i s, p i ∉ convex_hull 𝕜 (p '' (s \ {i})) := begin refine ⟨λ hc i s h, _, λ h s i hi, _⟩, { rw hc.mem_convex_hull_iff at h, exact h.2 (set.mem_singleton _) }, { by_contra H, refine h i s _, rw set.diff_singleton_eq_self H, exact hi } end lemma convex_independent_set_iff_inter_convex_hull_subset {s : set E} : convex_independent 𝕜 (λ x, x : s → E) ↔ ∀ t, t ⊆ s → s ∩ convex_hull 𝕜 t ⊆ t := begin split, { rintro hc t h x ⟨hxs, hxt⟩, refine hc {x | ↑x ∈ t} ⟨x, hxs⟩ _, rw subtype.coe_image_of_subset h, exact hxt }, { intros hc t x h, rw ←subtype.coe_injective.mem_set_image, exact hc (t.image coe) (subtype.coe_image_subset s t) ⟨x.prop, h⟩ } end /-- If a set is convex independent, a point in the set is not in the convex hull of the other points. See `convex_independent_iff_not_mem_convex_hull_diff` for the indexed family version. -/ lemma convex_independent_set_iff_not_mem_convex_hull_diff {s : set E} : convex_independent 𝕜 (λ x, x : s → E) ↔ ∀ x ∈ s, x ∉ convex_hull 𝕜 (s \ {x}) := begin rw convex_independent_set_iff_inter_convex_hull_subset, split, { rintro hs x hxs hx, exact (hs _ (set.diff_subset _ _) ⟨hxs, hx⟩).2 (set.mem_singleton _) }, { rintro hs t ht x ⟨hxs, hxt⟩, by_contra h, exact hs _ hxs (convex_hull_mono (set.subset_diff_singleton ht h) hxt) } end end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] {s : set E} /-- To check convex independence, one only has to check finsets thanks to Carathéodory's theorem. -/ lemma convex_independent_iff_finset {p : ι → E} : convex_independent 𝕜 p ↔ ∀ (s : finset ι) (x : ι), p x ∈ convex_hull 𝕜 (s.image p : set E) → x ∈ s := begin refine ⟨λ hc s x hx, hc s x _, λ h s x hx, _⟩, { rwa finset.coe_image at hx }, have hp : injective p, { rintro a b hab, rw ←mem_singleton, refine h {b} a _, rw [hab, image_singleton, coe_singleton, convex_hull_singleton], exact set.mem_singleton _ }, rw convex_hull_eq_union_convex_hull_finite_subsets at hx, simp_rw set.mem_Union at hx, obtain ⟨t, ht, hx⟩ := hx, rw ←hp.mem_set_image, refine ht _, suffices : x ∈ t.preimage p (hp.inj_on _), { rwa [mem_preimage, ←mem_coe] at this }, refine h _ x _, rwa [t.image_preimage p (hp.inj_on _), filter_true_of_mem], { exact λ y hy, s.image_subset_range p (ht $ mem_coe.2 hy) } end /-! ### Extreme points -/ lemma convex.convex_independent_extreme_points (hs : convex 𝕜 s) : convex_independent 𝕜 (λ p, p : s.extreme_points 𝕜 → E) := convex_independent_set_iff_not_mem_convex_hull_diff.2 $ λ x hx h, (extreme_points_convex_hull_subset (inter_extreme_points_subset_extreme_points_of_subset (convex_hull_min ((set.diff_subset _ _).trans extreme_points_subset) hs) ⟨h, hx⟩)).2 (set.mem_singleton _) end linear_ordered_field
ddd4f181da9203e7c01f03d09d2106efbbeafcb7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/functor/basic.lean
8af552edc4983e8f6b5dad9ec71265ee6d383079
[ "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
3,954
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison -/ import tactic.reassoc_axiom import category_theory.category.basic /-! # Functors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Defines a functor between categories, extending a `prefunctor` between quivers. Introduces notation `C ⥤ D` for the type of all functors from `C` to `D`. (Unfortunately the `⇒` arrow (`\functor`) is taken by core, but in mathlib4 we should switch to this.) -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v v₁ v₂ v₃ u u₁ u₂ u₃ section set_option old_structure_cmd true /-- `functor C D` represents a functor between categories `C` and `D`. To apply a functor `F` to an object use `F.obj X`, and to a morphism use `F.map f`. The axiom `map_id` expresses preservation of identities, and `map_comp` expresses functoriality. See <https://stacks.math.columbia.edu/tag/001B>. -/ structure functor (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] extends prefunctor C D : Type (max v₁ v₂ u₁ u₂) := (map_id' : ∀ (X : C), map (𝟙 X) = 𝟙 (obj X) . obviously) (map_comp' : ∀ {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z), map (f ≫ g) = (map f) ≫ (map g) . obviously) /-- The prefunctor between the underlying quivers. -/ add_decl_doc functor.to_prefunctor end -- A functor is basically a function, so give ⥤ a similar precedence to → (25). -- For example, `C × D ⥤ E` should parse as `(C × D) ⥤ E` not `C × (D ⥤ E)`. infixr ` ⥤ `:26 := functor -- type as \func -- restate_axiom functor.map_id' attribute [simp] functor.map_id restate_axiom functor.map_comp' attribute [reassoc, simp] functor.map_comp namespace functor section variables (C : Type u₁) [category.{v₁} C] /-- `𝟭 C` is the identity functor on a category `C`. -/ -- We don't use `@[simps]` here because we want `C` implicit for the simp lemmas. protected def id : C ⥤ C := { obj := λ X, X, map := λ _ _ f, f } notation `𝟭` := functor.id -- Type this as `\sb1` instance : inhabited (C ⥤ C) := ⟨functor.id C⟩ variable {C} @[simp] lemma id_obj (X : C) : (𝟭 C).obj X = X := rfl @[simp] lemma id_map {X Y : C} (f : X ⟶ Y) : (𝟭 C).map f = f := rfl end section variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] /-- `F ⋙ G` is the composition of a functor `F` and a functor `G` (`F` first, then `G`). -/ @[simps obj] def comp (F : C ⥤ D) (G : D ⥤ E) : C ⥤ E := { obj := λ X, G.obj (F.obj X), map := λ _ _ f, G.map (F.map f) } infixr ` ⋙ `:80 := comp @[simp] lemma comp_map (F : C ⥤ D) (G : D ⥤ E) {X Y : C} (f : X ⟶ Y) : (F ⋙ G).map f = G.map (F.map f) := rfl -- These are not simp lemmas because rewriting along equalities between functors -- is not necessarily a good idea. -- Natural isomorphisms are also provided in `whiskering.lean`. protected lemma comp_id (F : C ⥤ D) : F ⋙ (𝟭 D) = F := by cases F; refl protected lemma id_comp (F : C ⥤ D) : (𝟭 C) ⋙ F = F := by cases F; refl @[simp] lemma map_dite (F : C ⥤ D) {X Y : C} {P : Prop} [decidable P] (f : P → (X ⟶ Y)) (g : ¬P → (X ⟶ Y)) : F.map (if h : P then f h else g h) = if h : P then F.map (f h) else F.map (g h) := by { split_ifs; refl, } @[simp] lemma to_prefunctor_obj (F : C ⥤ D) (X : C) : F.to_prefunctor.obj X = F.obj X := rfl @[simp] lemma to_prefunctor_map (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) : F.to_prefunctor.map f = F.map f := rfl @[simp] lemma to_prefunctor_comp (F : C ⥤ D) (G : D ⥤ E) : F.to_prefunctor.comp G.to_prefunctor = (F ⋙ G).to_prefunctor := rfl end end functor end category_theory
811598cf10d43add03d90e5bd6b923480ad6c37c
fe6a6bdd171ff04b1f2728c050ebe0262fb5f788
/MdT - Beginning.lean
c3f46c6cc674fb55a46235fc140ab9782693582f
[]
no_license
FeIipeVieira/LogicasFormaisSistemasNormativos
4a4cc9fe2fa70e7acdc1ff34b81783b6a26a2b6f
c63dd3b15a072779200a12eb6b88a60acf065d70
refs/heads/master
1,583,547,325,700
1,536,799,298,000
1,536,799,298,000
127,204,138
1
0
null
null
null
null
UTF-8
Lean
false
false
2,030
lean
universe u inductive movimento: Type | direita : movimento | esquerda : movimento | parado : movimento structure configuracao : Type := mk :: (estAtual: int) -- (simboloLer: nat) (simboloEsc: nat) (mov: movimento) (proxEst: int) def confInvalida: configuracao := configuracao.mk 0 0 0 sorry 0 structure fita : Type := mk :: (anterior: list nat) (proximo: list nat) (atual: list nat) structure MdT : Type := mk :: (transicoes: list configuracao) (simbolos: list nat) -- 0, 1 para escrita e 2 para representar o vazio. (estInicial: int) -- Estado permitidos: ≥ 0; Estado de erro: -1. (isEstFinal: int -> bool) -- (proxEst: int -> nat -> int) -- Pega um estado mais um simbolo e leva em outro estado. def is_equal : list char → list char → bool | [] [] := tt | (x :: xs) [] := ff | [] (y :: ys) := ff | (x :: xs) (y :: ys) := (x = y) && is_equal xs ys def find_int (x : int) : list int -> option int | [] := none | (y :: ys) := if x = y then return 0 else do r <- find_int ys, return (r + 1) def find_int_in_conf (x : int) : list configuracao -> option int | [] := none | (y :: ys) := if x = y.estAtual then return x else do r <- find_int_in_conf ys, return (r + 1) def checaSimbolo (simboloEsp: nat) (simboloLido: nat) (proxEst: int) : int := if(simboloLido = simboloEsp) then proxEst else -1 -- Leu um símbolo que não era o símbolo esperado para o estado atual? Erro produzido. def procuraConf (maquina: MdT): configuracao := -- Talvez possa usar só find int_in_conf if((find_int_in_conf maquina.estInicial maquina.transicoes) = maquina.estInicial) then sorry else confInvalida def checaEstado (maquina: MdT) (tape: fita): int := let conftemp := configuracao in procuraConf maquina if((checaSimbolo (conftemp.simboloLer)(tape.atual)(conftemp.proxEst)) = (-1)) then -1 -- Cheguei num estado aonde o simbolo lido nao é o simbolo esperado para o estado. Quit else if --def avalia -- def visualizaFita