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
cdea452d5ac7deacc52ee29de69fb97edf165834
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/list.lean
dc5048331f6489b51a8b70a81024331b12ee526f
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
8,452
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Topology on lists and vectors. -/ import topology.constructions open topological_space set filter open_locale topological_space variables {α : Type*} {β : Type*} instance [topological_space α] : topological_space (list α) := topological_space.mk_of_nhds (traverse nhds) lemma nhds_list [topological_space α] (as : list α) : 𝓝 as = traverse 𝓝 as := begin refine nhds_mk_of_nhds _ _ _ _, { assume l, induction l, case list.nil { exact le_refl _ }, case list.cons : a l ih { suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> 𝓝 a <*> traverse 𝓝 l, { simpa only [] with functor_norm using this }, exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } }, { assume l s hs, rcases (mem_traverse_sets_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs, have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s, { induction hu generalizing s, case list.forall₂.nil : hs this { existsi [], simpa only [list.forall₂_nil_left_iff, exists_eq_left] }, case list.forall₂.cons : a s as ss ht h ih t hts { rcases mem_nhds_sets_iff.1 ht with ⟨u, hut, hu⟩, rcases ih (subset.refl _) with ⟨v, hv, hvss⟩, exact ⟨u::v, list.forall₂.cons hu hv, subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } }, rcases this with ⟨v, hv, hvs⟩, refine ⟨sequence v, mem_traverse_sets _ _ _, hvs, _⟩, { exact hv.imp (assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) }, { assume u hu, have hu := (list.mem_traverse _ _).1 hu, have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v, { refine list.forall₂.flip _, replace hv := hv.flip, simp only [list.forall₂_and_left, flip] at ⊢ hv, exact ⟨hv.1, hu.flip⟩ }, refine mem_sets_of_superset _ hvs, exact mem_traverse_sets _ _ (this.imp $ assume a s ⟨hs, ha⟩, mem_nhds_sets hs ha) } } end lemma nhds_nil [topological_space α] : 𝓝 ([] : list α) = pure [] := by rw [nhds_list, list.traverse_nil _]; apply_instance lemma nhds_cons [topological_space α] (a : α) (l : list α) : 𝓝 (a :: l) = list.cons <$> 𝓝 a <*> 𝓝 l := by rw [nhds_list, list.traverse_cons _, ← nhds_list]; apply_instance namespace list variables [topological_space α] [topological_space β] lemma tendsto_cons' {a : α} {l : list α} : tendsto (λp:α×list α, list.cons p.1 p.2) ((𝓝 a).prod (𝓝 l)) (𝓝 (a :: l)) := by rw [nhds_cons, tendsto, map_prod]; exact le_refl _ lemma tendsto_cons {α : Type*} {f : α → β} {g : α → list β} {a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (𝓝 b)) (hg : tendsto g a (𝓝 l)) : tendsto (λa, list.cons (f a) (g a)) a (𝓝 (b :: l)) := tendsto_cons'.comp (tendsto.prod_mk hf hg) lemma tendsto_cons_iff {β : Type*} {f : list α → β} {b : _root_.filter β} {a : α} {l : list α} : tendsto f (𝓝 (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) ((𝓝 a).prod (𝓝 l)) b := have 𝓝 (a :: l) = ((𝓝 a).prod (𝓝 l)).map (λp:α×list α, (p.1 :: p.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm, end, by rw [this, filter.tendsto_map'_iff] lemma tendsto_nhds {β : Type*} {f : list α → β} {r : list α → _root_.filter β} (h_nil : tendsto f (pure []) (r [])) (h_cons : ∀l a, tendsto f (𝓝 l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) ((𝓝 a).prod (𝓝 l)) (r (a::l))) : ∀l, tendsto f (𝓝 l) (r l) | [] := by rwa [nhds_nil] | (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l) lemma continuous_at_length : ∀(l : list α), continuous_at list.length l := begin simp only [continuous_at, nhds_discrete], refine tendsto_nhds _ _, { exact tendsto_pure_pure _ _ }, { assume l a ih, dsimp only [list.length], refine tendsto.comp (tendsto_pure_pure (λx, x + 1) _) _, refine tendsto.comp ih tendsto_snd } end lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α}, tendsto (λp:α×list α, insert_nth n p.1 p.2) ((𝓝 a).prod (𝓝 l)) (𝓝 (insert_nth n a l)) | 0 l := tendsto_cons' | (n+1) [] := suffices tendsto (λa, []) (𝓝 a) (𝓝 ([] : list α)), by simpa [nhds_nil, tendsto, map_prod, (∘), insert_nth], tendsto_const_nhds | (n+1) (a'::l) := have (𝓝 a).prod (𝓝 (a' :: l)) = ((𝓝 a).prod ((𝓝 a').prod (𝓝 l))).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm end, begin rw [this, tendsto_map'_iff], exact tendsto_cons (tendsto_fst.comp tendsto_snd) ((@tendsto_insert_nth' n l).comp (tendsto.prod_mk tendsto_fst (tendsto_snd.comp tendsto_snd))) end lemma tendsto_insert_nth {β : Type*} {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α} {b : _root_.filter β} (hf : tendsto f b (𝓝 a)) (hg : tendsto g b (𝓝 l)) : tendsto (λb:β, insert_nth n (f b) (g b)) b (𝓝 (insert_nth n a l)) := tendsto_insert_nth'.comp (tendsto.prod_mk hf hg) lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth' lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α}, tendsto (λl, remove_nth l n) (𝓝 l) (𝓝 (remove_nth l n)) | _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd | (n+1) (a::l) := begin rw [tendsto_cons_iff], dsimp [remove_nth], exact tendsto_cons tendsto_fst ((@tendsto_remove_nth n l).comp tendsto_snd) end lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) := continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth end list namespace vector open list instance (n : ℕ) [topological_space α] : topological_space (vector α n) := by unfold vector; apply_instance lemma cons_val {n : ℕ} {a : α} : ∀{v : vector α n}, (a :: v).val = a :: v.val | ⟨l, hl⟩ := rfl lemma tendsto_cons [topological_space α] {n : ℕ} {a : α} {l : vector α n}: tendsto (λp:α×vector α n, vector.cons p.1 p.2) ((𝓝 a).prod (𝓝 l)) (𝓝 (a :: l)) := by simp [tendsto_subtype_rng, cons_val]; exact tendsto_cons tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd) lemma tendsto_insert_nth [topological_space α] {n : ℕ} {i : fin (n+1)} {a:α} : ∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2) ((𝓝 a).prod (𝓝 l)) (𝓝 (insert_nth a i l)) | ⟨l, hl⟩ := begin rw [insert_nth, tendsto_subtype_rng], simp [insert_nth_val], exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_val tendsto_snd : _) end lemma continuous_insert_nth' [topological_space α] {n : ℕ} {i : fin (n+1)} : continuous (λp:α×vector α n, insert_nth p.1 i p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth lemma continuous_insert_nth [topological_space α] [topological_space β] {n : ℕ} {i : fin (n+1)} {f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) : continuous (λb, insert_nth (f b) i (g b)) := continuous_insert_nth'.comp (continuous.prod_mk hf hg) lemma continuous_at_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} : ∀{l:vector α (n+1)}, continuous_at (remove_nth i) l | ⟨l, hl⟩ := -- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (𝓝 l) (𝓝 (remove_nth i l)) --| ⟨l, hl⟩ := begin rw [continuous_at, remove_nth, tendsto_subtype_rng], simp [remove_nth_val], exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_val end lemma continuous_remove_nth [topological_space α] {n : ℕ} {i : fin (n+1)} : continuous (remove_nth i : vector α (n+1) → vector α n) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, continuous_at_remove_nth end vector
6b2c59656d4397f46fc7210e8b468a2ef73fc56f
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0904.lean
5d90824494a0b2a6aaba8c6ccad21bbba0af4fa3
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
466
lean
namespace hidden universe u constant list : Type u → Type u namespace list constant cons : Π {α : Type u}, α → list α → list α constant nil : Π {α : Type u}, list α constant append : Π {α : Type u}, list α → list α → list α end list end hidden open hidden.list variable α : Type variable a : α variables l1 l2 : hidden.list α #check cons a nil #check append (cons a nil) l1 #check append (append (cons a nil) l1) l2
5169d3350c5258df3bcc806da20b2bb1660a3758
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Meta/Tactic/Simp/Rewrite.lean
8bcb1ac7e30de0bf2918493f0e58e7b1844a9fc3
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,250
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.SynthInstance import Lean.Meta.Tactic.Simp.Types namespace Lean.Meta.Simp def synthesizeArgs (lemmaName : Name) (xs : Array Expr) (bis : Array BinderInfo) (discharge? : Expr → SimpM (Option Expr)) : SimpM Bool := do for x in xs, bi in bis do let type ← inferType x if bi.isInstImplicit then unless (← synthesizeInstance x type) do return false else if (← instantiateMVars x).isMVar then if (← isProp type) then match (← discharge? type) with | some proof => unless (← isDefEq x proof) do trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to assign proof{indentExpr type}" return false | none => trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to discharge hypotheses{indentExpr type}" return false else if (← isClass? type).isSome then unless (← synthesizeInstance x type) do return false return true where synthesizeInstance (x type : Expr) : SimpM Bool := do match (← trySynthInstance type) with | LOption.some val => if (← isDefEq x val) then return true else trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to assign instance{indentExpr type}" return false | _ => trace[Meta.Tactic.simp.discharge] "{lemmaName}, failed to synthesize instance{indentExpr type}" return false /- Remark: the parameter tag is used for creating trace messages. It is irrelevant otherwise. -/ def rewrite (e : Expr) (s : DiscrTree SimpLemma) (erased : Std.PHashSet Name) (discharge? : Expr → SimpM (Option Expr)) (tag : String) : SimpM Result := do let lemmas ← s.getMatch e if lemmas.isEmpty then trace[Debug.Meta.Tactic.simp] "no theorems found for {tag}-rewriting {e}" return { expr := e } else let lemmas := lemmas.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority for lemma in lemmas do unless inErasedSet lemma do if let some result ← tryLemma? lemma then return result return { expr := e } where inErasedSet (lemma : SimpLemma) : Bool := match lemma.name? with | none => false | some name => erased.contains name tryLemma? (lemma : SimpLemma) : SimpM (Option Result) := withNewMCtxDepth do let val ← lemma.getValue let type ← inferType val let (xs, bis, type) ← forallMetaTelescopeReducing type let type ← instantiateMVars type let lhs := type.appFn!.appArg! if (← isDefEq lhs e) then unless (← synthesizeArgs lemma.getName xs bis discharge?) do return none let proof ← instantiateMVars (mkAppN val xs) if ← hasAssignableMVar proof then trace[Meta.Tactic.simp.rewrite] "{lemma}, has unassigned metavariables after unification" return none let rhs ← instantiateMVars type.appArg! if e == rhs then return none if lemma.perm && !Expr.lt rhs e then trace[Meta.Tactic.simp.rewrite] "{lemma}, perm rejected {e} ==> {rhs}" return none trace[Meta.Tactic.simp.rewrite] "{lemma}, {e} ==> {rhs}" return some { expr := rhs, proof? := proof } else unless lhs.isMVar do -- We do not report unification failures when `lhs` is a metavariable -- Example: `x = ()` -- TODO: reconsider if we want lemmas such as `(x : Unit) → x = ()` trace[Meta.Tactic.simp.unify] "{lemma}, failed to unify {lhs} with {e}" return none def rewriteCtorEq? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do match e.eq? with | none => return none | some (_, lhs, rhs) => let lhs ← whnf lhs let rhs ← whnf rhs let env ← getEnv match lhs.constructorApp? env, rhs.constructorApp? env with | some (c₁, _), some (c₂, _) => if c₁.name != c₂.name then withLocalDeclD `h e fun h => return some { expr := mkConst ``False, proof? := (← mkEqFalse' (← mkLambdaFVars #[h] (← mkNoConfusion (mkConst ``False) h))) } else return none | _, _ => return none @[inline] def tryRewriteCtorEq (e : Expr) (x : SimpM Step) : SimpM Step := do match (← rewriteCtorEq? e) with | some r => return Step.done r | none => x def rewriteUsingDecide? (e : Expr) : MetaM (Option Result) := withReducibleAndInstances do if e.hasFVar || e.hasMVar || e.isConstOf ``True || e.isConstOf ``False then return none else try let d ← mkDecide e let r ← withDefault <| whnf d if r.isConstOf ``true then return some { expr := mkConst ``True, proof? := mkAppN (mkConst ``eq_true_of_decide) #[e, d.appArg!, (← mkEqRefl (mkConst ``true))] } else if r.isConstOf ``false then let h ← mkEqRefl d return some { expr := mkConst ``False, proof? := mkAppN (mkConst ``eq_false_of_decide) #[e, d.appArg!, (← mkEqRefl (mkConst ``false))] } else return none catch _ => return none @[inline] def tryRewriteUsingDecide (e : Expr) (x : SimpM Step) : SimpM Step := do if (← read).config.decide then match (← rewriteUsingDecide? e) with | some r => return Step.done r | none => x else x def rewritePre (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.pre lemmas.erased discharge? (tag := "pre")) def rewritePost (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do let lemmas ← (← read).simpLemmas return Step.visit (← rewrite e lemmas.post lemmas.erased discharge? (tag := "post")) def preDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := tryRewriteCtorEq e <| rewritePre e discharge? def postDefault (e : Expr) (discharge? : Expr → SimpM (Option Expr)) : SimpM Step := do -- TODO: try equation lemmas tryRewriteCtorEq e <| tryRewriteUsingDecide e <| rewritePost e discharge? end Lean.Meta.Simp
d5ed7dd14ff7b913346446f677c33ef9dcc29d90
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/for_mathlib/finsupp_prod_inv.lean
d7f705e8e6f70bb69a7a895441226018d1ed2819
[ "Apache-2.0" ]
permissive
semorrison/lean-perfectoid-spaces
78c1572cedbfae9c3e460d8aaf91de38616904d8
bb4311dff45791170bcb1b6a983e2591bee88a19
refs/heads/master
1,588,841,765,494
1,554,805,620,000
1,554,805,620,000
180,353,546
0
1
null
1,554,809,880,000
1,554,809,880,000
null
UTF-8
Lean
false
false
883
lean
import data.finsupp universes u v w namespace finsupp variables {α : Type u} {β : Type v} {γ : Type w} variables [decidable_eq α] [decidable_eq β] [add_group β] [comm_group γ] variables {g : α →₀ β} {h h₁ h₂ : α → β → γ} theorem prod_mul_distrib : finsupp.prod g (λ a b, h₁ a b * h₂ a b) = finsupp.prod g h₁ * finsupp.prod g h₂ := finset.prod_mul_distrib theorem prod_const_one : finsupp.prod g (λ a b, (1 : γ)) = 1 := finset.prod_const_one theorem prod_inv : finsupp.prod g (λ a b, (h a b)⁻¹) = (finsupp.prod g h)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← prod_mul_distrib]; simp only [inv_mul_self]; exact prod_const_one theorem prod_neg_index' (h0 : ∀ a, h a 0 = 1) (hn : ∀ a b, h a (-b) = (h a b)⁻¹) : finsupp.prod (-g) h = (finsupp.prod g h)⁻¹ := by rw [prod_neg_index h0]; simp only [hn]; exact prod_inv end finsupp
ad1fa462084e4b0bcdfb0691b068122a98f09383
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/types/functor.lean
49faa80544cf7387f4261a47d1ee48f795e4c52d
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,087
lean
-- -- Copyright (c) 2018 Scott Morrison. All rights reserved. -- -- Released under Apache 2.0 license as described in the file LICENSE. -- -- Authors: Scott Morrison -- import category_theory.types -- import category_theory.tactics.obviously -- open category_theory -- universes u v -- instance functor_of_functor (F : (Type u) ⥤ (Type v)) : _root_.functor F.obj := -- { map := λ _ _ f, F.map f } -- -- local attribute [tidy] dsimp' -- -- TODO yuck, automate -- instance lawful_functor_of_Functor (F : (Type u) ⥤ (Type v)) : is_lawful_functor (F.obj) := -- { id_map := begin obviously, end, -- comp_map := begin -- tidy, -- calc (F.map (λ (x : α), h (g x))) x = (F.map (g ≫ h)) x : by obviously -- ... = (F.map h) ((F.map g) x) : by obviously -- end -- } -- attribute [search] is_lawful_functor.comp_map -- def functor_of_functor' (g : Type u → Type v) [functor g] [is_lawful_functor g] : (Type u) ⥤ (Type v) := -- { obj := g, -- map' := λ X Y f z, f <$> z }
d96a60368b67616f57c2ad4e7da76d886921b62a
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/witt_vector/witt_polynomial.lean
1e469e6505c1751921ceeaed396d299258fad92c
[ "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
10,817
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import algebra.char_p.invertible import data.fintype.card import data.mv_polynomial.variables import data.mv_polynomial.comm_ring import data.mv_polynomial.expand import data.zmod.basic /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ open mv_polynomial open finset (hiding map) open finsupp (single) open_locale big_operators local attribute [-simp] coe_eval₂_hom variables (p : ℕ) variables (R : Type*) [comm_ring R] /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ noncomputable def witt_polynomial (n : ℕ) : mv_polynomial ℕ R := ∑ i in range (n+1), monomial (single i (p ^ (n - i))) (p ^ i : R) lemma witt_polynomial_eq_sum_C_mul_X_pow (n : ℕ) : witt_polynomial p R n = ∑ i in range (n+1), C (p ^ i : R) * X i ^ (p ^ (n - i)) := begin apply sum_congr rfl, rintro i -, rw [monomial_eq, finsupp.prod_single_index], rw pow_zero, end /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit localized "notation `W_` := witt_polynomial p" in witt -- Notation with ring of coefficients implicit localized "notation `W` := witt_polynomial p _" in witt open_locale witt open mv_polynomial /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map_witt_polynomial (f : R →+* S) (n : ℕ) : map f (W n) = W n := begin rw [witt_polynomial, ring_hom.map_sum, witt_polynomial, sum_congr rfl], intros i hi, rw [map_monomial, ring_hom.map_pow, ring_hom.map_nat_cast], end variables (R) @[simp] lemma constant_coeff_witt_polynomial [hp : fact p.prime] (n : ℕ) : constant_coeff (witt_polynomial p R n) = 0 := begin simp only [witt_polynomial, ring_hom.map_sum, constant_coeff_monomial], rw [sum_eq_zero], rintro i hi, rw [if_neg], rw [finsupp.single_eq_zero], exact ne_of_gt (pow_pos hp.1.pos _) end @[simp] lemma witt_polynomial_zero : witt_polynomial p R 0 = X 0 := by simp only [witt_polynomial, X, sum_singleton, range_one, pow_zero] @[simp] lemma witt_polynomial_one : witt_polynomial p R 1 = C ↑p * X 1 + (X 0) ^ p := by simp only [witt_polynomial_eq_sum_C_mul_X_pow, sum_range_succ_comm, range_one, sum_singleton, one_mul, pow_one, C_1, pow_zero] lemma aeval_witt_polynomial {A : Type*} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : aeval f (W_ R n) = ∑ i in range (n+1), p^i * (f i) ^ (p ^ (n-i)) := by simp [witt_polynomial, alg_hom.map_sum, aeval_monomial, finsupp.prod_single_index] /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th Witt polynomial by `p`. -/ @[simp] lemma witt_polynomial_zmod_self (n : ℕ) : W_ (zmod (p ^ (n + 1))) (n + 1) = expand p (W_ (zmod (p^(n + 1))) n) := begin simp only [witt_polynomial_eq_sum_C_mul_X_pow], rw [sum_range_succ, ← nat.cast_pow, char_p.cast_eq_zero (zmod (p^(n+1))) (p^(n+1)), C_0, zero_mul, add_zero, alg_hom.map_sum, sum_congr rfl], intros k hk, rw [alg_hom.map_mul, alg_hom.map_pow, expand_X, alg_hom_C, ← pow_mul, ← pow_succ], congr, rw mem_range at hk, rw [add_comm, add_tsub_assoc_of_le (nat.lt_succ_iff.mp hk), ← add_comm], end section p_prime -- in fact, `0 < p` would be sufficient variables [hp : fact p.prime] include hp lemma witt_polynomial_vars [char_zero R] (n : ℕ) : (witt_polynomial p R n).vars = range (n + 1) := begin have : ∀ i, (monomial (finsupp.single i (p ^ (n - i))) (p ^ i : R)).vars = {i}, { intro i, refine vars_monomial_single i (pow_ne_zero _ hp.1.ne_zero) _, rw [← nat.cast_pow, nat.cast_ne_zero], exact pow_ne_zero i hp.1.ne_zero }, rw [witt_polynomial, vars_sum_of_disjoint], { simp only [this, int.nat_cast_eq_coe_nat, bUnion_singleton_eq_self], }, { simp only [this, int.nat_cast_eq_coe_nat], intros a b h, apply disjoint_singleton_left.mpr, rwa mem_singleton, }, end lemma witt_polynomial_vars_subset (n : ℕ) : (witt_polynomial p R n).vars ⊆ range (n + 1) := begin rw [← map_witt_polynomial p (int.cast_ring_hom R), ← witt_polynomial_vars p ℤ], apply vars_map, end end p_prime end /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ noncomputable def X_in_terms_of_W [invertible (p : R)] : ℕ → mv_polynomial ℕ R | n := (X n - (∑ i : fin n, have _ := i.2, (C (p^(i : ℕ) : R) * (X_in_terms_of_W i)^(p^(n-i))))) * C (⅟p ^ n : R) lemma X_in_terms_of_W_eq [invertible (p : R)] {n : ℕ} : X_in_terms_of_W p R n = (X n - (∑ i in range n, C (p^i : R) * X_in_terms_of_W p R i ^ p ^ (n - i))) * C (⅟p ^ n : R) := by { rw [X_in_terms_of_W, ← fin.sum_univ_eq_sum_range] } @[simp] lemma constant_coeff_X_in_terms_of_W [hp : fact p.prime] [invertible (p : R)] (n : ℕ) : constant_coeff (X_in_terms_of_W p R n) = 0 := begin apply nat.strong_induction_on n; clear n, intros n IH, rw [X_in_terms_of_W_eq, mul_comm, ring_hom.map_mul, ring_hom.map_sub, ring_hom.map_sum, constant_coeff_C, sum_eq_zero], { simp only [constant_coeff_X, sub_zero, mul_zero] }, { intros m H, rw mem_range at H, simp only [ring_hom.map_mul, ring_hom.map_pow, constant_coeff_C, IH m H], rw [zero_pow, mul_zero], apply pow_pos hp.1.pos, } end @[simp] lemma X_in_terms_of_W_zero [invertible (p : R)] : X_in_terms_of_W p R 0 = X 0 := by rw [X_in_terms_of_W_eq, range_zero, sum_empty, pow_zero, C_1, mul_one, sub_zero] section p_prime variables [hp : fact p.prime] include hp lemma X_in_terms_of_W_vars_aux (n : ℕ) : n ∈ (X_in_terms_of_W p ℚ n).vars ∧ (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := begin apply nat.strong_induction_on n, clear n, intros n ih, rw [X_in_terms_of_W_eq, mul_comm, vars_C_mul, vars_sub_of_disjoint, vars_X, range_succ, insert_eq], swap 3, { apply nonzero_of_invertible }, work_on_goal 0 { simp only [true_and, true_or, eq_self_iff_true, mem_union, mem_singleton], intro i, rw [mem_union, mem_union], apply or.imp id }, work_on_goal 1 { rw [vars_X, disjoint_singleton_left] }, all_goals { intro H, replace H := vars_sum_subset _ _ H, rw mem_bUnion at H, rcases H with ⟨j, hj, H⟩, rw vars_C_mul at H, swap, { apply pow_ne_zero, exact_mod_cast hp.1.ne_zero }, rw mem_range at hj, replace H := (ih j hj).2 (vars_pow _ _ H), rw mem_range at H }, { rw mem_range, exact lt_of_lt_of_le H hj }, { exact lt_irrefl n (lt_of_lt_of_le H hj) }, end lemma X_in_terms_of_W_vars_subset (n : ℕ) : (X_in_terms_of_W p ℚ n).vars ⊆ range (n + 1) := (X_in_terms_of_W_vars_aux p n).2 end p_prime lemma X_in_terms_of_W_aux [invertible (p : R)] (n : ℕ) : X_in_terms_of_W p R n * C (p^n : R) = X n - ∑ i in range n, C (p^i : R) * (X_in_terms_of_W p R i)^p^(n-i) := by rw [X_in_terms_of_W_eq, mul_assoc, ← C_mul, ← mul_pow, inv_of_mul_self, one_pow, C_1, mul_one] @[simp] lemma bind₁_X_in_terms_of_W_witt_polynomial [invertible (p : R)] (k : ℕ) : bind₁ (X_in_terms_of_W p R) (W_ R k) = X k := begin rw [witt_polynomial_eq_sum_C_mul_X_pow, alg_hom.map_sum], simp only [alg_hom.map_pow, C_pow, alg_hom.map_mul, alg_hom_C], rw [sum_range_succ_comm, tsub_self, pow_zero, pow_one, bind₁_X_right, mul_comm, ← C_pow, X_in_terms_of_W_aux], simp only [C_pow, bind₁_X_right, sub_add_cancel], end @[simp] lemma bind₁_witt_polynomial_X_in_terms_of_W [invertible (p : R)] (n : ℕ) : bind₁ (W_ R) (X_in_terms_of_W p R n) = X n := begin apply nat.strong_induction_on n, clear n, intros n H, rw [X_in_terms_of_W_eq, alg_hom.map_mul, alg_hom.map_sub, bind₁_X_right, alg_hom_C, alg_hom.map_sum], have : W_ R n - ∑ i in range n, C (p ^ i : R) * (X i) ^ p ^ (n - i) = C (p ^ n : R) * X n, by simp only [witt_polynomial_eq_sum_C_mul_X_pow, tsub_self, sum_range_succ_comm, pow_one, add_sub_cancel, pow_zero], rw [sum_congr rfl, this], { -- this is really slow for some reason rw [mul_right_comm, ← C_mul, ← mul_pow, mul_inv_of_self, one_pow, C_1, one_mul] }, { intros i h, rw mem_range at h, simp only [alg_hom.map_mul, alg_hom.map_pow, alg_hom_C, H i h] }, end
c68d5c8009aa75c2ffbfc076cc27215de216654b
33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354
/dlo/dnf.lean
0e311fd734813268736a076b8a88f989e0fa273c
[]
no_license
lclem/cooper
79554e72ced343c64fed24b2d892d24bf9447dfe
812afc6b158821f2e7dac9c91d3b6123c7a19faf
refs/heads/master
1,607,554,257,488
1,578,694,133,000
1,578,694,133,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,261
lean
import .nnf open list -- Requires : nqfree arg-0 def dnf_core : formula_dlo → list (list atom_dlo) | (formula_dlo.true) := [[]] | (formula_dlo.false) := [] | (formula_dlo.atom a) := [[a]] | (formula_dlo.and p q) := map append_pair $ product (dnf_core p) (dnf_core q) | (formula_dlo.or p q) := dnf_core p ++ dnf_core q | (formula_dlo.ex _) := [] | (formula_dlo.not _) := [] def dnf : formula_dlo → list (list atom_dlo) := dnf_core ∘ nnf def to_frm (ls : list (list atom_dlo)) := disj (map conj_atom ls) lemma eval_to_frm (bs) (ls : list (list atom_dlo)) : (to_frm ls).eval bs ↔ ∃ l ∈ ls, avals bs l := begin simp [to_frm, eval_disj], constructor; intro h, { cases h with p hp, cases hp with hp1 hp2, cases hp1 with l hl, cases hl with h1 h2, subst h2, simp [eval_conj_atom] at hp2, existsi l, apply and.intro h1 hp2 }, { cases h with l hl, existsi (conj_atom l), constructor, { existsi l, constructor, apply hl.left, refl }, { simp [eval_conj_atom], apply hl.right } } end lemma some_core_disjunct_true_iff : ∀ {p : formula_dlo}, nqfree p → ∀ {bs : list rat}, (∃ (as : list atom_dlo), as ∈ dnf_core p ∧ ∀ (a : atom_dlo), a ∈ as → atom_dlo.eval bs a) ↔ p.eval bs | ⊤' h1 bs := begin simp [dnf_core] end | ⊥' h1 bs := begin simp [dnf_core, formula_dlo.eval] end | (A' a) h1 bs := begin simp [dnf_core, formula_dlo.eval] end | (p ∨' q) h1 bs := begin cases h1 with hp hq, simp [dnf_core, eval_or], apply iff.trans (exists_iff_exists _) _; [ {}, { intro as, apply or_and_distrib_right}, { rw exists_or_distrib, apply or_iff_or; apply some_core_disjunct_true_iff; assumption } ] end | (p ∧' q) h1 bs := begin simp [dnf_core, eval_and], constructor; intro h2; [ { cases h1 with hp hq, cases h2 with as h2, cases h2 with h2 h3, cases h2 with as2 h2, cases h2 with as3 h2, cases h2 with h2 h4, cases h2 with h2p h2q, subst h4, simp only [append_pair] at h3, rw [forall_mem_append] at h3, cases h3 with h3 h4, constructor; [ { rw (some_core_disjunct_true_iff _).symm, existsi as2, constructor; assumption, assumption }, { rw (some_core_disjunct_true_iff _).symm, existsi as3, constructor; assumption, assumption } ] }, { cases h1 with h1p h1q, cases h2 with h2p h2q, rw (some_core_disjunct_true_iff h1p).symm at h2p, rw (some_core_disjunct_true_iff h1q).symm at h2q, cases h2p with as1 hp, cases hp with hp1 hp2, cases h2q with as2 hq, cases hq with hq1 hq2, existsi (as1 ++ as2), constructor; [ { existsi as1, existsi as2, apply and.intro _ rfl, constructor; assumption }, { intros a ha, rw mem_append at ha, cases ha; [{apply hp2},{apply hq2}]; assumption } ] } ] end lemma some_disjunct_true_iff {p : formula_dlo} (h : qfree p) {bs : list rat} : (∃ (as : list atom_dlo), as ∈ dnf p ∧ ∀ (a : atom_dlo), a ∈ as → atom_dlo.eval bs a) ↔ p.eval bs := begin simp [dnf, dnf_core], rw some_core_disjunct_true_iff, apply eval_nnf h, apply nqfree_nnf h, end #exit lemma join_dnf_core_subset_atms : ∀ {φ : formula_dlo}, join (dnf_core φ) ⊆ atom_dlos φ | (A' a') a h := begin simp [dnf_core, atms] at *, assumption end | (p ∧' q) a h := begin simp [dnf_core, atms] at *, cases h with as1 h, cases h with h h1, cases h with as2 h, cases h with as3 h, cases h with h2 h4, cases h2 with h2 h3, subst h4, rw mem_append at h1, cases h1; [ {apply or.inl, apply join_dnf_core_subset_atms, rw mem_join, existsi as2, constructor; assumption}, {apply or.inr, apply join_dnf_core_subset_atms, rw mem_join, existsi as3, constructor; assumption} ] end | (p ∨' q) a h := begin simp [dnf_core, atms] at *, cases h; cases h with as h; cases h with h1 h2; [ {apply or.inl, apply join_dnf_core_subset_atms, rw mem_join, existsi as, constructor; assumption}, {apply or.inr, apply join_dnf_core_subset_atms, rw mem_join, existsi as, constructor; assumption} ] end lemma forall_mem_dnf_core_forall_mem [axms α] (p : atom_dlo → Prop) : ∀ (φ : formula_dlo), (∀ a ∈ (atms φ), p a) → ∀ as ∈ (dnf_core φ), ∀ a ∈ as, p a := begin intros φ h1 as h2 a h3, apply h1, apply join_dnf_core_subset_atms, rw mem_join, existsi as, constructor; assumption end lemma forall_mem_dnf_core_forall_mem_normal [axms α] : ∀ {p : formula_dlo}, @fnormal α _ p → ∀ {as : list atom_dlo}, as ∈ (dnf_core p) → ∀ a ∈ as, normal a := begin intros p hp, rewrite fnormal_iff_fnormal_alt at hp, apply forall_mem_dnf_core_forall_mem (normal) _ hp, end lemma forall_mem_dnf_forall_mem_normal [axms α] {p : formula_dlo} (hp1 : qfree p) (hp2 : fnormal p) : ∀ {as : list atom_dlo}, (as ∈ (dnf p)) → ∀ a ∈ as, normal a := begin intros as has, simp [dnf] at has, apply forall_mem_dnf_core_forall_mem_normal _ has, apply nnf.fnormal_dnf hp1 hp2 end
d2fd1043ff6447d4fab20ac7388246060ce21997
690889011852559ee5ac4dfea77092de8c832e7e
/src/data/fintype.lean
9cc3c4441c59160d0a4a3a7b204ebf0f07887451
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
33,776
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset algebra.big_operators data.array.lemmas logic.unique import tactic.wlog universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext] end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [fintype α] [fintype β] [decidable_eq β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [fintype α] [decidable_eq α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [fintype β] [decidable_eq β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨finset.singleton a, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = finset.singleton a := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = (finset.univ : finset α).sum (λ _, 1) := finset.card_eq_sum_ones _ end fintype lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1), list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩, λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := by rw [fin.fintype]; simp [fintype.card, card, univ] @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := ⟨finset.singleton (default α), λ x, by rw [unique.eq_default x]; simp⟩ @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () @[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl @[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) := card_sigma _ _ instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by rw [sum.fintype, fintype.of_equiv_card]; simp lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using surjective_comp e.surjective (this.1 (injective_comp e.symm.injective hinj)), λ hsurj, by simpa [function.comp] using injective_comp e.injective (this.2 (surjective_comp e.symm.surjective hsurj))⟩ instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) instance pi.fintype {α : Type*} {β : α → Type*} [fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) := @fintype.of_equiv _ _ ⟨univ.pi $ λa:α, @univ (β a) _, λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩ ⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩ @[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) := by letI f' : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _ @[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [∀ a, fintype (β a)] [decidable α] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [fintype α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) := prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩) section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := by rw [length_cons, nat.fact_succ]; simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul] lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext.2 $ by simp [mem_perms_of_list_iff,mem_of_perm hab])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨injective_of_left_inverse (right_inverse_bij_inv _), surjective_of_has_right_inverse ⟨f, left_inverse_bij_inv _⟩⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, not_le_of_gt (nat.lt_succ_self (s.sum id)) $ @finset.single_le_sum _ _ _ id _ _ (λ _ _, nat.zero_le _) _ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
b01c73bf04d746c783ebe0c5dc548bf73aba329a
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/l1_space.lean
cf57f4c0c0005eb299894ac8a55b1f3e5fddf065
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
28,706
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.ae_eq_fun /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `f` is called `integrable` if `(∫⁻ a, nnnorm (f a)) < ⊤` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space namespace measure_theory open set filter topological_space ennreal emetric universes u v w variables {α : Type u} [measure_space α] variables {β : Type v} [normed_group β] {γ : Type w} [normed_group γ] /-- A function is `integrable` if the integral of its pointwise norm is less than infinity. -/ def integrable (f : α → β) : Prop := (∫⁻ a, nnnorm (f a)) < ⊤ lemma integrable_iff_norm (f : α → β) : integrable f ↔ (∫⁻ a, ennreal.of_real ∥f a∥) < ⊤ := by simp only [integrable, of_real_norm_eq_coe_nnnorm] lemma integrable_iff_edist (f : α → β) : integrable f ↔ (∫⁻ a, edist (f a) 0) < ⊤ := have eq : (λa, edist (f a) 0) = (λa, (nnnorm(f a) : ennreal)), by { funext, rw edist_eq_coe_nnnorm }, iff.intro (by { rw eq, exact λh, h }) $ by { rw eq, exact λh, h } lemma integrable_iff_of_real {f : α → ℝ} (h : ∀ₘ a, 0 ≤ f a) : integrable f ↔ (∫⁻ a, ennreal.of_real (f a)) < ⊤ := have lintegral_eq : (∫⁻ a, ennreal.of_real ∥f a∥) = (∫⁻ a, ennreal.of_real (f a)) := begin apply lintegral_congr_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg], exact h end, by rw [integrable_iff_norm, lintegral_eq] lemma integrable_of_ae_eq {f g : α → β} (hf : integrable f) (h : ∀ₘ a, f a = g a) : integrable g := begin simp only [integrable] at *, have : (∫⁻ (a : α), ↑(nnnorm (f a))) = (∫⁻ (a : α), ↑(nnnorm (g a))), { apply lintegral_congr_ae, filter_upwards [h], assume a, simp only [mem_set_of_eq], assume h, rw h }, rwa ← this end lemma integrable_congr_ae {f g : α → β} (h : ∀ₘ a, f a = g a) : integrable f ↔ integrable g := iff.intro (λhf, integrable_of_ae_eq hf h) (λhg, integrable_of_ae_eq hg (all_ae_eq_symm h)) lemma integrable_of_le_ae {f : α → β} {g : α → γ} (h : ∀ₘ a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥f a∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥g a∥) : lintegral_le_lintegral_ae (by { filter_upwards [h], assume a h, exact of_real_le_of_real h }) ... < ⊤ : hg end lemma integrable_of_le {f : α → β} {g : α → γ} (h : ∀a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := integrable_of_le_ae (all_ae_of_all h) hg lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : (∫⁻ a, nnnorm (f a)) = ∫⁻ a, edist (f a) 0 := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : (∫⁻ a, ennreal.of_real ∥f a∥) = ∫⁻ a, edist (f a) 0 := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g h : α → β} (hf : measurable f) (hg : measurable g) (hh : measurable h) : (∫⁻ a, edist (f a) (g a)) ≤ (∫⁻ a, edist (f a) (h a)) + ∫⁻ a, edist (g a) (h a) := begin rw ← lintegral_add (hf.edist hh) (hg.edist hh), apply lintegral_mono, assume a, have := edist_triangle (f a) (h a) (g a), convert this, rw edist_comm (h a) (g a), end lemma lintegral_edist_lt_top [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫⁻ a, edist (f a) (g a)) < ⊤ := lt_of_le_of_lt (lintegral_edist_triangle hfm hgm (measurable_const : measurable (λa, (0 : β)))) (ennreal.add_lt_top.2 $ by { split; rw ← integrable_iff_edist; assumption }) lemma lintegral_nnnorm_zero : (∫⁻ a : α, nnnorm (0 : β)) = 0 := by simp variables (α β) @[simp] lemma integrable_zero : integrable (λa:α, (0:β)) := by simp [integrable] variables {α β} lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : (∫⁻ a, nnnorm (f a) + nnnorm (g a)) = (∫⁻ a, nnnorm (f a)) + ∫⁻ a, nnnorm (g a) := lintegral_add hf.ennnorm hg.ennnorm lemma integrable.add [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a + g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f + g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (g a)) : lintegral_mono (assume a, by { simp only [← coe_add, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : lintegral_nnnorm_add hfm hgm ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable_finset_sum {ι} [measurable_space β] [borel_space β] [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : integrable (λ a, s.sum (λ i, f i a)) := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], refine (hfi _).add (hfm _) (s.measurable_sum hfm) ih } end lemma lintegral_nnnorm_neg {f : α → β} : (∫⁻ (a : α), ↑(nnnorm ((-f) a))) = ∫⁻ (a : α), ↑(nnnorm ((f) a)) := by simp only [pi.neg_apply, nnnorm_neg] lemma integrable.neg {f : α → β} : integrable f → integrable (λa, -f a) := assume hfi, calc _ = _ : lintegral_nnnorm_neg ... < ⊤ : hfi @[simp] lemma integrable_neg_iff (f : α → β) : integrable (λa, -f a) ↔ integrable f := begin split, { assume h, simpa only [_root_.neg_neg] using h.neg }, exact integrable.neg end lemma integrable.sub [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a - g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f - g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (-g a)) : lintegral_mono (assume a, by { simp only [← coe_add, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hfm hgm } ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable.norm {f : α → β} (hfi : integrable f) : integrable (λa, ∥f a∥) := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rwa [integrable, eq] } lemma integrable_norm_iff (f : α → β) : integrable (λa, ∥f a∥) ↔ integrable f := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rw [integrable, integrable, eq] } lemma integrable_of_integrable_bound {f : α → β} {bound : α → ℝ} (h : integrable bound) (h_bound : ∀ₘ a, ∥f a∥ ≤ bound a) : integrable f := have h₁ : ∀ₘ a, (nnnorm (f a) : ennreal) ≤ ennreal.of_real (bound a), begin filter_upwards [h_bound], simp only [mem_set_of_eq], assume a h, calc (nnnorm (f a) : ennreal) = ennreal.of_real (∥f a∥) : by rw of_real_norm_eq_coe_nnnorm ... ≤ ennreal.of_real (bound a) : ennreal.of_real_le_of_real h end, calc (∫⁻ a, nnnorm (f a)) ≤ (∫⁻ a, ennreal.of_real (bound a)) : by { apply lintegral_le_lintegral_ae, exact h₁ } ... ≤ (∫⁻ a, ennreal.of_real ∥bound a∥) : lintegral_mono $ by { assume a, apply ennreal.of_real_le_of_real, exact le_max_left (bound a) (-bound a) } ... < ⊤ : by { rwa [integrable_iff_norm] at h } section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, by filter_upwards [h n] λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ₘ a, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ₘ a, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := by filter_upwards [h] λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ₘ a, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← all_ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' at_top_ne_bot tendsto_norm (F_le_bound) end lemma integrable_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : integrable f := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is integrable -/ begin rw integrable_iff_norm, calc (∫⁻ a, (ennreal.of_real ∥f a∥)) ≤ ∫⁻ a, ennreal.of_real (bound a) : lintegral_le_lintegral_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ⊤ : begin rw ← integrable_iff_of_real, { exact bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h, end end lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β] [borel_space β] [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add' h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin suffices h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 $ ennreal.of_real 0), { rwa ennreal.of_real_zero at h }, filter_upwards [h_lim], assume a h, refine tendsto.comp (continuous.tendsto continuous_of_real _) _, rw ← tendsto_iff_norm_tendsto_zero, exact h end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 (∫⁻ (a:α), 0)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is measurable for all `n` { exact λn, measurable_of_real.comp ((F_measurable n).sub f_measurable).norm }, -- Show `2 * bound` is integrable { rw integrable_iff_of_real at bound_integrable, { calc (∫⁻ a, b a) = 2 * (∫⁻ a, ennreal.of_real (bound a)) : by { rw lintegral_const_mul', exact coe_ne_top } ... < ⊤ : mul_lt_top (coe_lt_top) bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, max (f a) 0) := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥max (f a) 0∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥f a∥) : lintegral_mono begin assume a, apply of_real_le_of_real, simp only [real.norm_eq_abs], calc abs (max (f a) 0) = max (f a) 0 : by { rw abs_of_nonneg, apply le_max_right } ... ≤ abs (f a) : max_le (le_abs_self _) (abs_nonneg _) end ... < ⊤ : hf end lemma integrable.min_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, min (f a) 0) := begin have : (λa, min (f a) 0) = (λa, - max (-f a) 0), { funext, rw [min_eq_neg_max_neg_neg, neg_zero] }, rw this, exact (integrable.max_zero hf.neg).neg, end end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul (c : 𝕜) {f : α → β} : integrable f → integrable (λa, c • f a) := begin simp only [integrable], assume hfi, calc (∫⁻ (a : α), nnnorm ((c • f) a)) = (∫⁻ (a : α), (nnnorm c) * nnnorm (f a)) : begin apply lintegral_congr_ae, filter_upwards [], assume a, simp only [nnnorm_smul, set.mem_set_of_eq, pi.smul_apply, ennreal.coe_mul] end ... < ⊤ : begin rw lintegral_const_mul', apply mul_lt_top, { exact coe_lt_top }, { exact hfi }, { simp only [ennreal.coe_ne_top, ne.def, not_false_iff] } end end lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (λa, c • f a) ↔ integrable f := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact integrable.smul _ end end normed_space variables [second_countable_topology β] namespace ae_eq_fun variable [measurable_space β] section variable [opens_measurable_space β] /-- An almost everywhere equal function is `integrable` if it has a finite distance to the origin. Should mean the same thing as the predicate `integrable` over functions. -/ def integrable (f : α →ₘ β) : Prop := f ∈ ball (0 : α →ₘ β) ⊤ lemma integrable_mk {f : α → β} (hf : measurable f) : (integrable (mk f hf)) ↔ measure_theory.integrable f := by simp [integrable, zero_def, edist_mk_mk', measure_theory.integrable, nndist_eq_nnnorm] lemma integrable_to_fun (f : α →ₘ β) : integrable f ↔ (measure_theory.integrable f.to_fun) := by conv_lhs { rw [self_eq_mk f, integrable_mk] } local attribute [simp] integrable_mk lemma integrable_zero : integrable (0 : α →ₘ β) := mem_ball_self coe_lt_top end section variable [borel_space β] lemma integrable.add : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f + g) := begin rintros ⟨f, hf⟩ ⟨g, hg⟩, simp only [mem_ball, zero_def, mk_add_mk, integrable_mk, quot_mk_eq_mk], assume hfi hgi, exact hfi.add hf hg hgi end lemma integrable.neg : ∀ {f : α →ₘ β}, integrable f → integrable (-f) := begin rintros ⟨f, hfm⟩ hfi, exact (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg end lemma integrable.sub : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f - g) := begin rintros ⟨f, hfm⟩ ⟨g, hgm⟩, simp only [quot_mk_eq_mk, integrable_mk, mk_sub_mk], exact λ hfi hgi, hfi.sub hfm hgm hgi end protected lemma is_add_subgroup : is_add_subgroup (ball (0 : α →ₘ β) ⊤) := { zero_mem := integrable_zero, add_mem := λ _ _, integrable.add, neg_mem := λ _, integrable.neg } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul : ∀ {c : 𝕜} {f : α →ₘ β}, integrable f → integrable (c • f) := begin rintros c ⟨f, hfm⟩, simp only [quot_mk_eq_mk, integrable_mk, smul_mk], exact λ hfi, hfi.smul c end end normed_space end end ae_eq_fun section variables (α β) [measurable_space β] [opens_measurable_space β] /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 : Type (max u v) := subtype (@ae_eq_fun.integrable α _ β _ _ _ _) infixr ` →₁ `:25 := l1 end namespace l1 open ae_eq_fun local attribute [instance] ae_eq_fun.is_add_subgroup variables [measurable_space β] section variable [opens_measurable_space β] instance : has_coe (α →₁ β) (α →ₘ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (l1.eq) (congr_arg coe) /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →₁ β) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ instance : metric_space (α →₁ β) := metric_space_emetric_ball 0 ⊤ end variable [borel_space β] instance : add_comm_group (α →₁ β) := subtype.add_comm_group instance : inhabited (α →₁ β) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ β) : α →ₘ β) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ β) : ((f + g : α →₁ β) : α →ₘ β) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ β) : ((-f : α →₁ β) : α →ₘ β) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ β) : ((f - g : α →₁ β) : α →ₘ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ β) : edist f g = edist (f : α →ₘ β) (g : α →ₘ β) := rfl lemma dist_eq (f g : α →₁ β) : dist f g = ennreal.to_real (edist (f : α →ₘ β) (g : α →ₘ β)) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ instance : has_norm (α →₁ β) := ⟨λ f, dist f 0⟩ lemma norm_eq (f : α →₁ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl instance : normed_group (α →₁ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add], rw edist_eq_add_add } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : has_scalar 𝕜 (α →₁ β) := ⟨λ x f, ⟨x • (f : α →ₘ β), ae_eq_fun.integrable.smul f.2⟩⟩ @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ β) : ((c • f : α →₁ β) : α →ₘ β) = c • (f : α →ₘ β) := rfl instance : semimodule 𝕜 (α →₁ β) := { one_smul := λf, l1.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, l1.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, l1.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, l1.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, l1.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, l1.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } instance : module 𝕜 (α →₁ β) := { .. l1.semimodule } instance : vector_space 𝕜 (α →₁ β) := { .. l1.semimodule } instance : normed_space 𝕜 (α →₁ β) := ⟨ begin rintros x ⟨f, hf⟩, show ennreal.to_real (edist (x • f) 0) ≤ ∥x∥ * ennreal.to_real (edist f 0), rw [edist_smul, to_real_of_real_mul], exact norm_nonneg _ end ⟩ end normed_space section of_fun /-- Construct the equivalence class `[f]` of a measurable and integrable function `f`. -/ def of_fun (f : α → β) (hfm : measurable f) (hfi : integrable f) : (α →₁ β) := ⟨mk f hfm, by { rw integrable_mk, exact hfi }⟩ lemma of_fun_eq_mk (f : α → β) (hfm hfi) : (of_fun f hfm hfi : α →ₘ β) = mk f hfm := rfl lemma of_fun_eq_of_fun (f g : α → β) (hfm hfi hgm hgi) : of_fun f hfm hfi = of_fun g hgm hgi ↔ ∀ₘ a, f a = g a := by { rw ← l1.eq_iff, simp only [of_fun_eq_mk, mk_eq_mk] } lemma of_fun_zero : of_fun (λa:α, (0:β)) (@measurable_const _ _ _ _ (0:β)) (integrable_zero α β) = 0 := rfl lemma of_fun_add (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a + g a) (measurable.add hfm hgm) (integrable.add hfm hfi hgm hgi) = of_fun f hfm hfi + of_fun g hgm hgi := rfl lemma of_fun_neg (f : α → β) (hfm hfi) : of_fun (λa, - f a) (measurable.neg hfm) (integrable.neg hfi) = - of_fun f hfm hfi := rfl lemma of_fun_sub (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a - g a) (measurable.sub hfm hgm) (integrable.sub hfm hfi hgm hgi) = of_fun f hfm hfi - of_fun g hgm hgi := rfl lemma norm_of_fun (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl lemma norm_of_fun_eq_lintegral_norm (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := by { rw [norm_of_fun, lintegral_norm_eq_lintegral_edist] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_fun_smul (f : α → β) (hfm : measurable f) (hfi : integrable f) (k : 𝕜) : of_fun (λa, k • f a) (hfm.const_smul _) (hfi.smul _) = k • of_fun f hfm hfi := rfl end of_fun section to_fun /-- Find a representative of an `L¹` function [f] -/ @[reducible] protected def to_fun (f : α →₁ β) : α → β := (f : α →ₘ β).to_fun protected lemma measurable (f : α →₁ β) : measurable f.to_fun := f.1.measurable protected lemma integrable (f : α →₁ β) : integrable f.to_fun := by { rw [l1.to_fun, ← integrable_to_fun], exact f.2 } lemma of_fun_to_fun (f : α →₁ β) : of_fun (f.to_fun) f.measurable f.integrable = f := begin rcases f with ⟨f, hfi⟩, rw [of_fun, subtype.mk_eq_mk], exact (self_eq_mk f).symm end lemma mk_to_fun (f : α →₁ β) : mk (f.to_fun) f.measurable = f := by { rw ← of_fun_eq_mk, rw l1.eq_iff, exact of_fun_to_fun f } lemma to_fun_of_fun (f : α → β) (hfm hfi) : ∀ₘ a, (of_fun f hfm hfi).to_fun a = f a := (all_ae_mk_to_fun f hfm).mono $ assume a, id variables (α β) lemma zero_to_fun : ∀ₘ a, (0 : α →₁ β).to_fun a = 0 := ae_eq_fun.zero_to_fun variables {α β} lemma add_to_fun (f g : α →₁ β) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a := ae_eq_fun.add_to_fun _ _ lemma neg_to_fun (f : α →₁ β) : ∀ₘ a, (-f).to_fun a = -f.to_fun a := ae_eq_fun.neg_to_fun _ lemma sub_to_fun (f g : α →₁ β) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a := ae_eq_fun.sub_to_fun _ _ lemma dist_to_fun (f g : α →₁ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_fun x) (g.to_fun x)) := by { simp only [dist_eq, edist_to_fun] } lemma norm_eq_nnnorm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, nnnorm (f.to_fun a)) := by { rw [lintegral_nnnorm_eq_lintegral_edist, ← edist_zero_to_fun], refl } lemma norm_eq_norm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f.to_fun a∥) := by { rw norm_eq_nnnorm_to_fun, congr, funext, rw of_real_norm_eq_coe_nnnorm } lemma lintegral_edist_to_fun_lt_top (f g : α →₁ β) : (∫⁻ a, edist (f.to_fun a) (g.to_fun a)) < ⊤ := begin apply lintegral_edist_lt_top, exact f.measurable, exact f.integrable, exact g.measurable, exact g.integrable end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_fun (c : 𝕜) (f : α →₁ β) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a := ae_eq_fun.smul_to_fun _ _ end to_fun section pos_part /-- Positive part of a function in `L¹` space. -/ def pos_part (f : α →₁ ℝ) : α →₁ ℝ := ⟨ ae_eq_fun.pos_part f, begin rw [ae_eq_fun.integrable_to_fun, integrable_congr_ae (pos_part_to_fun _)], exact integrable.max_zero f.integrable end ⟩ /-- Negative part of a function in `L¹` space. -/ def neg_part (f : α →₁ ℝ) : α →₁ ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ ℝ) : (f.pos_part : α →ₘ ℝ) = (f : α →ₘ ℝ).pos_part := rfl lemma pos_part_to_fun (f : α →₁ ℝ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) 0 := ae_eq_fun.pos_part_to_fun _ lemma neg_part_to_fun_eq_max (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = max (- f.to_fun a) 0 := begin rw neg_part, filter_upwards [pos_part_to_fun (-f), neg_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] end lemma neg_part_to_fun_eq_min (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = - min (f.to_fun a) 0 := begin filter_upwards [neg_part_to_fun_eq_max f], simp only [mem_set_of_eq], assume a h, rw [h, min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], end lemma norm_le_norm_of_ae_le {f g : α →₁ β} (h : ∀ₘ a, ∥f.to_fun a∥ ≤ ∥g.to_fun a∥) : ∥f∥ ≤ ∥g∥ := begin simp only [l1.norm_eq_norm_to_fun], rw to_real_le_to_real, { apply lintegral_le_lintegral_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, exact of_real_le_of_real h }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact f.integrable }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact g.integrable } end lemma continuous_pos_part : continuous $ λf : α →₁ ℝ, pos_part f := begin simp only [metric.continuous_iff], assume g ε hε, use ε, use hε, simp only [dist_eq_norm], assume f hfg, refine lt_of_le_of_lt (norm_le_norm_of_ae_le _) hfg, filter_upwards [l1.sub_to_fun f g, l1.sub_to_fun (pos_part f) (pos_part g), pos_part_to_fun f, pos_part_to_fun g], simp only [mem_set_of_eq], assume a h₁ h₂ h₃ h₄, simp only [real.norm_eq_abs, h₁, h₂, h₃, h₄], exact abs_max_sub_max_le_abs _ _ _ end lemma continuous_neg_part : continuous $ λf : α →₁ ℝ, neg_part f := have eq : (λf : α →₁ ℝ, neg_part f) = (λf : α →₁ ℝ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part /- TODO: l1 is a complete space -/ end l1 end measure_theory
e412c0114de40456346a3edc6ad229e6b047690a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/derive.lean
f1ea5bdb53d3062949f3c40919fd590d5dceedb7
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
371
lean
@[derive has_reflect] inductive foo (α β : Type*) | bar : ℕ → foo | baz : foo → α → foo #check foo.has_reflect -- indexed families @[derive [decidable_eq, has_sizeof]] inductive {u} foo' (α β : Type u) (n : nat) : nat → Type u | bar : ℕ → foo' 0 | baz (n : nat) : foo' n → α → foo' (nat.succ n) #check foo'.decidable_eq #check foo'.has_sizeof
7350b8d876249f9f2af6084e4633e44c104da574
f3be49eddff7edf577d3d3666e314d995f7a6357
/TBA.lean
2d170c77c722551f2d12274fc93416813d40eb64
[]
no_license
IPDSnelting/tba-2021
8b930bcd2f4aae44a2ddc86e72b77f84e6d46e82
b6390e55b768423d3266969e81d19290129c5914
refs/heads/master
1,686,754,693,583
1,625,135,602,000
1,625,136,365,000
355,124,341
50
7
null
1,625,133,762,000
1,617,699,824,000
Lean
UTF-8
Lean
false
false
95
lean
import Leanpkg -- should print 'nightly-2021-04-06' or later #eval Leanpkg.leanVersionString
2dc08a4ae24a52187a2fc3965ae7a9b701ea867f
bb31430994044506fa42fd667e2d556327e18dfe
/src/field_theory/minpoly/gcd_monoid.lean
81719806b40658b6b8426cd11ce80a17c86ed087
[ "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
7,247
lean
/- Copyright (c) 2019 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import data.polynomial.field_division import ring_theory.adjoin_root import field_theory.minpoly.field import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials over a GCD monoid This file specializes the theory of minpoly to the case of an algebra over a GCD monoid. ## Main results * `gcd_domain_eq_field_fractions`: For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. * `gcd_domain_dvd` : For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. * `gcd_domain_unique` : The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. -/ open_locale classical polynomial open polynomial set function minpoly namespace minpoly variables {R S : Type*} [comm_ring R] [comm_ring S] [is_domain R] [is_domain S] [algebra R S] section gcd_domain variables (K L : Type*) [normalized_gcd_monoid R] [field K] [algebra R K] [is_fraction_ring R K] [field L] [algebra S L] [algebra K L] [algebra R L] [is_scalar_tower R K L] [is_scalar_tower R S L] {s : S} (hs : is_integral R s) include hs /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. See `minpoly.gcd_domain_eq_field_fractions'` if `S` is already a `K`-algebra. -/ lemma gcd_domain_eq_field_fractions : minpoly K (algebra_map S L s) = (minpoly R s).map (algebra_map R K) := begin refine (eq_of_irreducible_of_monic _ _ _).symm, { exact (polynomial.is_primitive.irreducible_iff_irreducible_map_fraction_map (polynomial.monic.is_primitive (monic hs))).1 (irreducible hs) }, { rw [aeval_map_algebra_map, aeval_algebra_map_apply, aeval, map_zero] }, { exact (monic hs).map _ } end /-- For GCD domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. Compared to `minpoly.gcd_domain_eq_field_fractions`, this version is useful if the element is in a ring that is already a `K`-algebra. -/ lemma gcd_domain_eq_field_fractions' [algebra K S] [is_scalar_tower R K S] : minpoly K s = (minpoly R s).map (algebra_map R K) := begin let L := fraction_ring S, rw [← gcd_domain_eq_field_fractions K L hs], refine minpoly.eq_of_algebra_map_eq (is_fraction_ring.injective S L) (is_integral_of_is_scalar_tower hs) rfl end variable [no_zero_smul_divisors R S] /-- For GCD domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. See also `minpoly.dvd` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma gcd_domain_dvd {P : R[X]} (hP : P ≠ 0) (hroot : polynomial.aeval s P = 0) : minpoly R s ∣ P := begin let K := fraction_ring R, let L := fraction_ring S, let P₁ := P.prim_part, suffices : minpoly R s ∣ P₁, { exact dvd_trans this (prim_part_dvd _) }, apply (is_primitive.dvd_iff_fraction_map_dvd_fraction_map K (monic hs).is_primitive P.is_primitive_prim_part).2, let y := algebra_map S L s, have hy : is_integral R y := hs.algebra_map, rw [← gcd_domain_eq_field_fractions K L hs], refine dvd _ _ _, rw [aeval_map_algebra_map, aeval_algebra_map_apply, aeval_prim_part_eq_zero hP hroot, map_zero] end /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. See also `minpoly.degree_le_of_ne_zero` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma gcd_domain_degree_le_of_ne_zero {p : R[X]} (hp0 : p ≠ 0) (hp : polynomial.aeval s p = 0) : degree (minpoly R s) ≤ degree p := begin rw [degree_eq_nat_degree (minpoly.ne_zero hs), degree_eq_nat_degree hp0], norm_cast, exact nat_degree_le_of_dvd (gcd_domain_dvd hs hp0 hp) hp0 end omit hs /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. See also `minpoly.unique` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma gcd_domain_unique {P : R[X]} (hmo : P.monic) (hP : polynomial.aeval s P = 0) (Pmin : ∀ Q : R[X], Q.monic → polynomial.aeval s Q = 0 → degree P ≤ degree Q) : P = minpoly R s := begin have hs : is_integral R s := ⟨P, hmo, hP⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := gcd_domain_degree_le_of_ne_zero hs hnz (by simp [hP]), contrapose! this, refine degree_sub_lt _ (ne_zero hs) _, { exact le_antisymm (min R s hmo hP) (Pmin (minpoly R s) (monic hs) (aeval R s)) }, { rw [(monic hs).leading_coeff, hmo.leading_coeff] } end end gcd_domain section adjoin_root noncomputable theory open algebra polynomial adjoin_root variables {R} {x : S} [normalized_gcd_monoid R] [no_zero_smul_divisors R S] lemma to_adjoin.injective (hx : is_integral R x) : function.injective (minpoly.to_adjoin R x) := begin refine (injective_iff_map_eq_zero _).2 (λ P₁ hP₁, _), obtain ⟨P, hP⟩ := mk_surjective (minpoly.monic hx) P₁, by_cases hPzero : P = 0, { simpa [hPzero] using hP.symm }, have hPcont : P.content ≠ 0 := λ h, hPzero (content_eq_zero_iff.1 h), rw [← hP, minpoly.to_adjoin_apply', lift_hom_mk, ← subalgebra.coe_eq_zero, aeval_subalgebra_coe, set_like.coe_mk, P.eq_C_content_mul_prim_part, aeval_mul, aeval_C] at hP₁, replace hP₁ := eq_zero_of_ne_zero_of_mul_left_eq_zero ((map_ne_zero_iff _ (no_zero_smul_divisors.algebra_map_injective R S)).2 hPcont) hP₁, obtain ⟨Q, hQ⟩ := minpoly.gcd_domain_dvd hx P.is_primitive_prim_part.ne_zero hP₁, rw [P.eq_C_content_mul_prim_part] at hP, simpa [hQ] using hP.symm end /-- The algebra isomorphism `adjoin_root (minpoly R x) ≃ₐ[R] adjoin R x` -/ @[simps] def equiv_adjoin (hx : is_integral R x) : adjoin_root (minpoly R x) ≃ₐ[R] adjoin R ({x} : set S) := alg_equiv.of_bijective (minpoly.to_adjoin R x) ⟨minpoly.to_adjoin.injective hx, minpoly.to_adjoin.surjective R x⟩ /-- The `power_basis` of `adjoin R {x}` given by `x`. See `algebra.adjoin.power_basis` for a version over a field. -/ @[simps] def _root_.algebra.adjoin.power_basis' (hx : _root_.is_integral R x) : _root_.power_basis R (algebra.adjoin R ({x} : set S)) := power_basis.map (adjoin_root.power_basis' (minpoly.monic hx)) (minpoly.equiv_adjoin hx) /-- The power basis given by `x` if `B.gen ∈ adjoin R {x}`. -/ @[simps] noncomputable def _root_.power_basis.of_gen_mem_adjoin' (B : _root_.power_basis R S) (hint : is_integral R x) (hx : B.gen ∈ adjoin R ({x} : set S)) : _root_.power_basis R S := (algebra.adjoin.power_basis' hint).map $ (subalgebra.equiv_of_eq _ _ $ power_basis.adjoin_eq_top_of_gen_mem_adjoin hx).trans subalgebra.top_equiv end adjoin_root end minpoly
fa4bb7d3ac9c04a909a35dea2835e4f093a530ff
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/regular/basic.lean
a4c3aaa361cc930a6c0635f68e422dbefff2a966
[ "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
13,669
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import algebra.group.commute import algebra.order.monoid.lemmas import algebra.group_with_zero.basic /-! # Regular elements > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/758 > Any changes to this file require a corresponding PR to mathlib4. We introduce left-regular, right-regular and regular elements, along with their `to_additive` analogues add-left-regular, add-right-regular and add-regular elements. By definition, a regular element in a commutative ring is a non-zero divisor. Lemma `is_regular_of_ne_zero` implies that every non-zero element of an integral domain is regular. Since it assumes that the ring is a `cancel_monoid_with_zero` it applies also, for instance, to `ℕ`. The lemmas in Section `mul_zero_class` show that the `0` element is (left/right-)regular if and only if the `mul_zero_class` is trivial. This is useful when figuring out stopping conditions for regular sequences: if `0` is ever an element of a regular sequence, then we can extend the sequence by adding one further `0`. The final goal is to develop part of the API to prove, eventually, results about non-zero-divisors. -/ variables {R : Type*} section has_mul variables [has_mul R] /-- A left-regular element is an element `c` such that multiplication on the left by `c` is injective. -/ @[to_additive "An add-left-regular element is an element `c` such that addition on the left by `c` is injective. -/ "] def is_left_regular (c : R) := ((*) c).injective /-- A right-regular element is an element `c` such that multiplication on the right by `c` is injective. -/ @[to_additive "An add-right-regular element is an element `c` such that addition on the right by `c` is injective."] def is_right_regular (c : R) := (* c).injective /-- An add-regular element is an element `c` such that addition by `c` both on the left and on the right is injective. -/ structure is_add_regular {R : Type*} [has_add R] (c : R) : Prop := (left : is_add_left_regular c) (right : is_add_right_regular c) /-- A regular element is an element `c` such that multiplication by `c` both on the left and on the right is injective. -/ structure is_regular (c : R) : Prop := (left : is_left_regular c) (right : is_right_regular c) attribute [to_additive] is_regular @[to_additive] protected lemma mul_le_cancellable.is_left_regular [partial_order R] {a : R} (ha : mul_le_cancellable a) : is_left_regular a := ha.injective lemma is_left_regular.right_of_commute {a : R} (ca : ∀ b, commute a b) (h : is_left_regular a) : is_right_regular a := λ x y xy, h $ (ca x).trans $ xy.trans $ (ca y).symm lemma commute.is_regular_iff {a : R} (ca : ∀ b, commute a b) : is_regular a ↔ is_left_regular a := ⟨λ h, h.left, λ h, ⟨h, h.right_of_commute ca⟩⟩ end has_mul section semigroup variables [semigroup R] {a b : R} /-- In a semigroup, the product of left-regular elements is left-regular. -/ @[to_additive "In an additive semigroup, the sum of add-left-regular elements is add-left.regular."] lemma is_left_regular.mul (lra : is_left_regular a) (lrb : is_left_regular b) : is_left_regular (a * b) := show function.injective ((*) (a * b)), from (comp_mul_left a b) ▸ lra.comp lrb /-- In a semigroup, the product of right-regular elements is right-regular. -/ @[to_additive "In an additive semigroup, the sum of add-right-regular elements is add-right-regular."] lemma is_right_regular.mul (rra : is_right_regular a) (rrb : is_right_regular b) : is_right_regular (a * b) := show function.injective (* (a * b)), from (comp_mul_right b a) ▸ rrb.comp rra /-- If an element `b` becomes left-regular after multiplying it on the left by a left-regular element, then `b` is left-regular. -/ @[to_additive "If an element `b` becomes add-left-regular after adding to it on the left a add-left-regular element, then `b` is add-left-regular."] lemma is_left_regular.of_mul (ab : is_left_regular (a * b)) : is_left_regular b := function.injective.of_comp (by rwa comp_mul_left a b) /-- An element is left-regular if and only if multiplying it on the left by a left-regular element is left-regular. -/ @[simp, to_additive "An element is add-left-regular if and only if adding to it on the left a add-left-regular element is add-left-regular."] lemma mul_is_left_regular_iff (b : R) (ha : is_left_regular a) : is_left_regular (a * b) ↔ is_left_regular b := ⟨λ ab, is_left_regular.of_mul ab, λ ab, is_left_regular.mul ha ab⟩ /-- If an element `b` becomes right-regular after multiplying it on the right by a right-regular element, then `b` is right-regular. -/ @[to_additive "If an element `b` becomes add-right-regular after adding to it on the right a add-right-regular element, then `b` is add-right-regular."] lemma is_right_regular.of_mul (ab : is_right_regular (b * a)) : is_right_regular b := begin refine λ x y xy, ab (_ : x * (b * a) = y * (b * a)), rw [← mul_assoc, ← mul_assoc], exact congr_fun (congr_arg (*) xy) a, end /-- An element is right-regular if and only if multiplying it on the right with a right-regular element is right-regular. -/ @[simp, to_additive "An element is add-right-regular if and only if adding it on the right to a add-right-regular element is add-right-regular."] lemma mul_is_right_regular_iff (b : R) (ha : is_right_regular a) : is_right_regular (b * a) ↔ is_right_regular b := ⟨λ ab, is_right_regular.of_mul ab, λ ab, is_right_regular.mul ab ha⟩ /-- Two elements `a` and `b` are regular if and only if both products `a * b` and `b * a` are regular. -/ @[to_additive "Two elements `a` and `b` are add-regular if and only if both sums `a + b` and `b + a` are add-regular."] lemma is_regular_mul_and_mul_iff : is_regular (a * b) ∧ is_regular (b * a) ↔ is_regular a ∧ is_regular b := begin refine ⟨_, _⟩, { rintros ⟨ab, ba⟩, exact ⟨⟨is_left_regular.of_mul ba.left, is_right_regular.of_mul ab.right⟩, ⟨is_left_regular.of_mul ab.left, is_right_regular.of_mul ba.right⟩⟩ }, { rintros ⟨ha, hb⟩, exact ⟨⟨(mul_is_left_regular_iff _ ha.left).mpr hb.left, (mul_is_right_regular_iff _ hb.right).mpr ha.right⟩, ⟨(mul_is_left_regular_iff _ hb.left).mpr ha.left, (mul_is_right_regular_iff _ ha.right).mpr hb.right⟩⟩ } end /-- The "most used" implication of `mul_and_mul_iff`, with split hypotheses, instead of `∧`. -/ @[to_additive "The \"most used\" implication of `add_and_add_iff`, with split hypotheses, instead of `∧`."] lemma is_regular.and_of_mul_of_mul (ab : is_regular (a * b)) (ba : is_regular (b * a)) : is_regular a ∧ is_regular b := is_regular_mul_and_mul_iff.mp ⟨ab, ba⟩ end semigroup section mul_zero_class variables [mul_zero_class R] {a b : R} /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular.subsingleton (h : is_left_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (zero_mul a) (zero_mul b).symm⟩ /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular.subsingleton (h : is_right_regular (0 : R)) : subsingleton R := ⟨λ a b, h $ eq.trans (mul_zero a) (mul_zero b).symm⟩ /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular.subsingleton (h : is_regular (0 : R)) : subsingleton R := h.left.subsingleton /-- The element `0` is left-regular if and only if `R` is trivial. -/ lemma is_left_regular_zero_iff_subsingleton : is_left_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.subsingleton, λ H a b h, @subsingleton.elim _ H a b⟩ /-- In a non-trivial `mul_zero_class`, the `0` element is not left-regular. -/ lemma not_is_left_regular_zero_iff : ¬ is_left_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_left_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is right-regular if and only if `R` is trivial. -/ lemma is_right_regular_zero_iff_subsingleton : is_right_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.subsingleton, λ H a b h, @subsingleton.elim _ H a b⟩ /-- In a non-trivial `mul_zero_class`, the `0` element is not right-regular. -/ lemma not_is_right_regular_zero_iff : ¬ is_right_regular (0 : R) ↔ nontrivial R := begin rw [nontrivial_iff, not_iff_comm, is_right_regular_zero_iff_subsingleton, subsingleton_iff], push_neg, exact iff.rfl end /-- The element `0` is regular if and only if `R` is trivial. -/ lemma is_regular_iff_subsingleton : is_regular (0 : R) ↔ subsingleton R := ⟨λ h, h.left.subsingleton, λ h, ⟨is_left_regular_zero_iff_subsingleton.mpr h, is_right_regular_zero_iff_subsingleton.mpr h⟩⟩ /-- A left-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_left_regular.ne_zero [nontrivial R] (la : is_left_regular a) : a ≠ 0 := begin rintro rfl, rcases exists_pair_ne R with ⟨x, y, xy⟩, refine xy (la _), rw [zero_mul, zero_mul] end /-- A right-regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_right_regular.ne_zero [nontrivial R] (ra : is_right_regular a) : a ≠ 0 := begin rintro rfl, rcases exists_pair_ne R with ⟨x, y, xy⟩, refine xy (ra (_ : x * 0 = y * 0)), rw [mul_zero, mul_zero] end /-- A regular element of a `nontrivial` `mul_zero_class` is non-zero. -/ lemma is_regular.ne_zero [nontrivial R] (la : is_regular a) : a ≠ 0 := la.left.ne_zero /-- In a non-trivial ring, the element `0` is not left-regular -- with typeclasses. -/ lemma not_is_left_regular_zero [nR : nontrivial R] : ¬ is_left_regular (0 : R) := not_is_left_regular_zero_iff.mpr nR /-- In a non-trivial ring, the element `0` is not right-regular -- with typeclasses. -/ lemma not_is_right_regular_zero [nR : nontrivial R] : ¬ is_right_regular (0 : R) := not_is_right_regular_zero_iff.mpr nR /-- In a non-trivial ring, the element `0` is not regular -- with typeclasses. -/ lemma not_is_regular_zero [nontrivial R] : ¬ is_regular (0 : R) := λ h, is_regular.ne_zero h rfl end mul_zero_class section mul_one_class variable [mul_one_class R] /-- If multiplying by `1` on either side is the identity, `1` is regular. -/ @[to_additive "If adding `0` on either side is the identity, `0` is regular."] lemma is_regular_one : is_regular (1 : R) := ⟨λ a b ab, (one_mul a).symm.trans (eq.trans ab (one_mul b)), λ a b ab, (mul_one a).symm.trans (eq.trans ab (mul_one b))⟩ end mul_one_class section comm_semigroup variables [comm_semigroup R] {a b : R} /-- A product is regular if and only if the factors are. -/ @[to_additive "A sum is add-regular if and only if the summands are."] lemma is_regular_mul_iff : is_regular (a * b) ↔ is_regular a ∧ is_regular b := begin refine iff.trans _ is_regular_mul_and_mul_iff, refine ⟨λ ab, ⟨ab, by rwa mul_comm⟩, λ rab, rab.1⟩ end end comm_semigroup section monoid variables [monoid R] {a b : R} /-- An element admitting a left inverse is left-regular. -/ @[to_additive "An element admitting a left additive opposite is add-left-regular."] lemma is_left_regular_of_mul_eq_one (h : b * a = 1) : is_left_regular a := @is_left_regular.of_mul R _ _ _ (by { rw h, exact is_regular_one.left }) /-- An element admitting a right inverse is right-regular. -/ @[to_additive "An element admitting a right additive opposite is add-right-regular."] lemma is_right_regular_of_mul_eq_one (h : a * b = 1) : is_right_regular a := is_right_regular.of_mul (by { rw h, exact is_regular_one.right }) /-- If `R` is a monoid, an element in `Rˣ` is regular. -/ @[to_additive "If `R` is an additive monoid, an element in `add_units R` is add-regular."] lemma units.is_regular (a : Rˣ) : is_regular (a : R) := ⟨is_left_regular_of_mul_eq_one a.inv_mul, is_right_regular_of_mul_eq_one a.mul_inv⟩ /-- A unit in a monoid is regular. -/ @[to_additive "An additive unit in an additive monoid is add-regular."] lemma is_unit.is_regular (ua : is_unit a) : is_regular a := begin rcases ua with ⟨a, rfl⟩, exact units.is_regular a, end end monoid /-- Elements of a left cancel semigroup are left regular. -/ @[to_additive "Elements of an add left cancel semigroup are add-left-regular."] lemma is_left_regular_of_left_cancel_semigroup [left_cancel_semigroup R] (g : R) : is_left_regular g := mul_right_injective g /-- Elements of a right cancel semigroup are right regular. -/ @[to_additive "Elements of an add right cancel semigroup are add-right-regular"] lemma is_right_regular_of_right_cancel_semigroup [right_cancel_semigroup R] (g : R) : is_right_regular g := mul_left_injective g section cancel_monoid variables [cancel_monoid R] /-- Elements of a cancel monoid are regular. Cancel semigroups do not appear to exist. -/ @[to_additive "Elements of an add cancel monoid are regular. Add cancel semigroups do not appear to exist."] lemma is_regular_of_cancel_monoid (g : R) : is_regular g := ⟨mul_right_injective g, mul_left_injective g⟩ end cancel_monoid section cancel_monoid_with_zero variables [cancel_monoid_with_zero R] {a : R} /-- Non-zero elements of an integral domain are regular. -/ lemma is_regular_of_ne_zero (a0 : a ≠ 0) : is_regular a := ⟨λ b c, (mul_right_inj' a0).mp, λ b c, (mul_left_inj' a0).mp⟩ /-- In a non-trivial integral domain, an element is regular iff it is non-zero. -/ lemma is_regular_iff_ne_zero [nontrivial R] : is_regular a ↔ a ≠ 0 := ⟨is_regular.ne_zero, is_regular_of_ne_zero⟩ end cancel_monoid_with_zero
32a206472e6ae02f11d585d636674a9c8fe11665
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/order/nonneg.lean
ff1b7b90c367dcfde66510f98a9ff27a8b16c28b
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,048
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.order.sub import algebra.order.with_zero import algebra.archimedean import order.lattice_intervals import order.conditionally_complete_lattice /-! # The type of nonnegative elements This file defines instances and prove some properties about the nonnegative elements `{x : α // 0 ≤ x}` of an arbitrary type `α`. Currently we only state instances and states some `simp`/`norm_cast` lemmas. When `α` is `ℝ`, this will give us some properties about `ℝ≥0`. ## Main declarations * `{x : α // 0 ≤ x}` is a `canonically_linear_ordered_add_monoid` if `α` is a `linear_ordered_ring`. * `{x : α // 0 ≤ x}` is a `linear_ordered_comm_group_with_zero` if `α` is a `linear_ordered_field`. ## Implementation Notes Instead of `{x : α // 0 ≤ x}` we could also use `set.Ici (0 : α)`, which is definitionally equal. However, using the explicit subtype has a big advantage: when writing and element explicitly with a proof of nonnegativity as `⟨x, hx⟩`, the `hx` is expected to have type `0 ≤ x`. If we would use `Ici 0`, then the type is expected to be `x ∈ Ici 0`. Although these types are definitionally equal, this often confuses the elaborator. Similar problems arise when doing cases on an element. The disadvantage is that we have to duplicate some instances about `set.Ici` to this subtype. -/ open set variables {α : Type*} namespace nonneg instance order_bot [partial_order α] {a : α} : order_bot {x : α // a ≤ x} := set.Ici.order_bot instance no_top_order [partial_order α] [no_top_order α] {a : α} : no_top_order {x : α // a ≤ x} := set.Ici.no_top_order instance semilattice_inf_bot [semilattice_inf α] {a : α} : semilattice_inf_bot {x : α // a ≤ x} := set.Ici.semilattice_inf_bot instance densely_ordered [preorder α] [densely_ordered α] {a : α} : densely_ordered {x : α // a ≤ x} := show densely_ordered (Ici a), from set.densely_ordered /-- If `Sup ∅ ≤ a` then `{x : α // a ≤ x}` is a `conditionally_complete_linear_order_bot`. -/ @[reducible] protected noncomputable def conditionally_complete_linear_order_bot [conditionally_complete_linear_order α] {a : α} (h : Sup ∅ ≤ a) : conditionally_complete_linear_order_bot {x : α // a ≤ x} := { cSup_empty := (function.funext_iff.1 (@subset_Sup_def α (set.Ici a) _ ⟨⟨a, le_rfl⟩⟩) ∅).trans $ subtype.eq $ by { cases h.lt_or_eq with h2 h2, { simp [h2.not_le] }, simp [h2] }, ..nonneg.order_bot, .. @ord_connected_subset_conditionally_complete_linear_order α (set.Ici a) _ ⟨⟨a, le_rfl⟩⟩ _ } instance inhabited [preorder α] {a : α} : inhabited {x : α // a ≤ x} := ⟨⟨a, le_rfl⟩⟩ instance has_zero [has_zero α] [preorder α] : has_zero {x : α // 0 ≤ x} := ⟨⟨0, le_rfl⟩⟩ @[simp, norm_cast] protected lemma coe_zero [has_zero α] [preorder α] : ((0 : {x : α // 0 ≤ x}) : α) = 0 := rfl @[simp] lemma mk_eq_zero [has_zero α] [preorder α] {x : α} (hx : 0 ≤ x) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) = 0 ↔ x = 0 := subtype.ext_iff instance has_add [add_zero_class α] [preorder α] [covariant_class α α (+) (≤)] : has_add {x : α // 0 ≤ x} := ⟨λ x y, ⟨x + y, add_nonneg x.2 y.2⟩⟩ @[simp] lemma mk_add_mk [add_zero_class α] [preorder α] [covariant_class α α (+) (≤)] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) + ⟨y, hy⟩ = ⟨x + y, add_nonneg hx hy⟩ := rfl @[simp, norm_cast] protected lemma coe_add [add_zero_class α] [preorder α] [covariant_class α α (+) (≤)] (a b : {x : α // 0 ≤ x}) : ((a + b : {x : α // 0 ≤ x}) : α) = a + b := rfl instance ordered_add_comm_monoid [ordered_add_comm_monoid α] : ordered_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.ordered_add_comm_monoid (coe : {x : α // 0 ≤ x} → α) rfl (λ x y, rfl) instance linear_ordered_add_comm_monoid [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_add_comm_monoid (coe : {x : α // 0 ≤ x} → α) rfl (λ x y, rfl) instance ordered_cancel_add_comm_monoid [ordered_cancel_add_comm_monoid α] : ordered_cancel_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.ordered_cancel_add_comm_monoid (coe : {x : α // 0 ≤ x} → α) rfl (λ x y, rfl) instance linear_ordered_cancel_add_comm_monoid [linear_ordered_cancel_add_comm_monoid α] : linear_ordered_cancel_add_comm_monoid {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid (coe : {x : α // 0 ≤ x} → α) rfl (λ x y, rfl) /-- Coercion `{x : α // 0 ≤ x} → α` as a `add_monoid_hom`. -/ def coe_add_monoid_hom [ordered_add_comm_monoid α] : {x : α // 0 ≤ x} →+ α := ⟨coe, nonneg.coe_zero, nonneg.coe_add⟩ @[norm_cast] lemma nsmul_coe [ordered_add_comm_monoid α] (n : ℕ) (r : {x : α // 0 ≤ x}) : ↑(n • r) = n • (r : α) := nonneg.coe_add_monoid_hom.map_nsmul _ _ instance archimedean [ordered_add_comm_monoid α] [archimedean α] : archimedean {x : α // 0 ≤ x} := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x : α) (pos_y : (0 : α) < y) in ⟨n, show (x : α) ≤ (n • y : {x : α // 0 ≤ x}), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ instance has_one [ordered_semiring α] : has_one {x : α // 0 ≤ x} := { one := ⟨1, zero_le_one⟩ } @[simp, norm_cast] protected lemma coe_one [ordered_semiring α] : ((1 : {x : α // 0 ≤ x}) : α) = 1 := rfl @[simp] lemma mk_eq_one [ordered_semiring α] {x : α} (hx : 0 ≤ x) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) = 1 ↔ x = 1 := subtype.ext_iff instance has_mul [ordered_semiring α] : has_mul {x : α // 0 ≤ x} := { mul := λ x y, ⟨x * y, mul_nonneg x.2 y.2⟩ } @[simp, norm_cast] protected lemma coe_mul [ordered_semiring α] (a b : {x : α // 0 ≤ x}) : ((a * b : {x : α // 0 ≤ x}) : α) = a * b := rfl @[simp] lemma mk_mul_mk [ordered_semiring α] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) * ⟨y, hy⟩ = ⟨x * y, mul_nonneg hx hy⟩ := rfl instance ordered_semiring [ordered_semiring α] : ordered_semiring {x : α // 0 ≤ x} := subtype.coe_injective.ordered_semiring (coe : {x : α // 0 ≤ x} → α) rfl rfl (λ x y, rfl) (λ x y, rfl) instance ordered_comm_semiring [ordered_comm_semiring α] : ordered_comm_semiring {x : α // 0 ≤ x} := subtype.coe_injective.ordered_comm_semiring (coe : {x : α // 0 ≤ x} → α) rfl rfl (λ x y, rfl) (λ x y, rfl) instance nontrivial [linear_ordered_semiring α] : nontrivial {x : α // 0 ≤ x} := ⟨ ⟨0, 1, λ h, zero_ne_one (congr_arg subtype.val h)⟩ ⟩ instance linear_ordered_semiring [linear_ordered_semiring α] : linear_ordered_semiring {x : α // 0 ≤ x} := subtype.coe_injective.linear_ordered_semiring (coe : {x : α // 0 ≤ x} → α) rfl rfl (λ x y, rfl) (λ x y, rfl) instance linear_ordered_comm_monoid_with_zero [linear_ordered_comm_ring α] : linear_ordered_comm_monoid_with_zero {x : α // 0 ≤ x} := { mul_le_mul_left := λ a b h c, mul_le_mul_of_nonneg_left h c.2, ..nonneg.linear_ordered_semiring, ..nonneg.ordered_comm_semiring } /-- Coercion `{x : α // 0 ≤ x} → α` as a `ring_hom`. -/ def coe_ring_hom [ordered_semiring α] : {x : α // 0 ≤ x} →+* α := ⟨coe, nonneg.coe_one, nonneg.coe_mul, nonneg.coe_zero, nonneg.coe_add⟩ instance has_inv [linear_ordered_field α] : has_inv {x : α // 0 ≤ x} := { inv := λ x, ⟨x⁻¹, inv_nonneg.mpr x.2⟩ } @[simp, norm_cast] protected lemma coe_inv [linear_ordered_field α] (a : {x : α // 0 ≤ x}) : ((a⁻¹ : {x : α // 0 ≤ x}) : α) = a⁻¹ := rfl @[simp] lemma inv_mk [linear_ordered_field α] {x : α} (hx : 0 ≤ x) : (⟨x, hx⟩ : {x : α // 0 ≤ x})⁻¹ = ⟨x⁻¹, inv_nonneg.mpr hx⟩ := rfl instance linear_ordered_comm_group_with_zero [linear_ordered_field α] : linear_ordered_comm_group_with_zero {x : α // 0 ≤ x} := { inv_zero := by { ext, exact inv_zero }, mul_inv_cancel := by { intros a ha, ext, refine mul_inv_cancel (mt (λ h, _) ha), ext, exact h }, ..nonneg.nontrivial, ..nonneg.has_inv, ..nonneg.linear_ordered_comm_monoid_with_zero } instance has_div [linear_ordered_field α] : has_div {x : α // 0 ≤ x} := { div := λ x y, ⟨x / y, div_nonneg x.2 y.2⟩ } @[simp, norm_cast] protected lemma coe_div [linear_ordered_field α] (a b : {x : α // 0 ≤ x}) : ((a / b : {x : α // 0 ≤ x}) : α) = a / b := rfl @[simp] lemma mk_div_mk [linear_ordered_field α] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) / ⟨y, hy⟩ = ⟨x / y, div_nonneg hx hy⟩ := rfl instance canonically_ordered_add_monoid [ordered_ring α] : canonically_ordered_add_monoid {x : α // 0 ≤ x} := { le_iff_exists_add := λ ⟨a, ha⟩ ⟨b, hb⟩, by simpa only [mk_add_mk, subtype.exists, subtype.mk_eq_mk] using le_iff_exists_nonneg_add a b, ..nonneg.ordered_add_comm_monoid, ..nonneg.order_bot } instance canonically_ordered_comm_semiring [ordered_comm_ring α] [no_zero_divisors α] : canonically_ordered_comm_semiring {x : α // 0 ≤ x} := { eq_zero_or_eq_zero_of_mul_eq_zero := by { rintro ⟨a, ha⟩ ⟨b, hb⟩, simp }, ..nonneg.canonically_ordered_add_monoid, ..nonneg.ordered_comm_semiring } instance canonically_linear_ordered_add_monoid [linear_ordered_ring α] : canonically_linear_ordered_add_monoid {x : α // 0 ≤ x} := { ..subtype.linear_order _, ..nonneg.canonically_ordered_add_monoid } section linear_order variables [has_zero α] [linear_order α] /-- The function `a ↦ max a 0` of type `α → {x : α // 0 ≤ x}`. -/ def to_nonneg (a : α) : {x : α // 0 ≤ x} := ⟨max a 0, le_max_right _ _⟩ @[simp] lemma coe_to_nonneg {a : α} : (to_nonneg a : α) = max a 0 := rfl @[simp] lemma to_nonneg_of_nonneg {a : α} (h : 0 ≤ a) : to_nonneg a = ⟨a, h⟩ := by simp [to_nonneg, h] @[simp] lemma to_nonneg_coe {a : {x : α // 0 ≤ x}} : to_nonneg (a : α) = a := by { cases a with a ha, exact to_nonneg_of_nonneg ha } @[simp] lemma to_nonneg_le {a : α} {b : {x : α // 0 ≤ x}} : to_nonneg a ≤ b ↔ a ≤ b := by { cases b with b hb, simp [to_nonneg, hb] } @[simp] lemma to_nonneg_lt {a : {x : α // 0 ≤ x}} {b : α} : a < to_nonneg b ↔ ↑a < b := by { cases a with a ha, simp [to_nonneg, ha.not_lt] } instance has_sub [has_sub α] : has_sub {x : α // 0 ≤ x} := ⟨λ x y, to_nonneg (x - y)⟩ @[simp] lemma mk_sub_mk [has_sub α] {x y : α} (hx : 0 ≤ x) (hy : 0 ≤ y) : (⟨x, hx⟩ : {x : α // 0 ≤ x}) - ⟨y, hy⟩ = to_nonneg (x - y) := rfl end linear_order instance has_ordered_sub [linear_ordered_ring α] : has_ordered_sub {x : α // 0 ≤ x} := ⟨by { rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, simp only [sub_le_iff_le_add, subtype.mk_le_mk, mk_sub_mk, mk_add_mk, to_nonneg_le, subtype.coe_mk]}⟩ end nonneg
9678cfebb36a2ad16f49dcaa6d4f1a69b1e384cd
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/option_t.lean
58829bf8ec0e587a83e9fbb3f7591c2aca700e55
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
2,258
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.interactive init.category.transformers universes u v def option_t (m : Type u → Type v) [monad m] (α : Type u) : Type v := m (option α) @[inline] def option_t_bind {m : Type u → Type v} [monad m] {α β : Type u} (a : option_t m α) (b : α → option_t m β) : option_t m β := show m (option β), from do o ← a, match o with | none := return none | (some a) := b a end @[inline] def option_t_return {m : Type u → Type v} [monad m] {α : Type u} (a : α) : option_t m α := show m (option α), from return (some a) instance {m : Type u → Type v} [monad m] : monad (option_t m) := {pure := @option_t_return m _, bind := @option_t_bind m _, id_map := begin intros, simp [option_t_bind, function.comp], have h : option_t_bind._match_1 option_t_return = @pure m _ (option α), { apply funext, intro s, cases s, refl, refl }, { simp [h], apply @monad.bind_pure _ (option α) m }, end, pure_bind := begin intros, simp [option_t_bind, option_t_return, monad.pure_bind] end, bind_assoc := begin intros, simp [option_t_bind, option_t_return, monad.bind_assoc], apply congr_arg, apply funext, intro x, cases x, { simp [option_t_bind, monad.pure_bind] }, { refl } end} def option_t_orelse {m : Type u → Type v} [monad m] {α : Type u} (a : option_t m α) (b : option_t m α) : option_t m α := show m (option α), from do o ← a, match o with | none := b | (some v) := return (some v) end def option_t_fail {m : Type u → Type v} [monad m] {α : Type u} : option_t m α := show m (option α), from return none instance {m : Type u → Type v} [monad m] : alternative (option_t m) := { @option_t.monad m _ with failure := @option_t_fail m _, orelse := @option_t_orelse m _ } def option_t.lift {m : Type u → Type v} [monad m] {α : Type u} (a : m α) : option_t m α := (some <$> a : m (option α)) instance option_t.monad_transformer : monad.monad_transformer option_t := { is_monad := @option_t.monad, monad_lift := @option_t.lift }
cf61fb1fef52292a3f32c1f98eb052ef100f9b65
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/zify.lean
f7a01377658f098e160bcf2c3f46fb66f54936b9
[ "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
5,338
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.norm_cast import data.int.cast /-! # A tactic to shift `ℕ` goals to `ℤ` It is often easier to work in `ℤ`, where subtraction is well behaved, than in `ℕ` where it isn't. `zify` is a tactic that casts goals and hypotheses about natural numbers to ones about integers. It makes use of `push_cast`, part of the `norm_cast` family, to simplify these goals. ## Implementation notes `zify` is extensible, using the attribute `@[zify]` to label lemmas used for moving propositions from `ℕ` to `ℤ`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. `zify` is very nearly just `simp only with zify push_cast`. There are a few minor differences: * `zify` lemmas are used in the opposite order of the standard simp form. E.g. we will rewrite with `int.coe_nat_le_coe_nat_iff` from right to left. * `zify` should fail if no `zify` lemma applies (i.e. it was unable to shift any proposition to ℤ). However, once this succeeds, it does not necessarily need to rewrite with any `push_cast` rules. -/ open tactic namespace zify /-- The `zify` attribute is used by the `zify` tactic. It applies to lemmas that shift propositions between `nat` and `int`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. -/ @[user_attribute] meta def zify_attr : user_attribute simp_lemmas unit := { name := `zify, descr := "Used to tag lemmas for use in the `zify` tactic", cache_cfg := { mk_cache := λ ns, mmap (λ n, do c ← mk_const n, return (c, tt)) ns >>= simp_lemmas.mk.append_with_symm, dependencies := [] } } /-- Given an expression `e`, `lift_to_z e` looks for subterms of `e` that are propositions "about" natural numbers and change them to propositions about integers. Returns an expression `e'` and a proof that `e = e'`. Includes `ge_iff_le` and `gt_iff_lt` in the simp set. These can't be tagged with `zify` as we want to use them in the "forward", not "backward", direction. -/ meta def lift_to_z (e : expr) : tactic (expr × expr) := do sl ← zify_attr.get_cache, sl ← sl.add_simp `ge_iff_le, sl ← sl.add_simp `gt_iff_lt, simplify sl [] e attribute [zify] int.coe_nat_le_coe_nat_iff int.coe_nat_lt_coe_nat_iff int.coe_nat_eq_coe_nat_iff end zify @[zify] lemma int.coe_nat_ne_coe_nat_iff (a b : ℕ) : (a : ℤ) ≠ b ↔ a ≠ b := by simp /-- `zify extra_lems e` is used to shift propositions in `e` from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. The list of extra lemmas is used in the `push_cast` step. Returns an expression `e'` and a proof that `e = e'`.-/ meta def tactic.zify (extra_lems : list simp_arg_type) : expr → tactic (expr × expr) := λ z, do (z1, p1) ← zify.lift_to_z z <|> fail "failed to find an applicable zify lemma", (z2, p2) ← norm_cast.derive_push_cast extra_lems z1, prod.mk z2 <$> mk_eq_trans p1 p2 /-- A variant of `tactic.zify` that takes `h`, a proof of a proposition about natural numbers, and returns a proof of the zified version of that propositon. -/ meta def tactic.zify_proof (extra_lems : list simp_arg_type) (h : expr) : tactic expr := do (_, pf) ← infer_type h >>= tactic.zify extra_lems, mk_eq_mp pf h section setup_tactic_parser /-- The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. ```lean example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b := begin zify, zify at h, /- h : ¬↑x * ↑y * ↑z < 0 ⊢ ↑c < ↑a + 3 * ↑b -/ end ``` `zify` can be given extra lemmas to use in simplification. This is especially useful in the presence of nat subtraction: passing `≤` arguments will allow `push_cast` to do more work. ``` example (a b c : ℕ) (h : a - b < c) (hab : b ≤ a) : false := begin zify [hab] at h, /- h : ↑a - ↑b < ↑c -/ end ``` `zify` makes use of the `@[zify]` attribute to move propositions, and the `push_cast` tactic to simplify the `ℤ`-valued expressions. `zify` is in some sense dual to the `lift` tactic. `lift (z : ℤ) to ℕ` will change the type of an integer `z` (in the supertype) to `ℕ` (the subtype), given a proof that `z ≥ 0`; propositions concerning `z` will still be over `ℤ`. `zify` changes propositions about `ℕ` (the subtype) to propositions about `ℤ` (the supertype), without changing the type of any variable. -/ meta def tactic.interactive.zify (sl : parse simp_arg_list) (l : parse location) : tactic unit := do locs ← l.get_locals, replace_at (tactic.zify sl) locs l.include_goal >>= guardb end add_tactic_doc { name := "zify", category := doc_category.attr, decl_names := [`zify.zify_attr], tags := ["coercions", "transport"] } add_tactic_doc { name := "zify", category := doc_category.tactic, decl_names := [`tactic.interactive.zify], tags := ["coercions", "transport"] }
07af5d7a8980e26fec3c1f69428ca237e95db0f2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/test/linarith.lean
1d127062a60e555651021bb176aa59b2f2005350
[ "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
11,041
lean
import tactic.linarith example {α : Type} (_inst : Π (a : Prop), decidable a) [linear_ordered_field α] {a b c : α} (ha : a < 0) (hb : ¬b = 0) (hc' : c = 0) (h : (1 - a) * (b * b) ≤ 0) (hc : 0 ≤ 0) (this : -(a * -b * -b + b * -b + 0) = (1 - a) * (b * b)) (h : (1 - a) * (b * b) ≤ 0) : 0 < 1 - a := begin linarith end example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by linarith example (u v r s t : ℚ) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u := by linarith example (A B : ℚ) (h : 0 < A * B) : 0 < 8*A*B := begin linarith end example (A B : ℚ) (h : 0 < A * B) : 0 < A*8*B := begin linarith end example (A B : ℚ) (h : 0 < A * B) : 0 < A*B/8 := begin linarith end example (A B : ℚ) (h : 0 < A * B) : 0 < A/8*B := begin linarith end example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by linarith example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : false := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε := by linarith example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith {discharger := `[ring]} example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false := by linarith {restrict_type := ℚ} example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0) (h5 : 0 ≤ c) (h6 : c < 1) : v ≤ V := by linarith constant nat.prime : ℕ → Prop example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z)) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) : ¬ 12*y - 4* z < 0 := by linarith example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false := by linarith example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false := by linarith example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 := by linarith {exfalso := ff} example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith [rat.num_pos_iff_pos.mpr hx, h] example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith only [rat.num_pos_iff_pos.mpr hx, h] example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (h1 : (1 : ℕ) < 1) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 := by linarith example (a b c : ℕ) : a + b ≥ a := by linarith example (a b c : ℕ) : ¬ a + b < a := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0) (h'' : (6 + 3 * y) * y ≥ 0) : false := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 ∧ (x + 4) * x ≥ 0 ∧ (6 + 3 * y) * y ≥ 0) : false := by linarith example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false := by linarith example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false := by linarith example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 := by linarith example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c := by linarith example (N : ℕ) (n : ℕ) (Hirrelevant : n > N) (A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l) (h_3 : -(A - l) < 1) : A < l + 1 := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : d ≤ ((q : ℚ) - 1)*n := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : ((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) := by linarith example (a : ℚ) (ha : 0 ≤ a) : 0 * 0 ≤ 2 * a := by linarith example (x : ℚ) : id x ≥ x := by success_if_fail {linarith}; linarith! example (x y z : ℚ) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false := by linarith only [hx, hx2] example (x y z : ℚ) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x ≤ 5 := by linarith only [hx] example (x y : ℚ) (h : x < y) : x ≠ y := by linarith example (x y : ℚ) (h : x < y) : ¬ x = y := by linarith example (u v x y A B : ℚ) (a : 0 < A) (a_1 : 0 <= 1 - A) (a_2 : 0 <= B - 1) (a_3 : 0 <= B - x) (a_4 : 0 <= B - y) (a_5 : 0 <= u) (a_6 : 0 <= v) (a_7 : 0 < A - u) (a_8 : 0 < A - v) : u * y + v * x + u * v < 3 * A * B := by nlinarith example (u v x y A B : ℚ) : (0 < A) → (A ≤ 1) → (1 ≤ B) → (x ≤ B) → ( y ≤ B) → (0 ≤ u ) → (0 ≤ v ) → (u < A) → ( v < A) → (u * y + v * x + u * v < 3 * A * B) := begin intros, nlinarith end example (a b c z : ℚ) (_ : a ≤ z) (E0 : b ≤ c) (E1 : c ≤ a) (E2 : 0 ≤ c) : b ≤ a + c := by linarith example (u v x y A B : ℚ) (a_7 : 0 < A - u) (a_8 : 0 < A - v) : (0 ≤ A * (1 - A)) → (0 ≤ A * (B - 1)) → (0 < A * (A - u)) → (0 ≤ (B - 1) * (A - u)) → (0 ≤ (B - 1) * (A - v)) → (0 ≤ (B - x) * v) → (0 ≤ (B - y) * u) → (0 ≤ u * (A - v)) → u * y + v * x + u * v < 3 * A * B := begin intros, linarith end example (u v x y A B : ℚ) (a : 0 < A) (a_1 : 0 <= 1 - A) (a_2 : 0 <= B - 1) (a_3 : 0 <= B - x) (a_4 : 0 <= B - y) (a_5 : 0 <= u) (a_6 : 0 <= v) (a_7 : 0 < A - u) (a_8 : 0 < A - v) : (0 < A * A) -> (0 <= A * (1 - A)) -> (0 <= A * (B - 1)) -> (0 <= A * (B - x)) -> (0 <= A * (B - y)) -> (0 <= A * u) -> (0 <= A * v) -> (0 < A * (A - u)) -> (0 < A * (A - v)) -> (0 <= (1 - A) * A) -> (0 <= (1 - A) * (1 - A)) -> (0 <= (1 - A) * (B - 1)) -> (0 <= (1 - A) * (B - x)) -> (0 <= (1 - A) * (B - y)) -> (0 <= (1 - A) * u) -> (0 <= (1 - A) * v) -> (0 <= (1 - A) * (A - u)) -> (0 <= (1 - A) * (A - v)) -> (0 <= (B - 1) * A) -> (0 <= (B - 1) * (1 - A)) -> (0 <= (B - 1) * (B - 1)) -> (0 <= (B - 1) * (B - x)) -> (0 <= (B - 1) * (B - y)) -> (0 <= (B - 1) * u) -> (0 <= (B - 1) * v) -> (0 <= (B - 1) * (A - u)) -> (0 <= (B - 1) * (A - v)) -> (0 <= (B - x) * A) -> (0 <= (B - x) * (1 - A)) -> (0 <= (B - x) * (B - 1)) -> (0 <= (B - x) * (B - x)) -> (0 <= (B - x) * (B - y)) -> (0 <= (B - x) * u) -> (0 <= (B - x) * v) -> (0 <= (B - x) * (A - u)) -> (0 <= (B - x) * (A - v)) -> (0 <= (B - y) * A) -> (0 <= (B - y) * (1 - A)) -> (0 <= (B - y) * (B - 1)) -> (0 <= (B - y) * (B - x)) -> (0 <= (B - y) * (B - y)) -> (0 <= (B - y) * u) -> (0 <= (B - y) * v) -> (0 <= (B - y) * (A - u)) -> (0 <= (B - y) * (A - v)) -> (0 <= u * A) -> (0 <= u * (1 - A)) -> (0 <= u * (B - 1)) -> (0 <= u * (B - x)) -> (0 <= u * (B - y)) -> (0 <= u * u) -> (0 <= u * v) -> (0 <= u * (A - u)) -> (0 <= u * (A - v)) -> (0 <= v * A) -> (0 <= v * (1 - A)) -> (0 <= v * (B - 1)) -> (0 <= v * (B - x)) -> (0 <= v * (B - y)) -> (0 <= v * u) -> (0 <= v * v) -> (0 <= v * (A - u)) -> (0 <= v * (A - v)) -> (0 < (A - u) * A) -> (0 <= (A - u) * (1 - A)) -> (0 <= (A - u) * (B - 1)) -> (0 <= (A - u) * (B - x)) -> (0 <= (A - u) * (B - y)) -> (0 <= (A - u) * u) -> (0 <= (A - u) * v) -> (0 < (A - u) * (A - u)) -> (0 < (A - u) * (A - v)) -> (0 < (A - v) * A) -> (0 <= (A - v) * (1 - A)) -> (0 <= (A - v) * (B - 1)) -> (0 <= (A - v) * (B - x)) -> (0 <= (A - v) * (B - y)) -> (0 <= (A - v) * u) -> (0 <= (A - v) * v) -> (0 < (A - v) * (A - u)) -> (0 < (A - v) * (A - v)) -> u * y + v * x + u * v < 3 * A * B := begin intros, linarith end example (A B : ℚ) : (0 < A) → (1 ≤ B) → (0 < A / 8 * B) := begin intros, nlinarith end example (x y : ℚ) : 0 ≤ x ^2 + y ^2 := by nlinarith example (x y : ℚ) : 0 ≤ x*x + y*y := by nlinarith example (x y : ℚ) : x = 0 → y = 0 → x*x + y*y = 0 := by intros; nlinarith lemma norm_eq_zero_iff {x y : ℚ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split, { intro, split; nlinarith }, { intro, nlinarith } end lemma norm_nonpos_right {x y : ℚ} (h1 : x * x + y * y ≤ 0) : y = 0 := by nlinarith lemma norm_nonpos_left (x y : ℚ) (h1 : x * x + y * y ≤ 0) : x = 0 := by nlinarith variables {E : Type*} [add_group E] example (f : ℤ → E) (h : 0 = f 0) : 1 ≤ 2 := by nlinarith example (a : E) (h : a = a) : 1 ≤ 2 := by nlinarith -- test that the apply bug doesn't affect linarith preprocessing constant α : Type variable [fact false] -- we work in an inconsistent context below def leα : α → α → Prop := λ a b, ∀ c : α, true noncomputable instance : linear_ordered_field α := by refine_struct { le := leα }; exact (fact.out false).elim example (a : α) (ha : a < 2) : a ≤ a := by linarith example (p q r s t u v w : ℕ) (h1 : p + u = q + t) (h2 : r + w = s + v) : p * r + q * s + (t * w + u * v) = p * s + q * r + (t * v + u * w) := by nlinarith -- Tests involving a norm, including that squares in a type where `sq_nonneg` does not apply -- do not cause an exception variables {R : Type*} [ring R] (abs : R → ℚ) lemma abs_nonneg' : ∀ r, 0 ≤ abs r := (fact.out false).elim example (t : R) (a b : ℚ) (h : a ≤ b) : abs (t^2) * a ≤ abs (t^2) * b := by nlinarith [abs_nonneg' abs (t^2)] example (t : R) (a b : ℚ) (h : a ≤ b) : a ≤ abs (t^2) + b := by linarith [abs_nonneg' abs (t^2)] example (t : R) (a b : ℚ) (h : a ≤ b) : abs t * a ≤ abs t * b := by nlinarith [abs_nonneg' abs t] constant T : Type attribute [instance] constant T_zero : ordered_ring T namespace T lemma zero_lt_one : (0 : T) < 1 := (fact.out false).elim lemma works {a b : ℕ} (hab : a ≤ b) (h : b < a) : false := begin linarith, end end T example (a b c : ℚ) (h : a ≠ b) (h3 : b ≠ c) (h2 : a ≥ b) : b ≠ c := by linarith {split_ne := tt} example (a b c : ℚ) (h : a ≠ b) (h2 : a ≥ b) (h3 : b ≠ c) : a > b := by linarith {split_ne := tt} example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x * x := by nlinarith example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x ^ 2 := by nlinarith axiom foo {x : int} : 1 ≤ x → 1 ≤ x*x lemma bar (x y: int)(h : 0 ≤ y ∧ 1 ≤ x) : 1 ≤ y + x*x := by linarith [foo h.2] -- issue #9822 lemma mytest (j : ℕ) (h : 0 < j) : j-1 < j:= begin linarith, end
12e2300816c30a2f5e0349fad8091b2f9c3e1c4e
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/polynomial/reverse.lean
70bccafe4a3fa5d51242c1201bd185298e3aa046
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
11,409
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.erase_lead import data.polynomial.degree /-! # Reverse of a univariate polynomial The main definition is `reverse`. Applying `reverse` to a polynomial `f : polynomial R` produces the polynomial with a reversed list of coefficients, equivalent to `X^f.nat_degree * f(1/X)`. The main result is that `reverse (f * g) = reverse (f) * reverse (g)`, provided the leading coefficients of `f` and `g` do not multiply to zero. -/ namespace polynomial open polynomial finsupp finset open_locale classical section semiring variables {R : Type*} [semiring R] {f : polynomial R} /-- If `i ≤ N`, then `rev_at_fun N i` returns `N - i`, otherwise it returns `i`. This is the map used by the embedding `rev_at`. -/ def rev_at_fun (N i : ℕ) : ℕ := ite (i ≤ N) (N-i) i lemma rev_at_fun_invol {N i : ℕ} : rev_at_fun N (rev_at_fun N i) = i := begin unfold rev_at_fun, split_ifs with h j, { exact nat.sub_sub_self h, }, { exfalso, apply j, exact nat.sub_le N i, }, { refl, }, end lemma rev_at_fun_inj {N : ℕ} : function.injective (rev_at_fun N) := begin intros a b hab, rw [← @rev_at_fun_invol N a, hab, rev_at_fun_invol], end /-- If `i ≤ N`, then `rev_at N i` returns `N - i`, otherwise it returns `i`. Essentially, this embedding is only used for `i ≤ N`. The advantage of `rev_at N i` over `N - i` is that `rev_at` is an involution. -/ def rev_at (N : ℕ) : function.embedding ℕ ℕ := { to_fun := λ i , (ite (i ≤ N) (N-i) i), inj' := rev_at_fun_inj } /-- We prefer to use the bundled `rev_at` over unbundled `rev_at_fun`. -/ @[simp] lemma rev_at_fun_eq (N i : ℕ) : rev_at_fun N i = rev_at N i := rfl @[simp] lemma rev_at_invol {N i : ℕ} : (rev_at N) (rev_at N i) = i := rev_at_fun_invol @[simp] lemma rev_at_le {N i : ℕ} (H : i ≤ N) : rev_at N i = N - i := if_pos H lemma rev_at_add {N O n o : ℕ} (hn : n ≤ N) (ho : o ≤ O) : rev_at (N + O) (n + o) = rev_at N n + rev_at O o := begin rcases nat.le.dest hn with ⟨n', rfl⟩, rcases nat.le.dest ho with ⟨o', rfl⟩, repeat { rw rev_at_le (le_add_right rfl.le) }, rw [add_assoc, add_left_comm n' o, ← add_assoc, rev_at_le (le_add_right rfl.le)], repeat {rw nat.add_sub_cancel_left}, end /-- `reflect N f` is the polynomial such that `(reflect N f).coeff i = f.coeff (rev_at N i)`. In other words, the terms with exponent `[0, ..., N]` now have exponent `[N, ..., 0]`. In practice, `reflect` is only used when `N` is at least as large as the degree of `f`. Eventually, it will be used with `N` exactly equal to the degree of `f`. -/ noncomputable def reflect (N : ℕ) (f : polynomial R) : polynomial R := finsupp.emb_domain (rev_at N) f lemma reflect_support (N : ℕ) (f : polynomial R) : (reflect N f).support = image (rev_at N) f.support := begin ext1, rw [reflect, mem_image, support_emb_domain, mem_map], end @[simp] lemma coeff_reflect (N : ℕ) (f : polynomial R) (i : ℕ) : coeff (reflect N f) i = f.coeff (rev_at N i) := calc finsupp.emb_domain (rev_at N) f i = finsupp.emb_domain (rev_at N) f (rev_at N (rev_at N i)) : by rw rev_at_invol ... = f.coeff (rev_at N i) : finsupp.emb_domain_apply _ _ _ @[simp] lemma reflect_zero {N : ℕ} : reflect N (0 : polynomial R) = 0 := rfl @[simp] lemma reflect_eq_zero_iff {N : ℕ} {f : polynomial R} : reflect N (f : polynomial R) = 0 ↔ f = 0 := begin split, { intros a, injection a with f0 f1, rwa [map_eq_empty, support_eq_empty] at f0, }, { rintro rfl, refl, }, end @[simp] lemma reflect_add (f g : polynomial R) (N : ℕ) : reflect N (f + g) = reflect N f + reflect N g := by { ext, simp only [coeff_add, coeff_reflect], } @[simp] lemma reflect_C_mul (f : polynomial R) (r : R) (N : ℕ) : reflect N (C r * f) = C r * (reflect N f) := by { ext, simp only [coeff_reflect, coeff_C_mul], } @[simp] lemma reflect_C_mul_X_pow (N n : ℕ) {c : R} : reflect N (C c * X ^ n) = C c * X ^ (rev_at N n) := begin ext, rw [reflect_C_mul, coeff_C_mul, coeff_C_mul, coeff_X_pow, coeff_reflect], split_ifs with h j, { rw [h, rev_at_invol, coeff_X_pow_self], }, { rw [not_mem_support_iff_coeff_zero.mp], intro a, rw [← one_mul (X ^ n), ← C_1] at a, apply h, rw [← (mem_support_C_mul_X_pow a), rev_at_invol], }, end @[simp] lemma reflect_monomial (N n : ℕ) : reflect N ((X : polynomial R) ^ n) = X ^ (rev_at N n) := by rw [← one_mul (X ^ n), ← one_mul (X ^ (rev_at N n)), ← C_1, reflect_C_mul_X_pow] lemma reflect_mul_induction (cf cg : ℕ) : ∀ N O : ℕ, ∀ f g : polynomial R, f.support.card ≤ cf.succ → g.support.card ≤ cg.succ → f.nat_degree ≤ N → g.nat_degree ≤ O → (reflect (N + O) (f * g)) = (reflect N f) * (reflect O g) := begin induction cf with cf hcf, --first induction (left): base case { induction cg with cg hcg, -- second induction (right): base case { intros N O f g Cf Cg Nf Og, rw [← C_mul_X_pow_eq_self Cf, ← C_mul_X_pow_eq_self Cg], simp only [mul_assoc, X_pow_mul, ← pow_add X, reflect_C_mul, reflect_monomial, add_comm, rev_at_add Nf Og] }, -- second induction (right): induction step { intros N O f g Cf Cg Nf Og, by_cases g0 : g = 0, { rw [g0, reflect_zero, mul_zero, mul_zero, reflect_zero], }, rw [← erase_lead_add_C_mul_X_pow g, mul_add, reflect_add, reflect_add, mul_add, hcg, hcg]; try { assumption }, { exact le_add_left card_support_C_mul_X_pow_le_one }, { exact (le_trans (nat_degree_C_mul_X_pow_le g.leading_coeff g.nat_degree) Og) }, { exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cg (erase_lead_support_card_lt g0)) }, { exact le_trans erase_lead_nat_degree_le Og } } }, --first induction (left): induction step { intros N O f g Cf Cg Nf Og, by_cases f0 : f = 0, { rw [f0, reflect_zero, zero_mul, zero_mul, reflect_zero], }, rw [← erase_lead_add_C_mul_X_pow f, add_mul, reflect_add, reflect_add, add_mul, hcf, hcf]; try { assumption }, { exact le_add_left card_support_C_mul_X_pow_le_one }, { exact (le_trans (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree) Nf) }, { exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cf (erase_lead_support_card_lt f0)) }, { exact (le_trans erase_lead_nat_degree_le Nf) } }, end @[simp] theorem reflect_mul (f g : polynomial R) {F G : ℕ} (Ff : f.nat_degree ≤ F) (Gg : g.nat_degree ≤ G) : reflect (F + G) (f * g) = reflect F f * reflect G g := reflect_mul_induction _ _ F G f g f.support.card.le_succ g.support.card.le_succ Ff Gg /-- The reverse of a polynomial f is the polynomial obtained by "reading f backwards". Even though this is not the actual definition, reverse f = f (1/X) * X ^ f.nat_degree. -/ noncomputable def reverse (f : polynomial R) : polynomial R := reflect f.nat_degree f lemma coeff_reverse (f : polynomial R) (n : ℕ) : f.reverse.coeff n = f.coeff (rev_at f.nat_degree n) := by rw [reverse, coeff_reflect] @[simp] lemma coeff_zero_reverse (f : polynomial R) : coeff (reverse f) 0 = leading_coeff f := by rw [coeff_reverse, rev_at_le (zero_le f.nat_degree), nat.sub_zero, leading_coeff] @[simp] lemma reverse_zero : reverse (0 : polynomial R) = 0 := rfl @[simp] lemma reverse_eq_zero : f.reverse = 0 ↔ f = 0 := begin split, { rw [polynomial.ext_iff, polynomial.ext_iff], intros h n, specialize h (rev_at f.nat_degree n), rwa [coeff_zero, coeff_reverse, rev_at_invol] at h }, { intro h, rw [h, reverse_zero] }, end lemma reverse_nat_degree_le (f : polynomial R) : f.reverse.nat_degree ≤ f.nat_degree := begin rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero], intros n hn, rw with_bot.coe_lt_coe at hn, rw [coeff_reverse, rev_at, function.embedding.coe_fn_mk, if_neg (not_le_of_gt hn), coeff_eq_zero_of_nat_degree_lt hn], end lemma nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree (f : polynomial R) : f.nat_degree = f.reverse.nat_degree + f.nat_trailing_degree := begin by_cases hf : f = 0, { rw [hf, reverse_zero, nat_degree_zero, nat_trailing_degree_zero] }, apply le_antisymm, { apply nat.le_add_of_sub_le_right, apply le_nat_degree_of_ne_zero, rw [reverse, coeff_reflect, ←rev_at_le f.nat_trailing_degree_le_nat_degree, rev_at_invol], exact trailing_coeff_nonzero_iff_nonzero.mpr hf }, { rw ← nat.le_sub_left_iff_add_le f.reverse_nat_degree_le, apply nat_trailing_degree_le_of_ne_zero, have key := mt leading_coeff_eq_zero.mp (mt reverse_eq_zero.mp hf), rwa [leading_coeff, coeff_reverse, rev_at_le f.reverse_nat_degree_le] at key }, end lemma reverse_nat_degree (f : polynomial R) : f.reverse.nat_degree = f.nat_degree - f.nat_trailing_degree := by rw [f.nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree, nat.add_sub_cancel] lemma reverse_leading_coeff (f : polynomial R) : f.reverse.leading_coeff = f.trailing_coeff := by rw [leading_coeff, reverse_nat_degree, ←rev_at_le f.nat_trailing_degree_le_nat_degree, coeff_reverse, rev_at_invol, trailing_coeff] lemma reverse_nat_trailing_degree (f : polynomial R) : f.reverse.nat_trailing_degree = 0 := begin by_cases hf : f = 0, { rw [hf, reverse_zero, nat_trailing_degree_zero] }, { rw ← nat.le_zero_iff, apply nat_trailing_degree_le_of_ne_zero, rw [coeff_zero_reverse], exact mt leading_coeff_eq_zero.mp hf }, end lemma reverse_trailing_coeff (f : polynomial R) : f.reverse.trailing_coeff = f.leading_coeff := by rw [trailing_coeff, reverse_nat_trailing_degree, coeff_zero_reverse] theorem reverse_mul {f g : polynomial R} (fg : f.leading_coeff * g.leading_coeff ≠ 0) : reverse (f * g) = reverse f * reverse g := begin unfold reverse, rw [nat_degree_mul' fg, reflect_mul f g rfl.le rfl.le], end @[simp] lemma reverse_mul_of_domain {R : Type*} [domain R] (f g : polynomial R) : reverse (f * g) = reverse f * reverse g := begin by_cases f0 : f=0, { simp only [f0, zero_mul, reverse_zero], }, by_cases g0 : g=0, { rw [g0, mul_zero, reverse_zero, mul_zero], }, simp [reverse_mul, *], end lemma trailing_coeff_mul {R : Type*} [integral_domain R] (p q : polynomial R) : (p * q).trailing_coeff = p.trailing_coeff * q.trailing_coeff := by rw [←reverse_leading_coeff, reverse_mul_of_domain, leading_coeff_mul, reverse_leading_coeff, reverse_leading_coeff] @[simp] lemma coeff_one_reverse (f : polynomial R) : coeff (reverse f) 1 = next_coeff f := begin rw [coeff_reverse, next_coeff], split_ifs with hf, { have : coeff f 1 = 0 := coeff_eq_zero_of_nat_degree_lt (by simp only [hf, zero_lt_one]), simp [*, rev_at] }, { rw rev_at_le, exact nat.succ_le_iff.2 (pos_iff_ne_zero.2 hf) } end end semiring section ring variables {R : Type*} [ring R] @[simp] lemma reflect_neg (f : polynomial R) (N : ℕ) : reflect N (- f) = - reflect N f := by rw [neg_eq_neg_one_mul, ←C_1, ←C_neg, reflect_C_mul, C_neg, C_1, ←neg_eq_neg_one_mul] @[simp] lemma reflect_sub (f g : polynomial R) (N : ℕ) : reflect N (f - g) = reflect N f - reflect N g := by rw [sub_eq_add_neg, sub_eq_add_neg, reflect_add, reflect_neg] @[simp] lemma reverse_neg (f : polynomial R) : reverse (- f) = - reverse f := by rw [reverse, reverse, reflect_neg, nat_degree_neg] end ring end polynomial
44b058bcea9f9982cc1300a62e6ad19a3b85fbad
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/topology/metric_space/emetric_space.lean
0442a4b111341f0b512a508bcf8b7b68bc103670
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
31,726
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Extended metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ import data.real.nnreal data.real.ennreal import topology.uniform_space.separation topology.uniform_space.uniform_embedding open lattice set filter classical noncomputable theory local attribute [instance, priority 0] nat.cast_coe local notation `𝓤` := uniformity universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /- Design note: one could define an `emetric_space` just by giving `edist`, and then derive an instance of `uniform_space` by taking the natural uniform structure associated to the distance. This creates diamonds problem for products, as the uniform structure on the product of two emetric spaces could be obtained first by obtaining two uniform spaces and then taking their products, or by taking the product of the emetric spaces and then the associated uniform structure. The two uniform structure we have just described are equal, but not defeq, which creates a lot of problem. The idea is to add, in the very definition of an `emetric_space`, a uniform structure with a uniformity which equal to the one given by the distance, but maybe not defeq. And the instance from `emetric_space` to `uniform_space` uses this uniformity. In this way, when we create the product of emetric spaces, we put in the product the uniformity corresponding to the product of the uniformities. There is one more proof obligation, that this product uniformity is equal to the uniformity corresponding to the product metric. But the diamond problem disappears. The same trick is used in the definition of a metric space, where one stores as well a uniform structure and an edistance. -/ /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, this ▸ ennreal.nat_ne_top 2⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is finally proving in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space α export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense (by simp) h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist' : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := emetric_space.uniformity_edist _ /-- Reformulation of the uniform structure in terms of the extended distance on a subtype -/ theorem uniformity_edist'' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_edist' theorem uniformity_edist_nnreal : 𝓤 α = (⨅(ε:nnreal) (h : ε > 0), principal {p:α×α | edist p.1 p.2 < ε}) := begin rw [uniformity_edist', ennreal.infi_ennreal, inf_of_le_left], { congr, funext ε, refine infi_congr_Prop ennreal.coe_pos _, assume h, refl }, refine le_infi (assume h, infi_le_of_le 1 $ infi_le_of_le ennreal.zero_lt_one $ _), exact principal_mono.2 (assume p h, lt_of_lt_of_le h le_top) end /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := begin rw [uniformity_edist'', mem_infi], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ end /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_edist.1 $ H _ $ edist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_edist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (edist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ end emetric open emetric /-- An emetric space is separated -/ instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ (emetric_space.to_uniform_space α)) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced subtype.val (λ x y, subtype.eq) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} [t : emetric_space α] (x y : subtype p) : edist x y = edist x.1 y.1 := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := eq_of_edist_eq_zero (by simpa using h₁), have B : x.snd = y.snd := eq_of_edist_eq_zero (by simpa using h₂), exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, eq_of_edist_eq_zero $ bot_unique $ eq1 b $ mem_univ b), end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤): ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := lattice.ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ theorem nhds_eq : nhds x = (⨅ε:{ε:ennreal // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_edist'', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, edist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff : s ∈ nhds x ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq, mem_infi], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right, (≥)] }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ } end theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ nhds x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ theorem mem_closure_iff' : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := ⟨begin intros hx ε hε, have A : ball x ε ∩ s ≠ ∅ := mem_closure_iff.1 hx _ is_open_ball (mem_ball_self hε), cases ne_empty_iff_exists_mem.1 A with y hy, simp, exact ⟨y, ⟨hy.2, by have B := hy.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho xo, rcases is_open_iff.1 ho x xo with ⟨ε, ⟨εpos, hε⟩⟩, rcases H ε εpos with ⟨y, ⟨ys, ydist⟩⟩, have B : y ∈ o ∩ s := ⟨hε (by simpa [edist_comm]), ys⟩, apply ne_empty_of_mem B end⟩ theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, edist (u x) a < ε := ⟨λ H ε ε0, ⟨u⁻¹' (ball a ε), H (ball_mem_nhds _ ε0), by simp⟩, λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in f.sets_of_superset δ0 (λx xδ, hε (hδ x xδ))⟩ theorem tendsto_at_top [inhabited β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := begin rw tendsto_nhds, apply forall_congr, intro ε, apply forall_congr, intro hε, simp, exact ⟨λ ⟨s, ⟨N, hN⟩, hs⟩, ⟨N, λn hn, hs _ (hN _ hn)⟩, λ ⟨N, hN⟩, ⟨{n | n ≥ N}, ⟨⟨N, by simp⟩, hN⟩⟩⟩, end /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ theorem cauchy_seq_iff [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u n) (u m) < ε := begin simp only [cauchy_seq, emetric.cauchy_iff, true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot, filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq], split, { intros H ε εpos, rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩, exact ⟨N, λm n hm hn, ht _ _ (hN _ hn) (hN _ hm)⟩ }, { intros H ε εpos, rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩, existsi ball (u N) (ε/2), split, { exact ⟨N, λx hx, hN _ _ (le_refl N) hx⟩ }, { exact λx y hx hy, calc edist x y ≤ edist x (u N) + edist y (u N) : edist_triangle_right _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add hx hy ... = ε : ennreal.add_halves _ } } end /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := begin rw cauchy_seq_iff, split, { intros H ε εpos, rcases H ε εpos with ⟨N, hN⟩, exact ⟨N, λn hn, hN _ _ (le_refl N) hn⟩ }, { intros H ε εpos, rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩, exact ⟨N, λ m n hm hn, calc edist (u n) (u m) ≤ edist (u n) (u N) + edist (u m) (u N) : edist_triangle_right _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add (hN _ hn) (hN _ hm) ... = ε : ennreal.add_halves _⟩ } end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, countable_finite], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff'.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := ⟨assume a, ⟨⋃ i:ℕ, {ball a i⁻¹}, countable_Union $ assume n, countable_singleton _, suffices (⨅ i:{ i : ennreal // i > 0}, principal (ball a i)) = ⨅ (n : ℕ), principal (ball a n⁻¹), by simpa [nhds_eq, @infi_comm _ _ ℕ], begin apply le_antisymm, { refine le_infi (assume n, infi_le_of_le _ _), exact ⟨n⁻¹, by apply bot_lt_iff_ne_bot.2; simp⟩, exact le_refl _ }, refine le_infi (assume ε, _), rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 ε.2) with ⟨n, εn⟩, exact infi_le_of_le n (principal_mono.2 $ ball_subset_ball $ le_of_lt εn) end⟩⟩ end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ α in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply countable_bUnion S_countable, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space α = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff'.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := Sup ((λp : α × α, edist p.1 p.2) '' (set.prod s s)) /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := le_Sup ((mem_image _ _ _).2 ⟨(⟨x, y⟩ : α × α), by simp [hx, hy]⟩) /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀x y ∈ s, edist x y ≤ d) : diam s ≤ d := begin apply Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x y xs ys dxy, rw ← dxy, exact h x y xs ys end /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := by simp [diam] /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := by simp [diam] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := begin refine Sup_le_Sup (λp hp, _), simp only [set.mem_image, set.mem_prod, prod.exists] at hp, rcases hp with ⟨x, y, ⟨⟨xs, ys⟩, dxy⟩⟩, exact (mem_image _ _ _).2 ⟨⟨x, y⟩, ⟨⟨h xs, h ys⟩, dxy⟩⟩ end /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa b ha hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := ne_empty_iff_exists_mem.1 h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa b ha hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
d9144340cb27c0bc787a80c7269ebd256d480fc1
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/induction.lean
b1c9de63a0e8b4cb233cf6171919a404dc7b6370
[ "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
4,154
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.coeff /-! # Theory of univariate polynomials The main results are `induction_on` and `as_sum`. -/ noncomputable theory open finsupp finset namespace polynomial open_locale polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} lemma sum_C_mul_X_eq (p : R[X]) : p.sum (λn a, C a * X^n) = p := begin ext n, simp only [polynomial.sum, X_pow_eq_monomial, coeff_monomial, mul_one, finset_sum_coeff, C_mul_monomial, not_not, mem_support_iff, finset.sum_ite_eq', ite_eq_left_iff], exact λ h, h.symm end lemma sum_monomial_eq (p : R[X]) : p.sum (λn a, monomial n a) = p := by simp only [monomial_eq_C_mul_X, sum_C_mul_X_eq] @[elab_as_eliminator] protected lemma induction_on {M : R[X] → Prop} (p : R[X]) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (C a * X^n) → M (C a * X^(n+1))) : M p := begin have A : ∀{n:ℕ} {a}, M (C a * X^n), { assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } }, have B : ∀ (s : finset ℕ), M (s.sum (λ (n : ℕ), C (p.coeff n) * X ^ n)), { apply finset.induction, { convert h_C 0, exact C_0.symm }, { assume n s ns ih, rw sum_insert ns, exact h_add _ _ A ih, } }, rw [← sum_C_mul_X_eq p, polynomial.sum], exact B _ end /-- To prove something about polynomials, it suffices to show the condition is closed under taking sums, and it holds for monomials. -/ @[elab_as_eliminator] protected lemma induction_on' {M : R[X] → Prop} (p : R[X]) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (monomial n a)) : M p := polynomial.induction_on p (h_monomial 0) h_add (λ n a h, by { rw ← monomial_eq_C_mul_X at ⊢, exact h_monomial _ _ }) section coeff theorem coeff_mul_monomial (p : R[X]) (n d : ℕ) (r : R) : coeff (p * monomial n r) (d + n) = coeff p d * r := by rw [monomial_eq_C_mul_X, ←X_pow_mul, ←mul_assoc, coeff_mul_C, coeff_mul_X_pow] theorem coeff_monomial_mul (p : R[X]) (n d : ℕ) (r : R) : coeff (monomial n r * p) (d + n) = r * coeff p d := by rw [monomial_eq_C_mul_X, mul_assoc, coeff_C_mul, X_pow_mul, coeff_mul_X_pow] -- This can already be proved by `simp`. theorem coeff_mul_monomial_zero (p : R[X]) (d : ℕ) (r : R) : coeff (p * monomial 0 r) d = coeff p d * r := coeff_mul_monomial p 0 d r -- This can already be proved by `simp`. theorem coeff_monomial_zero_mul (p : R[X]) (d : ℕ) (r : R) : coeff (monomial 0 r * p) d = r * coeff p d := coeff_monomial_mul p 0 d r end coeff open submodule polynomial set variables {f : R[X]} {I : submodule R[X] R[X]} /-- If the coefficients of a polynomial belong to n ideal contains the submodule span of the coefficients of a polynomial. -/ lemma span_le_of_coeff_mem_C_inverse (cf : ∀ (i : ℕ), f.coeff i ∈ (C ⁻¹' I.carrier)) : (span R[X] {g | ∃ i, g = C (f.coeff i)}) ≤ I := begin refine bInter_subset_of_mem _, rintros _ ⟨i, rfl⟩, exact set_like.mem_coe.mpr (cf i), end lemma mem_span_C_coeff : f ∈ span R[X] {g : R[X] | ∃ i : ℕ, g = (C (coeff f i))} := begin let p := span R[X] {g : R[X] | ∃ i : ℕ, g = (C (coeff f i))}, nth_rewrite 0 (sum_C_mul_X_eq f).symm, refine submodule.sum_mem _ (λ n hn, _), dsimp, have : C (coeff f n) ∈ p, by { apply subset_span, simp }, have : (monomial n (1 : R)) • C (coeff f n) ∈ p := p.smul_mem _ this, convert this using 1, simp only [monomial_mul_C, one_mul, smul_eq_mul], rw monomial_eq_C_mul_X, end lemma exists_coeff_not_mem_C_inverse : f ∉ I → ∃ i : ℕ , coeff f i ∉ (C ⁻¹' I.carrier) := imp_of_not_imp_not _ _ (λ cf, not_not.mpr ((span_le_of_coeff_mem_C_inverse (not_exists_not.mp cf)) mem_span_C_coeff)) end semiring end polynomial
15cd17c6f370943a9c3ddd0e12aa519ab1ff66b4
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/exponential_complex1.lean
1e7192d89e42b420935a0db0ce7b340f7ab8d91c
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
23,353
lean
import data.complex.basic data.real.cau_seq tactic.norm_num data.nat.basic tactic.ring algebra.archimedean .limits data.nat.choose section a open real nat is_absolute_value finset noncomputable theory local attribute [instance, priority 0] classical.prop_decidable lemma pow_inv' {α : Type*} [discrete_field α] (a : α) (n : ℕ) : (a ^ n)⁻¹ = a⁻¹ ^ n := by induction n; simp [_root_.pow_succ, *, mul_inv', mul_comm] lemma pow_incrs_of_gt_one {α : Type*} [linear_ordered_semiring α] {x : α} {n m : ℕ} (h1x : 1 < x) (hnm : n < m) : x ^ n < x ^ m := begin rw [← nat.sub_add_cancel hnm, _root_.pow_add, _root_.pow_succ, ← mul_assoc], refine (lt_mul_iff_one_lt_left (pow_pos (lt_trans (by norm_num) h1x) _)).2 _, rw ← one_mul (1 : α), refine mul_lt_mul' (one_le_pow_of_one_le (le_of_lt h1x) _) h1x (by norm_num) (pow_pos (lt_trans (by norm_num) h1x) _) end lemma pow_dcrs_of_lt_one_of_pos {α : Type*} [discrete_linear_ordered_field α] {x : α} {n m : ℕ} (hx1 : x < 1) (h0x : 0 < x) (hnm : n < m) : x ^ m < x ^ n := begin refine (inv_lt_inv _ _).1 _, { exact pow_pos h0x _ }, { exact pow_pos h0x _ }, { rw [pow_inv', pow_inv'], refine pow_incrs_of_gt_one (one_lt_inv h0x hx1) hnm } end open finset @[simp] lemma sum_range_zero {α : Type*} [add_comm_monoid α] (f : ℕ → α) : (range 0).sum f = 0 := rfl lemma sum_range_succ {α : Type*} [add_comm_monoid α] (f : ℕ → α) (n : ℕ) : (range (succ n)).sum f = f n + (range n).sum f := by simp lemma sum_range_succ' {α : Type*} [add_comm_monoid α] (f : ℕ → α) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 | 0 := by simp | (n + 1) := by rw [sum_range_succ (λ m, f (nat.succ m)), add_assoc, ← sum_range_succ']; exact sum_range_succ _ _ /-- The binomial theorem -/ theorem add_pow {α : Type*} [comm_semiring α] (x y : α) : ∀ n : ℕ, (x + y) ^ n = (range (succ n)).sum (λ m, x ^ m * y ^ (n - m) * choose n m) | 0 := by simp | (succ n) := have h₁ : x * (x ^ n * y ^ (n - n) * choose n n) = x ^ succ n * y ^ (succ n - succ n) * choose (succ n) (succ n), by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0, by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₃ : (range n).sum (λ m, x * (x ^ m * y ^ (n - m) * choose n m) + y * (x ^ succ m * y ^ (n - succ m) * choose n (succ m))) = (range n).sum (λ m, x ^ succ m * y ^ (succ n - succ m) * ↑(choose (succ n) (succ m))), from finset.sum_congr rfl $ λ m hm, begin simp only [mul_assoc, mul_left_comm y, mul_left_comm (y ^ (n - succ m)), mul_comm y], rw [← _root_.pow_succ', add_one, ← succ_sub (mem_range.1 hm)], simp [choose_succ_succ, mul_comm, mul_assoc, mul_left_comm, add_mul, mul_add, _root_.pow_succ] end, by rw [_root_.pow_succ, add_pow, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ', sum_range_succ, sum_range_succ', add_assoc, ← add_assoc ((range n).sum _), ← finset.sum_add_distrib, h₁, h₂, h₃] lemma geo_series_eq {α : Type*} [field α] {x : α} (n : ℕ) (hx1 : x ≠ 1) : (range n).sum (λ m, x ^ m) = (1 - x ^ n) / (1 - x) := have 1 - x ≠ 0 := mt sub_eq_zero_iff_eq.1 hx1.symm, begin induction n with n ih, { simp }, { rw [sum_range_succ, ← mul_div_cancel (x ^ n) this, ih, ← add_div, _root_.pow_succ], refine congr_fun (congr_arg _ _) _, ring } end variables {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f (succ n) ≤ 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 lemma is_cau_of_dcrs_bounded {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f (succ n) ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - add_monoid.smul (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_monoid.add_smul], 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 - add_monoid.smul 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 (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 - add_monoid.smul (pred l) ε : hi.2 ... = a - add_monoid.smul l ε + ε : by conv {to_rhs, rw [← succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_incrs_bounded {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f (succ n)) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_dcrs_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma series_cau_of_abv_le_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {f : ℕ → β} {g : ℕ → α} {abv : β → α} [is_absolute_value abv] (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) at this, rw 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 *, rw [succ_add, sum_range_succ, sum_range_succ, add_assoc, 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 pow_abv {α β : Type*} [discrete_linear_ordered_field α] [domain β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, _root_.pow_succ, abv_one abv, *] lemma series_cau_of_abv_cau {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] {abv : β → α} {f : ℕ → β} [is_absolute_value abv] : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := λ h, series_cau_of_abv_le_cau 0 (λ n h, le_refl _) h lemma geo_series_cau {α β : Type*} [discrete_linear_ordered_field α] [archimedean α] [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, series_cau_of_abv_cau begin simp only [pow_abv abv, geo_series_eq _ hx1'] {eta := ff}, refine @is_cau_of_incrs_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg , refine div_le_div_of_le_of_pos (sub_le_self _ (pow_abv 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 [_root_.pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (pow_abv 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), _root_.pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma geo_series_const_cau {α : Type*} [discrete_linear_ordered_field α] [archimedean α] (a x : α) : abs x < 1 → is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := λ hx1, begin have : is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, geo_series_cau x hx1⟩).2, simpa only [mul_sum] using this end -- The form of ratio test with 0 ≤ r < 1, and abv (f (succ m)) ≤ r * abv (f m) handled zero terms of series the best lemma series_ratio_test {α : Type*} {β : Type*} [discrete_linear_ordered_field α] [ring β] [archimedean α] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} (n : ℕ) (r : α) : 0 ≤ r → r < 1 → (∀ m, n ≤ m → abv (f (succ m)) ≤ r * abv (f m)) → is_cau_seq abv (λ m, (range m).sum f) := begin assume r0 r1 h, refine series_cau_of_abv_le_cau (succ n) _ (geo_series_const_cau (abv (f (succ n)) * r⁻¹ ^ (succ n)) r _), assume m mn, generalize hk : m - (succ n) = k,rw nat.sub_eq_iff_eq_add mn at hk, cases classical.em (r = 0) with r_zero r_pos,have m_pos := lt_of_lt_of_le (succ_pos n) mn, have := pred_le_pred mn,simp at this, have := h (pred m) this,simp[r_zero,succ_pred_eq_of_pos m_pos] at this, refine le_trans this _,refine mul_nonneg _ _, refine mul_nonneg (abv_nonneg _ _) (pow_nonneg (inv_nonneg.mpr r0) _),exact pow_nonneg r0 _, replace r_pos : 0 < r,cases lt_or_eq_of_le r0 with h h,exact h,exact absurd h.symm r_pos, revert m n, induction k with k' hi,assume m n h mn hk, rw [hk,zero_add,mul_right_comm,←pow_inv',←div_eq_mul_inv,mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm, assume m n h mn hk,rw [hk,succ_add], have kn : k' + (succ n) ≥ (succ n), rw ←zero_add (succ n),refine add_le_add _ _,exact zero_le _,simp, replace hi := hi (k' + (succ n)) n h kn rfl, rw [(by simp [_root_.pow_succ'] : r ^ (succ (k' + succ n)) = r ^ (k' + succ n) * r),←mul_assoc], replace h := h (k' + succ n) (le_of_succ_le kn),rw mul_comm at h, exact le_trans h (mul_le_mul_of_nonneg_right hi r0), rwa abs_of_nonneg r0, 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 ∘ 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, sum (range (n - m)) (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 < 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 (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, 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, 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 (le_of_lt ha.1)).1 ha.2), mem_range.2 (lt_succ_of_le (le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {α β γ : Type*} [discrete_linear_ordered_field α] [ring β] (abv : β → α) [is_absolute_value abv] (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := 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_nonneg {α β : Type*} [ordered_comm_monoid α] {f : β → α} {s : finset β} : (∀ x ∈ s, 0 ≤ f x) → 0 ≤ s.sum f := finset.induction_on s (by simp) $ λ a s has ih h, begin rw [sum_insert has], exact add_nonneg' (h a (by simp)) (ih (λx hx, by simp *)), end lemma neg_sum {α β : Type*} [add_comm_group α] {f : β → α} {s : finset β} : -s.sum f = s.sum (λ x, -f x) := finset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] lemma filter_true {α : Type*} (s : finset α) : s.filter (λ _, true) = s := finset.ext.2 $ by simp 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 lemma series_cauchy_prod {α β : Type*} [discrete_linear_ordered_field α] [ring β] {a b : ℕ → β} {abv : β → α} [is_absolute_value abv] : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n))) → is_cau_seq abv (λ m, (range m).sum b) → ∀ ε : α, 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))) ) < ε := begin -- slightly adapted version of theorem 9.4.7 from "The Real Numbers and Real Analysis", Ethan D. Bloch assume ha hb ε ε0, cases cau_seq.bounded ⟨_, hb⟩ with Q hQ,simp at hQ, cases cau_seq.bounded ⟨_, ha⟩ with P hP,simp at hP, have P0 : 0 < P,exact lt_of_le_of_lt (abs_nonneg _) (hP 0), have Pε0 := div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) P0), cases cau_seq.cauchy₂ ⟨_, hb⟩ Pε0 with N hN,simp at hN, have Qε0 := div_pos ε0 (mul_pos (show (4 : α) > 0, from by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), cases cau_seq.cauchy₂ ⟨_, ha⟩ Qε0 with M hM,simp at hM, existsi 2 * (max N M + 1), assume K hK, have := sum_range_diag_flip K (λ m n, a m * b n), dsimp at this, rw this, have : (λ (i : ℕ), (range (K - i)).sum (λ (k : ℕ), a i * b k)) = (λ (i : ℕ), a i * (range (K - i)).sum b), by simp [finset.mul_sum], rw this,clear this, have : (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), {rw ←sum_add_distrib,simp[(mul_add _ _ _).symm]}, rw this, clear this, rw sum_mul, simp, rw abv_neg abv, refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _ _) _, simp [abv_mul 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), { simp [(div_div_eq_div_mul _ _ _).symm] at this, rwa[div_mul_cancel _ (ne_of_lt P0).symm,(by norm_num : (4 : α) = 2 * 2),←div_div_eq_div_mul,mul_comm (2 : α),←_root_.mul_assoc, div_mul_cancel _ (ne_of_lt (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).symm,div_mul_cancel,add_halves] at this, norm_num}, refine add_lt_add _ _, {have : (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))) := by {refine sum_le_sum _,assume m mJ,refine mul_le_mul_of_nonneg_left _ _, {refine le_of_lt (hN (K - m) K _ _),{ refine nat.le_sub_left_of_add_le (le_trans _ hK), rw[succ_mul,_root_.one_mul], exact add_le_add (le_of_lt (mem_range.1 mJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))}, {refine le_trans _ hK,rw ←_root_.one_mul N, refine mul_le_mul (by norm_num) (by rw _root_.one_mul;exact le_trans (le_max_left _ _) (le_of_lt (lt_add_one _))) (zero_le _) (zero_le _)}}, exact abv_nonneg abv _}, refine lt_of_le_of_lt this _, rw [← sum_mul, mul_comm], specialize hP (max N M + 1),rwa abs_of_nonneg at hP, exact (mul_lt_mul_left Pε0).mpr hP, exact sum_nonneg (λ x h, abv_nonneg abv _)}, {have hNMK : max N M + 1 < K := by {refine lt_of_lt_of_le _ hK, rw [succ_mul,_root_.one_mul,←add_zero (max N M + 1)], refine add_lt_add_of_le_of_lt (le_refl _) _,rw add_zero, refine add_pos_of_nonneg_of_pos (zero_le _) (by norm_num)}, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc sum (filter (λ (k : ℕ), max N M + 1 ≤ k) (range K)) (λ (i : ℕ), abv (a i) * abv (sum (range (K - i)) b - sum (range K) b)) ≤ sum (filter (λ (k : ℕ), max N M + 1 ≤ k) (range K)) (λ i, abv (a i) * (2 * Q)) : sum_le_sum (begin assume n hn, 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], refine add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < _ : begin rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)], refine (mul_lt_mul_right _).2 _, rw two_mul, refine add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)), refine lt_of_le_of_lt (le_abs_self _) _, refine hM _ _ (le_trans (le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (le_succ_of_le (le_max_right _ _)) end } end end a open nat finset lemma complex.exp_series_abs_cau (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, complex.abs (z ^ m / fact m))) := begin cases exists_nat_gt (complex.abs z) with n hn, have n_pos : (0 : ℝ) < n := lt_of_le_of_lt (complex.abs_nonneg _) hn, refine series_ratio_test n (complex.abs z / n) _ _ _,exact div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) n_pos,rwa [div_lt_iff n_pos,one_mul], assume m mn,rw [abs_of_nonneg (complex.abs_nonneg _),abs_of_nonneg (complex.abs_nonneg _)], unfold fact,simp only [_root_.pow_succ, complex.abs_div,complex.abs_mul,div_eq_mul_inv,mul_inv', nat.cast_mul,complex.abs_inv], have : complex.abs z * complex.abs (z ^ m) * ((complex.abs ↑(fact m))⁻¹ * (complex.abs ↑(succ m))⁻¹) = complex.abs z * complex.abs (z ^ m) * (complex.abs ↑(fact m))⁻¹ * (complex.abs ↑(succ m))⁻¹,ring,rw this, have : complex.abs z * (↑n)⁻¹ * (complex.abs (z ^ m) * (complex.abs ↑(fact m))⁻¹) = complex.abs z * complex.abs (z ^ m) * (complex.abs ↑(fact m))⁻¹ * (↑n)⁻¹,ring, rw this, rw[(by simp : (succ m : ℂ) = ((succ m : ℝ) : ℂ)),complex.abs_of_nonneg], refine mul_le_mul_of_nonneg_left _ _, rw [inv_le_inv,nat.cast_le],exact le_succ_of_le mn, rw [←nat.cast_zero,nat.cast_lt],exact succ_pos _,exact n_pos,rw[←complex.abs_inv,←complex.abs_mul,←complex.abs_mul], exact complex.abs_nonneg _,rw[←nat.cast_zero,nat.cast_le],exact zero_le _, end lemma complex.exp_series_cau (z : ℂ) : is_cau_seq complex.abs (λ n, (range n).sum (λ m, z ^ m / fact m)) := series_cau_of_abv_cau (complex.exp_series_abs_cau z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨_, complex.exp_series_cau z⟩ open complex def exp (z : ℂ) : ℂ := complex.lim (exp' z) def sin (z : ℂ) : ℂ := (exp (I * z) - exp (-I * z)) / (2 * I) def cos (z : ℂ) : ℂ := (exp (I * z) + exp (-I * z)) / 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 @[simp] lemma exp_zero : exp 0 = 1 := begin unfold exp exp', refine lim_eq_of_equiv_const _, assume ε ε0, existsi 1, assume j hj, dsimp [exp'], suffices : complex.abs (sum (range j) (λ (m : ℕ), 0 ^ m / ↑(fact m)) + -1) = 0, rwa this, cases j, { exact absurd hj (by norm_num) }, { induction j, { simpa }, { rw ← j_ih dec_trivial, simp only [sum_range_succ, _root_.pow_succ], simp } } end lemma exp_add (x y : ℂ) : exp (x + y) = exp x * exp y := show complex.lim (⟨_, complex.exp_series_cau (x + y)⟩ : cau_seq ℂ abs) = complex.lim ⇑(show cau_seq ℂ abs, from ⟨_, complex.exp_series_cau x⟩) * complex.lim (show cau_seq ℂ abs, from ⟨_, complex.exp_series_cau y⟩), begin have hxa := complex.exp_series_abs_cau x, have hx := complex.exp_series_cau x, have hy := complex.exp_series_cau y, have hxy := complex.exp_series_cau (x + y), rw complex.lim_mul_lim, have hj : ∀ j : ℕ, (range j).sum (λ (m : ℕ), (x + y) ^ m / ↑(fact m)) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / fact k * (y ^ (i - k) / fact (i - k)))), { assume j, refine finset.sum_congr rfl (λ m hm, _), rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have := choose_mul_fact_mul_fact (le_of_lt_succ $ finset.mem_range.1 hi), rw [← this, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (choose m i : ℂ), mul_assoc, mul_left_comm (choose m i : ℂ)⁻¹, mul_comm (choose m i : ℂ)], have : (choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (λ h, by have := choose_pos (le_of_lt_succ (mem_range.1 hi)); simpa [h, lt_irrefl] using this), rw inv_mul_cancel this, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] }, have hf := funext hj, have hxy1 := hxy, rw hf at hxy1, have := series_cauchy_prod hxa hy, refine eq.symm (lim_eq_lim_of_equiv _), assume ε ε0, dsimp, simp only [hj], exact this ε ε0, end
180262fbe5c6dc158602ca267967f126a158f130
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Util/ForEachExpr.lean
7221b7f9fd99aefeff91ee5f97039762c3de8add
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,453
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr import Lean.Util.MonadCache namespace Lean /- Remark: we cannot use the caching trick used at `FindExpr` and `ReplaceExpr` because they may visit the same expression multiple times if they are stored in different memory addresses. Note that the following code is parametric in a monad `m`. -/ variables {ω : Type} {m : Type → Type} [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] namespace ForEachExpr @[specialize] partial def visit (f : Expr → m Bool) : Expr → MonadCacheT Expr Unit m Unit | e => checkCache e fun e => condM (not <$> liftM (f e)) (pure ()) do match e with | Expr.forallE _ d b _ => do visit d; visit b | Expr.lam _ d b _ => do visit d; visit b | Expr.letE _ t v b _ => do visit t; visit v; visit b | Expr.app f a _ => do visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | _ => pure () end ForEachExpr /-- Apply `f` to each sub-expression of `e`. If `f t` return true, then t's children are not visited. -/ @[inline] def Expr.forEach' (e : Expr) (f : Expr → m Bool) : m Unit := (ForEachExpr.visit f e).run @[inline] def Expr.forEach (e : Expr) (f : Expr → m Unit) : m Unit := e.forEach' fun e => do f e; pure true end Lean
b292703d649948071bdec0380367ebf09fd232d1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/conditionally_complete_lattice.lean
679c79d02b05b17f00667158a7e7a024674ff498
[ "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
53,221
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import order.bounds import data.set.intervals.basic import data.set.finite import data.set.lattice /-! # Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ set_option old_structure_cmd true open function order_dual set variables {α β γ : Type*} {ι : Sort*} section /-! Extension of Sup and Inf from a preorder `α` to `with_top α` and `with_bot α` -/ open_locale classical noncomputable instance {α : Type*} [preorder α] [has_Sup α] : has_Sup (with_top α) := ⟨λ S, if ⊤ ∈ S then ⊤ else if bdd_above (coe ⁻¹' S : set α) then ↑(Sup (coe ⁻¹' S : set α)) else ⊤⟩ noncomputable instance {α : Type*} [has_Inf α] : has_Inf (with_top α) := ⟨λ S, if S ⊆ {⊤} then ⊤ else ↑(Inf (coe ⁻¹' S : set α))⟩ noncomputable instance {α : Type*} [has_Sup α] : has_Sup (with_bot α) := ⟨(@with_top.has_Inf αᵒᵈ _).Inf⟩ noncomputable instance {α : Type*} [preorder α] [has_Inf α] : has_Inf (with_bot α) := ⟨(@with_top.has_Sup αᵒᵈ _ _).Sup⟩ @[simp] theorem with_top.cInf_empty {α : Type*} [has_Inf α] : Inf (∅ : set (with_top α)) = ⊤ := if_pos $ set.empty_subset _ @[simp] theorem with_top.cinfi_empty {α : Type*} [is_empty ι] [has_Inf α] (f : ι → with_top α) : (⨅ i, f i) = ⊤ := by rw [infi, range_eq_empty, with_top.cInf_empty] lemma with_top.coe_Inf' [has_Inf α] {s : set α} (hs : s.nonempty) : ↑(Inf s) = (Inf (coe '' s) : with_top α) := begin obtain ⟨x, hx⟩ := hs, change _ = ite _ _ _, split_ifs, { cases h (mem_image_of_mem _ hx) }, { rw preimage_image_eq, exact option.some_injective _ }, end @[norm_cast] lemma with_top.coe_infi [nonempty ι] [has_Inf α] (f : ι → α) : ↑(⨅ i, f i) = (⨅ i, f i : with_top α) := by rw [infi, infi, with_top.coe_Inf' (range_nonempty f), range_comp] theorem with_top.coe_Sup' [preorder α] [has_Sup α] {s : set α} (hs : bdd_above s) : ↑(Sup s) = (Sup (coe '' s) : with_top α) := begin change _ = ite _ _ _, rw [if_neg, preimage_image_eq, if_pos hs], { exact option.some_injective _ }, { rintro ⟨x, h, ⟨⟩⟩ }, end @[norm_cast] lemma with_top.coe_supr [preorder α] [has_Sup α] (f : ι → α) (h : bdd_above (set.range f)) : ↑(⨆ i, f i) = (⨆ i, f i : with_top α) := by rw [supr, supr, with_top.coe_Sup' h, range_comp] @[simp] theorem with_bot.cSup_empty {α : Type*} [has_Sup α] : Sup (∅ : set (with_bot α)) = ⊥ := if_pos $ set.empty_subset _ @[simp] theorem with_bot.csupr_empty {α : Type*} [is_empty ι] [has_Sup α] (f : ι → with_bot α) : (⨆ i, f i) = ⊥ := @with_top.cinfi_empty _ αᵒᵈ _ _ _ @[norm_cast] lemma with_bot.coe_Sup' [has_Sup α] {s : set α} (hs : s.nonempty) : ↑(Sup s) = (Sup (coe '' s) : with_bot α) := @with_top.coe_Inf' αᵒᵈ _ _ hs @[norm_cast] lemma with_bot.coe_supr [nonempty ι] [has_Sup α] (f : ι → α) : ↑(⨆ i, f i) = (⨆ i, f i : with_bot α) := @with_top.coe_infi αᵒᵈ _ _ _ _ @[norm_cast] theorem with_bot.coe_Inf' [preorder α] [has_Inf α] {s : set α} (hs : bdd_below s) : ↑(Inf s) = (Inf (coe '' s) : with_bot α) := @with_top.coe_Sup' αᵒᵈ _ _ _ hs @[norm_cast] lemma with_bot.coe_infi [preorder α] [has_Inf α] (f : ι → α) (h : bdd_below (set.range f)) : ↑(⨅ i, f i) = (⨅ i, f i : with_bot α) := @with_top.coe_supr αᵒᵈ _ _ _ _ h end -- section /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (α : Type*) extends lattice α, has_Sup α, has_Inf α := (le_cSup : ∀ s a, bdd_above s → a ∈ s → a ≤ Sup s) (cSup_le : ∀ s a, set.nonempty s → a ∈ upper_bounds s → Sup s ≤ a) (cInf_le : ∀ s a, bdd_below s → a ∈ s → Inf s ≤ a) (le_cInf : ∀ s a, set.nonempty s → a ∈ lower_bounds s → a ≤ Inf s) /-- A conditionally complete linear order is a linear order in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_linear_order (α : Type*) extends conditionally_complete_lattice α, linear_order α renaming max → sup min → inf /-- A conditionally complete linear order with `bot` is a linear order with least element, in which every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily bounded below) has an infimum. A typical example is the natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ @[ancestor conditionally_complete_linear_order has_bot] class conditionally_complete_linear_order_bot (α : Type*) extends conditionally_complete_linear_order α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (cSup_empty : Sup ∅ = ⊥) @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_bot.to_order_bot [h : conditionally_complete_linear_order_bot α] : order_bot α := { ..h } /-- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance complete_lattice.to_conditionally_complete_lattice [complete_lattice α] : conditionally_complete_lattice α := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..‹complete_lattice α› } @[priority 100] -- see Note [lower instance priority] instance complete_linear_order.to_conditionally_complete_linear_order_bot {α : Type*} [complete_linear_order α] : conditionally_complete_linear_order_bot α := { cSup_empty := Sup_empty, ..complete_lattice.to_conditionally_complete_lattice, .. ‹complete_linear_order α› } section open_locale classical /-- A well founded linear order is conditionally complete, with a bottom element. -/ @[reducible] noncomputable def is_well_order.conditionally_complete_linear_order_bot (α : Type*) [i₁ : linear_order α] [i₂ : order_bot α] [h : is_well_order α (<)] : conditionally_complete_linear_order_bot α := { Inf := λ s, if hs : s.nonempty then h.wf.min s hs else ⊥, cInf_le := λ s a hs has, begin have s_ne : s.nonempty := ⟨a, has⟩, simpa [s_ne] using not_lt.1 (h.wf.not_lt_min s s_ne has), end, le_cInf := λ s a hs has, begin simp only [hs, dif_pos], exact has (h.wf.min_mem s hs), end, Sup := λ s, if hs : (upper_bounds s).nonempty then h.wf.min _ hs else ⊥, le_cSup := λ s a hs has, begin have h's : (upper_bounds s).nonempty := hs, simp only [h's, dif_pos], exact h.wf.min_mem _ h's has, end, cSup_le := λ s a hs has, begin have h's : (upper_bounds s).nonempty := ⟨a, has⟩, simp only [h's, dif_pos], simpa using h.wf.not_lt_min _ h's has, end, cSup_empty := by simpa using eq_bot_iff.2 (not_lt.1 $ h.wf.not_lt_min _ _ $ mem_univ ⊥), ..i₁, ..i₂, ..linear_order.to_lattice } end section order_dual instance (α : Type*) [conditionally_complete_lattice α] : conditionally_complete_lattice αᵒᵈ := { le_cSup := @conditionally_complete_lattice.cInf_le α _, cSup_le := @conditionally_complete_lattice.le_cInf α _, le_cInf := @conditionally_complete_lattice.cSup_le α _, cInf_le := @conditionally_complete_lattice.le_cSup α _, ..order_dual.has_Inf α, ..order_dual.has_Sup α, ..order_dual.lattice α } instance (α : Type*) [conditionally_complete_linear_order α] : conditionally_complete_linear_order αᵒᵈ := { ..order_dual.conditionally_complete_lattice α, ..order_dual.linear_order α } end order_dual section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s := conditionally_complete_lattice.le_cSup s a h₁ h₂ theorem cSup_le (h₁ : s.nonempty) (h₂ : ∀ b ∈ s, b ≤ a) : Sup s ≤ a := conditionally_complete_lattice.cSup_le s a h₁ h₂ theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a := conditionally_complete_lattice.cInf_le s a h₁ h₂ theorem le_cInf (h₁ : s.nonempty) (h₂ : ∀ b ∈ s, a ≤ b) : a ≤ Inf s := conditionally_complete_lattice.le_cInf s a h₁ h₂ theorem le_cSup_of_le (hs : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_cSup hs hb) theorem cInf_le_of_le (hs : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (cInf_le hs hb) h theorem cSup_le_cSup (ht : bdd_above t) (hs : s.nonempty) (h : s ⊆ t) : Sup s ≤ Sup t := cSup_le hs (λ a ha, le_cSup ht (h ha)) theorem cInf_le_cInf (ht : bdd_below t) (hs : s.nonempty) (h : s ⊆ t) : Inf t ≤ Inf s := le_cInf hs (λ a ha, cInf_le ht (h ha)) theorem le_cSup_iff (h : bdd_above s) (hs : s.nonempty) : a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b := ⟨λ h b hb, le_trans h (cSup_le hs hb), λ hb, hb _ (λ x, le_cSup h)⟩ theorem cInf_le_iff (h : bdd_below s) (hs : s.nonempty) : Inf s ≤ a ↔ ∀ b ∈ lower_bounds s, b ≤ a := ⟨λ h b hb, le_trans (le_cInf hs hb) h, λ hb, hb _ (λ x, cInf_le h)⟩ lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨λ x, le_cSup H, λ x, cSup_le ne⟩ lemma is_lub_csupr [nonempty ι] {f : ι → α} (H : bdd_above (range f)) : is_lub (range f) (⨆ i, f i) := is_lub_cSup (range_nonempty f) H lemma is_lub_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) (Hne : s.nonempty) : is_lub (f '' s) (⨆ i : s, f i) := by { rw ← Sup_image', exact is_lub_cSup (Hne.image _) H } lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨λ x, cInf_le H, λ x, le_cInf ne⟩ lemma is_glb_cinfi [nonempty ι] {f : ι → α} (H : bdd_below (range f)) : is_glb (range f) (⨅ i, f i) := is_glb_cInf (range_nonempty f) H lemma is_glb_cinfi_set {f : β → α} {s : set β} (H : bdd_below (f '' s)) (Hne : s.nonempty) : is_glb (f '' s) (⨅ i : s, f i) := @is_lub_csupr_set αᵒᵈ _ _ _ _ H Hne lemma csupr_le_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_above (range f)) : supr f ≤ a ↔ ∀ i, f i ≤ a := (is_lub_le_iff $ is_lub_csupr hf).trans forall_range_iff lemma le_cinfi_iff [nonempty ι] {f : ι → α} {a : α} (hf : bdd_below (range f)) : a ≤ infi f ↔ ∀ i, a ≤ f i := (le_is_glb_iff $ is_glb_cinfi hf).trans forall_range_iff lemma csupr_set_le_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty) (hf : bdd_above (f '' s)) : (⨆ i : s, f i) ≤ a ↔ ∀ i ∈ s, f i ≤ a := (is_lub_le_iff $ is_lub_csupr_set hf hs).trans ball_image_iff lemma le_cinfi_set_iff {ι : Type*} {s : set ι} {f : ι → α} {a : α} (hs : s.nonempty) (hf : bdd_below (f '' s)) : a ≤ (⨅ i : s, f i) ↔ ∀ i ∈ s, a ≤ f i := (le_is_glb_iff $ is_glb_cinfi_set hf hs).trans ball_image_iff lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H lemma is_lub.csupr_eq [nonempty ι] {f : ι → α} (H : is_lub (range f) a) : (⨆ i, f i) = a := H.cSup_eq (range_nonempty f) lemma is_lub.csupr_set_eq {s : set β} {f : β → α} (H : is_lub (f '' s) a) (Hne : s.nonempty) : (⨆ i : s, f i) = a := is_lub.cSup_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f) /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_greatest.Sup_mem (H : is_greatest s a) : Sup s ∈ s := H.cSup_eq.symm ▸ H.1 lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H lemma is_glb.cinfi_eq [nonempty ι] {f : ι → α} (H : is_glb (range f) a) : (⨅ i, f i) = a := H.cInf_eq (range_nonempty f) lemma is_glb.cinfi_set_eq {s : set β} {f : β → α} (H : is_glb (f '' s) a) (Hne : s.nonempty) : (⨅ i : s, f i) = a := is_glb.cInf_eq (image_eq_range f s ▸ H) (image_eq_range f s ▸ Hne.image f) /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty lemma is_least.Inf_mem (H : is_least s a) : Inf s ∈ s := H.cInf_eq.symm ▸ H.1 lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) : s ⊆ Icc (Inf s) (Sup s) := λ x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩ theorem cSup_le_iff (hb : bdd_above s) (hs : s.nonempty) : Sup s ≤ a ↔ ∀ b ∈ s, b ≤ a := is_lub_le_iff (is_lub_cSup hs hb) theorem le_cInf_iff (hb : bdd_below s) (hs : s.nonempty) : a ≤ Inf s ↔ ∀ b ∈ s, a ≤ b := le_is_glb_iff (is_glb_cInf hs hb) lemma cSup_lower_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ λ x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ λ x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb lemma not_mem_of_lt_cInf {x : α} {s : set α} (h : x < Inf s) (hs : bdd_below s) : x ∉ s := λ hx, lt_irrefl _ (h.trans_le (cInf_le hs hx)) lemma not_mem_of_cSup_lt {x : α} {s : set α} (h : Sup s < x) (hs : bdd_above s) : x ∉ s := @not_mem_of_lt_cInf αᵒᵈ _ x s h hs /--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b` is larger than all elements of `s`, and that this is not the case of any `w<b`. See `Sup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem cSup_eq_of_forall_le_of_forall_lt_exists_gt (hs : s.nonempty) (H : ∀ a ∈ s, a ≤ b) (H' : ∀ w, w < b → ∃ a ∈ s, w < a) : Sup s = b := eq_of_le_of_not_lt (cSup_le hs H) $ λ hb, let ⟨a, ha, ha'⟩ := H' _ hb in lt_irrefl _ $ ha'.trans_le $ le_cSup ⟨b, H⟩ ha /--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b` is smaller than all elements of `s`, and that this is not the case of any `w>b`. See `Inf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cInf_eq_of_forall_ge_of_forall_gt_exists_lt : s.nonempty → (∀ a ∈ s, b ≤ a) → (∀ w, b < w → ∃ a ∈ s, a < w) → Inf s = b := @cSup_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (hs : bdd_above s) (ha : a ∈ s) (h : b < a) : b < Sup s := lt_of_lt_of_le h (le_cSup hs ha) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt : bdd_below s → a ∈ s → a < b → Inf s < b := @lt_cSup_of_lt αᵒᵈ _ _ _ _ /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : ∀ (x ∈ s) (y ∈ t), x ≤ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, λ x hx, le_cInf tne $ hst x hx, λ y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : α) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : α) : Inf {a} = a := is_least_singleton.cInf_eq @[simp] theorem cSup_pair (a b : α) : Sup {a, b} = a ⊔ b := (@is_lub_pair _ _ a b).cSup_eq (insert_nonempty _ _) @[simp] theorem cInf_pair (a b : α) : Inf {a, b} = a ⊓ b := (@is_glb_pair _ _ a b).cInf_eq (insert_nonempty _ _) /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s ∪ t) = Inf s ⊓ Inf t := @cSup_union αᵒᵈ _ _ _ hs sne ht tne /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (hs : bdd_above s) (ht : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := cSup_le hst $ λ x hx, le_inf (le_cSup hs hx.1) (le_cSup ht hx.2) /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter : bdd_below s → bdd_below t → (s ∩ t).nonempty → Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @cSup_inter_le αᵒᵈ _ _ _ /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a ⊔ Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a ⊓ Inf s := @cSup_insert αᵒᵈ _ _ _ hs sne @[simp] lemma cInf_Icc (h : a ≤ b) : Inf (Icc a b) = a := (is_glb_Icc h).cInf_eq (nonempty_Icc.2 h) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cInf_Ico (h : a < b) : Inf (Ico a b) = a := (is_glb_Ico h).cInf_eq (nonempty_Ico.2 h) @[simp] lemma cInf_Ioc [densely_ordered α] (h : a < b) : Inf (Ioc a b) = a := (is_glb_Ioc h).cInf_eq (nonempty_Ioc.2 h) @[simp] lemma cInf_Ioi [no_max_order α] [densely_ordered α] : Inf (Ioi a) = a := cInf_eq_of_forall_ge_of_forall_gt_exists_lt nonempty_Ioi (λ _, le_of_lt) (λ w hw, by simpa using exists_between hw) @[simp] lemma cInf_Ioo [densely_ordered α] (h : a < b) : Inf (Ioo a b) = a := (is_glb_Ioo h).cInf_eq (nonempty_Ioo.2 h) @[simp] lemma cSup_Icc (h : a ≤ b) : Sup (Icc a b) = b := (is_lub_Icc h).cSup_eq (nonempty_Icc.2 h) @[simp] lemma cSup_Ico [densely_ordered α] (h : a < b) : Sup (Ico a b) = b := (is_lub_Ico h).cSup_eq (nonempty_Ico.2 h) @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq @[simp] lemma cSup_Iio [no_min_order α] [densely_ordered α] : Sup (Iio a) = a := cSup_eq_of_forall_le_of_forall_lt_exists_gt nonempty_Iio (λ _, le_of_lt) (λ w hw, by simpa [and_comm] using exists_between hw) @[simp] lemma cSup_Ioc (h : a < b) : Sup (Ioc a b) = b := (is_lub_Ioc h).cSup_eq (nonempty_Ioc.2 h) @[simp] lemma cSup_Ioo [densely_ordered α] (h : a < b) : Sup (Ioo a b) = b := (is_lub_Ioo h).cSup_eq (nonempty_Ioo.2 h) /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, f x ≤ c) : supr f ≤ c := cSup_le (range_nonempty f) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : ι → α} (H : bdd_above (range f)) (c : ι) : f c ≤ supr f := le_cSup H (mem_range_self _) lemma le_csupr_of_le {f : ι → α} (H : bdd_above (range f)) (c : ι) (h : a ≤ f c) : a ≤ supr f := le_trans h (le_csupr H c) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_mono {f g : ι → α} (B : bdd_above (range g)) (H : ∀ x, f x ≤ g x) : supr f ≤ supr g := begin casesI is_empty_or_nonempty ι, { rw [supr_of_empty', supr_of_empty'] }, { exact csupr_le (λ x, le_csupr_of_le B x (H x)) }, end lemma le_csupr_set {f : β → α} {s : set β} (H : bdd_above (f '' s)) {c : β} (hc : c ∈ s) : f c ≤ ⨆ i : s, f i := (le_cSup H $ mem_image_of_mem f hc).trans_eq Sup_image' /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_mono {f g : ι → α} (B : bdd_below (range f)) (H : ∀ x, f x ≤ g x) : infi f ≤ infi g := @csupr_mono αᵒᵈ _ _ _ _ B H /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ι] {f : ι → α} {c : α} (H : ∀ x, c ≤ f x) : c ≤ infi f := @csupr_le αᵒᵈ _ _ _ _ _ H /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : ι → α} (H : bdd_below (range f)) (c : ι) : infi f ≤ f c := @le_csupr αᵒᵈ _ _ _ H c lemma cinfi_le_of_le {f : ι → α} (H : bdd_below (range f)) (c : ι) (h : f c ≤ a) : infi f ≤ a := @le_csupr_of_le αᵒᵈ _ _ _ _ H c h lemma cinfi_set_le {f : β → α} {s : set β} (H : bdd_below (f '' s)) {c : β} (hc : c ∈ s) : (⨅ i : s, f i) ≤ f c := @le_csupr_set αᵒᵈ _ _ _ _ H _ hc @[simp] theorem csupr_const [hι : nonempty ι] {a : α} : (⨆ b : ι, a) = a := by rw [supr, range_const, cSup_singleton] @[simp] theorem cinfi_const [hι : nonempty ι] {a : α} : (⨅ b:ι, a) = a := @csupr_const αᵒᵈ _ _ _ _ @[simp] theorem supr_unique [unique ι] {s : ι → α} : (⨆ i, s i) = s default := have ∀ i, s i = s default := λ i, congr_arg s (unique.eq_default i), by simp only [this, csupr_const] @[simp] theorem infi_unique [unique ι] {s : ι → α} : (⨅ i, s i) = s default := @supr_unique αᵒᵈ _ _ _ _ @[simp] lemma csupr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := by haveI := unique_prop hp; exact supr_unique @[simp] lemma cinfi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := @csupr_pos αᵒᵈ _ _ _ hp /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `supr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem csupr_eq_of_forall_le_of_forall_lt_exists_gt [nonempty ι] {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := cSup_eq_of_forall_le_of_forall_lt_exists_gt (range_nonempty f) (forall_range_iff.mpr h₁) (λ w hw, exists_range_iff.mpr $ h₂ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `infi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cinfi_eq_of_forall_ge_of_forall_gt_exists_lt [nonempty ι] {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @csupr_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ _ ‹_› ‹_› ‹_› /-- Nested intervals lemma: if `f` is a monotone sequence, `g` is an antitone sequence, and `f n ≤ g n` for all `n`, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma monotone.csupr_mem_Inter_Icc_of_antitone [semilattice_sup β] {f g : β → α} (hf : monotone f) (hg : antitone g) (h : f ≤ g) : (⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) := begin refine mem_Inter.2 (λ n, _), haveI : nonempty β := ⟨n⟩, have : ∀ m, f m ≤ g n := λ m, hf.forall_le_of_antitone hg h m n, exact ⟨le_csupr ⟨g $ n, forall_range_iff.2 this⟩ _, csupr_le this⟩ end /-- Nested intervals lemma: if `[f n, g n]` is an antitone sequence of nonempty closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma csupr_mem_Inter_Icc_of_antitone_Icc [semilattice_sup β] {f g : β → α} (h : antitone (λ n, Icc (f n) (g n))) (h' : ∀ n, f n ≤ g n) : (⨆ n, f n) ∈ ⋂ n, Icc (f n) (g n) := monotone.csupr_mem_Inter_Icc_of_antitone (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1) (λ m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h' lemma finset.nonempty.sup'_eq_cSup_image {s : finset β} (hs : s.nonempty) (f : β → α) : s.sup' hs f = Sup (f '' s) := eq_of_forall_ge_iff $ λ a, by simp [cSup_le_iff (s.finite_to_set.image f).bdd_above (hs.to_set.image f)] lemma finset.nonempty.sup'_id_eq_cSup {s : finset α} (hs : s.nonempty) : s.sup' hs id = Sup s := by rw [hs.sup'_eq_cSup_image, image_id] /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≤ b'.-/ theorem cSup_eq_of_is_forall_le_of_forall_le_imp_ge (hs : s.nonempty) (h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b := (cSup_le hs h_is_ub).antisymm (h_b_le_ub _ $ λ a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_lattice instance pi.conditionally_complete_lattice {ι : Type*} {α : Π i : ι, Type*} [Π i, conditionally_complete_lattice (α i)] : conditionally_complete_lattice (Π i, α i) := { le_cSup := λ s f ⟨g, hg⟩ hf i, le_cSup ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, cSup_le := λ s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $ λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i, cInf_le := λ s f ⟨g, hg⟩ hf i, cInf_le ⟨g i, set.forall_range_iff.2 $ λ ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, le_cInf := λ s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $ λ b ⟨⟨g, hg⟩, hb⟩, hb ▸ hf hg i, .. pi.lattice, .. pi.has_Sup, .. pi.has_Inf } section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} lemma finset.nonempty.cSup_eq_max' {s : finset α} (h : s.nonempty) : Sup ↑s = s.max' h := eq_of_forall_ge_iff $ λ a, (cSup_le_iff s.bdd_above h.to_set).trans (s.max'_le_iff h).symm lemma finset.nonempty.cInf_eq_min' {s : finset α} (h : s.nonempty) : Inf ↑s = s.min' h := @finset.nonempty.cSup_eq_max' αᵒᵈ _ s h lemma finset.nonempty.cSup_mem {s : finset α} (h : s.nonempty) : Sup (s : set α) ∈ s := by { rw h.cSup_eq_max', exact s.max'_mem _ } lemma finset.nonempty.cInf_mem {s : finset α} (h : s.nonempty) : Inf (s : set α) ∈ s := @finset.nonempty.cSup_mem αᵒᵈ _ _ h lemma set.nonempty.cSup_mem (h : s.nonempty) (hs : s.finite) : Sup s ∈ s := by { lift s to finset α using hs, exact finset.nonempty.cSup_mem h } lemma set.nonempty.cInf_mem (h : s.nonempty) (hs : s.finite) : Inf s ∈ s := @set.nonempty.cSup_mem αᵒᵈ _ _ h hs lemma set.finite.cSup_lt_iff (hs : s.finite) (h : s.nonempty) : Sup s < a ↔ ∀ x ∈ s, x < a := ⟨λ h x hx, (le_cSup hs.bdd_above hx).trans_lt h, λ H, H _ $ h.cSup_mem hs⟩ lemma set.finite.lt_cInf_iff (hs : s.finite) (h : s.nonempty) : a < Inf s ↔ ∀ x ∈ s, a < x := @set.finite.cSup_lt_iff αᵒᵈ _ _ _ hs h /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : ∃ a ∈ s, b < a := by { contrapose! hb, exact cSup_le hs hb } /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr [nonempty ι] {f : ι → α} (h : b < supr f) : ∃ i, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : ∃ a ∈ s, a < b := @exists_lt_of_lt_cSup αᵒᵈ _ _ _ hs hb /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt [nonempty ι] {f : ι → α} (h : infi f < a) : ∃ i, f i < a := @exists_lt_of_lt_csupr αᵒᵈ _ _ _ _ _ h open function variables [is_well_order α (<)] lemma Inf_eq_argmin_on (hs : s.nonempty) : Inf s = argmin_on id (@is_well_founded.wf α (<) _) s hs := is_least.cInf_eq ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ lemma is_least_Inf (hs : s.nonempty) : is_least s (Inf s) := by { rw Inf_eq_argmin_on hs, exact ⟨argmin_on_mem _ _ _ _, λ a ha, argmin_on_le id _ _ ha⟩ } lemma le_cInf_iff' (hs : s.nonempty) : b ≤ Inf s ↔ b ∈ lower_bounds s := le_is_glb_iff (is_least_Inf hs).is_glb lemma Inf_mem (hs : s.nonempty) : Inf s ∈ s := (is_least_Inf hs).1 lemma infi_mem [nonempty ι] (f : ι → α) : infi f ∈ range f := Inf_mem (range_nonempty f) lemma monotone_on.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone_on f s) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := (hf.map_is_least (is_least_Inf hs)).cInf_eq.symm lemma monotone.map_Inf {β : Type*} [conditionally_complete_lattice β] {f : α → β} (hf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := (hf.map_is_least (is_least_Inf hs)).cInf_eq.symm end conditionally_complete_linear_order /-! ### Lemmas about a conditionally complete linear order with bottom element In this case we have `Sup ∅ = ⊥`, so we can drop some `nonempty`/`set.nonempty` assumptions. -/ section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot α] @[simp] lemma cSup_empty : (Sup ∅ : α) = ⊥ := conditionally_complete_linear_order_bot.cSup_empty @[simp] lemma csupr_of_empty [is_empty ι] (f : ι → α) : (⨆ i, f i) = ⊥ := by rw [supr_of_empty', cSup_empty] @[simp] lemma csupr_false (f : false → α) : (⨆ i, f i) = ⊥ := csupr_of_empty f @[simp] lemma cInf_univ : Inf (univ : set α) = ⊥ := is_least_univ.cInf_eq lemma is_lub_cSup' {s : set α} (hs : bdd_above s) : is_lub s (Sup s) := begin rcases eq_empty_or_nonempty s with (rfl|hne), { simp only [cSup_empty, is_lub_empty] }, { exact is_lub_cSup hne hs } end lemma cSup_le_iff' {s : set α} (hs : bdd_above s) {a : α} : Sup s ≤ a ↔ ∀ x ∈ s, x ≤ a := is_lub_le_iff (is_lub_cSup' hs) lemma cSup_le' {s : set α} {a : α} (h : a ∈ upper_bounds s) : Sup s ≤ a := (cSup_le_iff' ⟨a, h⟩).2 h theorem le_cSup_iff' {s : set α} {a : α} (h : bdd_above s) : a ≤ Sup s ↔ ∀ b, b ∈ upper_bounds s → a ≤ b := ⟨λ h b hb, le_trans h (cSup_le' hb), λ hb, hb _ (λ x, le_cSup h)⟩ lemma le_csupr_iff' {s : ι → α} {a : α} (h : bdd_above (range s)) : a ≤ supr s ↔ ∀ b, (∀ i, s i ≤ b) → a ≤ b := by simp [supr, h, le_cSup_iff', upper_bounds] theorem le_cInf_iff'' {s : set α} {a : α} (ne : s.nonempty) : a ≤ Inf s ↔ ∀ (b : α), b ∈ s → a ≤ b := le_cInf_iff ⟨⊥, λ a _, bot_le⟩ ne theorem le_cinfi_iff' [nonempty ι] {f : ι → α} {a : α} : a ≤ infi f ↔ ∀ i, a ≤ f i := le_cinfi_iff ⟨⊥, λ a _, bot_le⟩ theorem cInf_le' {s : set α} {a : α} (h : a ∈ s) : Inf s ≤ a := cInf_le ⟨⊥, λ a _, bot_le⟩ h theorem cinfi_le' (f : ι → α) (i : ι) : infi f ≤ f i := cinfi_le ⟨⊥, λ a _, bot_le⟩ _ lemma exists_lt_of_lt_cSup' {s : set α} {a : α} (h : a < Sup s) : ∃ b ∈ s, a < b := by { contrapose! h, exact cSup_le' h } lemma csupr_le_iff' {f : ι → α} (h : bdd_above (range f)) {a : α} : (⨆ i, f i) ≤ a ↔ ∀ i, f i ≤ a := (cSup_le_iff' h).trans forall_range_iff lemma csupr_le' {f : ι → α} {a : α} (h : ∀ i, f i ≤ a) : (⨆ i, f i) ≤ a := cSup_le' $ forall_range_iff.2 h lemma exists_lt_of_lt_csupr' {f : ι → α} {a : α} (h : a < ⨆ i, f i) : ∃ i, a < f i := by { contrapose! h, exact csupr_le' h } lemma csupr_mono' {ι'} {f : ι → α} {g : ι' → α} (hg : bdd_above (range g)) (h : ∀ i, ∃ i', f i ≤ g i') : supr f ≤ supr g := csupr_le' $ λ i, exists.elim (h i) (le_csupr_of_le hg) lemma cInf_le_cInf' {s t : set α} (h₁ : t.nonempty) (h₂ : t ⊆ s) : Inf s ≤ Inf t := cInf_le_cInf (order_bot.bdd_below s) h₁ h₂ end conditionally_complete_linear_order_bot namespace with_top open_locale classical variables [conditionally_complete_linear_order_bot α] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : s.nonempty) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact le_rfl }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact le_rfl }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, show is_lub ∅ (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use ⊥, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {β : Type*} [conditionally_complete_lattice β] {s : set (with_top β)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊤ }, { exact (h ⟨a, ha⟩).elim }}, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use ⊥, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top α) := { Sup := Sup, le_Sup := λ s, (is_lub_Sup s).1, Sup_le := λ s, (is_lub_Sup s).2, Inf := Inf, le_Inf := λ s, (is_glb_Inf s).2, Inf_le := λ s, (is_glb_Inf s).1, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } /-- A version of `with_top.coe_Sup'` with a more convenient but less general statement. -/ @[norm_cast] lemma coe_Sup {s : set α} (hb : bdd_above s) : ↑(Sup s) = (⨆ a ∈ s, ↑a : with_top α) := by rw [coe_Sup' hb, Sup_image] /-- A version of `with_top.coe_Inf'` with a more convenient but less general statement. -/ @[norm_cast] lemma coe_Inf {s : set α} (hs : s.nonempty) : ↑(Inf s) = (⨅ a ∈ s, ↑a : with_top α) := by rw [coe_Inf' hs, Inf_image] end with_top namespace monotone variables [preorder α] [conditionally_complete_lattice β] {f : α → β} (h_mono : monotone f) /-! A monotone function into a conditionally complete lattice preserves the ordering properties of `Sup` and `Inf`. -/ lemma le_cSup_image {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_above s) : f c ≤ Sup (f '' s) := le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs) lemma cSup_image_le {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ upper_bounds s) : Sup (f '' s) ≤ f B := cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB) lemma cInf_image_le {s : set α} {c : α} (hcs : c ∈ s) (h_bdd : bdd_below s) : Inf (f '' s) ≤ f c := @le_cSup_image αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ _ hcs h_bdd lemma le_cInf_image {s : set α} (hs : s.nonempty) {B : α} (hB: B ∈ lower_bounds s) : f B ≤ Inf (f '' s) := @cSup_image_le αᵒᵈ βᵒᵈ _ _ _ (λ x y hxy, h_mono hxy) _ hs _ hB end monotone namespace galois_connection variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] {l : α → β} {u : β → α} lemma l_cSup (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = ⨆ x : s, l x := eq.symm $ is_lub.csupr_set_eq (gc.is_lub_l_image $ is_lub_cSup hne hbdd) hne lemma l_cSup' (gc : galois_connection l u) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = Sup (l '' s) := by rw [gc.l_cSup hne hbdd, Sup_image'] lemma l_csupr (gc : galois_connection l u) {f : ι → α} (hf : bdd_above (range f)) : l (⨆ i, f i) = ⨆ i, l (f i) := by rw [supr, gc.l_cSup (range_nonempty _) hf, supr_range'] lemma l_csupr_set (gc : galois_connection l u) {s : set γ} {f : γ → α} (hf : bdd_above (f '' s)) (hne : s.nonempty) : l (⨆ i : s, f i) = ⨆ i : s, l (f i) := by { haveI := hne.to_subtype, rw image_eq_range at hf, exact gc.l_csupr hf } lemma u_cInf (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = ⨅ x : s, u x := gc.dual.l_cSup hne hbdd lemma u_cInf' (gc : galois_connection l u) {s : set β} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = Inf (u '' s) := gc.dual.l_cSup' hne hbdd lemma u_cinfi (gc : galois_connection l u) {f : ι → β} (hf : bdd_below (range f)) : u (⨅ i, f i) = ⨅ i, u (f i) := gc.dual.l_csupr hf lemma u_cinfi_set (gc : galois_connection l u) {s : set γ} {f : γ → β} (hf : bdd_below (f '' s)) (hne : s.nonempty) : u (⨅ i : s, f i) = ⨅ i : s, u (f i) := gc.dual.l_csupr_set hf hne end galois_connection namespace order_iso variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [nonempty ι] lemma map_cSup (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = ⨆ x : s, e x := e.to_galois_connection.l_cSup hne hbdd lemma map_cSup' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = Sup (e '' s) := e.to_galois_connection.l_cSup' hne hbdd lemma map_csupr (e : α ≃o β) {f : ι → α} (hf : bdd_above (range f)) : e (⨆ i, f i) = ⨆ i, e (f i) := e.to_galois_connection.l_csupr hf lemma map_csupr_set (e : α ≃o β) {s : set γ} {f : γ → α} (hf : bdd_above (f '' s)) (hne : s.nonempty) : e (⨆ i : s, f i) = ⨆ i : s, e (f i) := e.to_galois_connection.l_csupr_set hf hne lemma map_cInf (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = ⨅ x : s, e x := e.dual.map_cSup hne hbdd lemma map_cInf' (e : α ≃o β) {s : set α} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = Inf (e '' s) := e.dual.map_cSup' hne hbdd lemma map_cinfi (e : α ≃o β) {f : ι → α} (hf : bdd_below (range f)) : e (⨅ i, f i) = ⨅ i, e (f i) := e.dual.map_csupr hf lemma map_cinfi_set (e : α ≃o β) {s : set γ} {f : γ → α} (hf : bdd_below (f '' s)) (hne : s.nonempty) : e (⨅ i : s, f i) = ⨅ i : s, e (f i) := e.dual.map_csupr_set hf hne end order_iso /-! ### Supremum/infimum of `set.image2` A collection of lemmas showing what happens to the suprema/infima of `s` and `t` when mapped under a binary function whose partial evaluations are lower/upper adjoints of Galois connections. -/ section variables [conditionally_complete_lattice α] [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : α → β → γ} {s : set α} {t : set β} variables {l u : α → β → γ} {l₁ u₁ : β → γ → α} {l₂ u₂ : α → γ → β} lemma cSup_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) (hs₀ : s.nonempty) (hs₁ : bdd_above s) (ht₀ : t.nonempty) (ht₁ : bdd_above t) : Sup (image2 l s t) = l (Sup s) (Sup t) := begin refine eq_of_forall_ge_iff (λ c, _), rw [cSup_le_iff (hs₁.image2 (λ _, (h₁ _).monotone_l) (λ _, (h₂ _).monotone_l) ht₁) (hs₀.image2 ht₀), forall_image2_iff, forall₂_swap, (h₂ _).le_iff_le, cSup_le_iff ht₁ ht₀], simp_rw [←(h₂ _).le_iff_le, (h₁ _).le_iff_le, cSup_le_iff hs₁ hs₀], end lemma cSup_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (swap l b) (u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : s.nonempty → bdd_above s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Sup s) (Inf t) := @cSup_image2_eq_cSup_cSup _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cSup_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a) (u₂ a)) : s.nonempty → bdd_below s → t.nonempty → bdd_above t → Sup (image2 l s t) = l (Inf s) (Sup t) := @cSup_image2_eq_cSup_cSup αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cSup_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (swap l b ∘ of_dual) (to_dual ∘ u₁ b)) (h₂ : ∀ a, galois_connection (l a ∘ of_dual) (to_dual ∘ u₂ a)) : s.nonempty → bdd_below s → t.nonempty → bdd_below t → Sup (image2 l s t) = l (Inf s) (Inf t) := @cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cInf_cInf (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : s.nonempty → bdd_below s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Inf s) (Inf t) := @cSup_image2_eq_cSup_cSup αᵒᵈ βᵒᵈ γᵒᵈ _ _ _ _ _ _ l₁ l₂ (λ _, (h₁ _).dual) (λ _, (h₂ _).dual) lemma cInf_image2_eq_cInf_cSup (h₁ : ∀ b, galois_connection (l₁ b) (swap u b)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : s.nonempty → bdd_below s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Inf s) (Sup t) := @cInf_image2_eq_cInf_cInf _ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cSup_cInf (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (l₂ a) (u a)) : s.nonempty → bdd_above s → t.nonempty → bdd_below t → Inf (image2 u s t) = u (Sup s) (Inf t) := @cInf_image2_eq_cInf_cInf αᵒᵈ _ _ _ _ _ _ _ _ _ _ h₁ h₂ lemma cInf_image2_eq_cSup_cSup (h₁ : ∀ b, galois_connection (to_dual ∘ l₁ b) (swap u b ∘ of_dual)) (h₂ : ∀ a, galois_connection (to_dual ∘ l₂ a) (u a ∘ of_dual)) : s.nonempty → bdd_above s → t.nonempty → bdd_above t → Inf (image2 u s t) = u (Sup s) (Sup t) := @cInf_image2_eq_cInf_cInf αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ _ _ h₁ h₂ end /-! ### Relation between `Sup` / `Inf` and `finset.sup'` / `finset.inf'` Like the `Sup` of a `conditionally_complete_lattice`, `finset.sup'` also requires the set to be non-empty. As a result, we can translate between the two. -/ namespace finset lemma sup'_eq_cSup_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) : s.sup' H f = Sup (f '' s) := begin apply le_antisymm, { refine (finset.sup'_le _ _ $ λ a ha, _), refine le_cSup ⟨s.sup' H f, _⟩ ⟨a, ha, rfl⟩, rintros i ⟨j, hj, rfl⟩, exact finset.le_sup' _ hj }, { apply cSup_le ((coe_nonempty.mpr H).image _), rintros _ ⟨a, ha, rfl⟩, exact finset.le_sup' _ ha, } end lemma inf'_eq_cInf_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) : s.inf' H f = Inf (f '' s) := @sup'_eq_cSup_image _ βᵒᵈ _ _ H _ lemma sup'_id_eq_cSup [conditionally_complete_lattice α] (s : finset α) (H) : s.sup' H id = Sup s := by rw [sup'_eq_cSup_image s H, set.image_id] lemma inf'_id_eq_cInf [conditionally_complete_lattice α] (s : finset α) (H) : s.inf' H id = Inf s := @sup'_id_eq_cSup αᵒᵈ _ _ H end finset section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot α)` If `α` is a `conditionally_complete_lattice`, then we show that `with_top α` and `with_bot α` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot α)` naturally inherits the structure of a complete lattice. Note that for α a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top α` fixes the unboundedness problem and the extension to `with_bot α` fixes the problem with the empty set. This result can be used to show that the extended reals [-∞, ∞] are a complete lattice. -/ open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_top α) := { le_cSup := λ S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, cSup_le := λ S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := λ S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := λ S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.has_Sup, ..with_top.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {α : Type*} [conditionally_complete_lattice α] : conditionally_complete_lattice (with_bot α) := { le_cSup := (@with_top.conditionally_complete_lattice αᵒᵈ _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice αᵒᵈ _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice αᵒᵈ _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } noncomputable instance with_top.with_bot.complete_lattice {α : Type*} [conditionally_complete_lattice α] : complete_lattice (with_top (with_bot α)) := { le_Sup := λ S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := λ S a ha, begin cases S.eq_empty_or_nonempty with h, { show ite _ _ _ ≤ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use ⊥, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := λ S a haS, show ite _ _ _ ≤ a, begin split_ifs, { cases a with a, exact le_rfl, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use ⊥, intros b hb, exact bot_le } } end, le_Inf := λ S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.has_Inf, ..with_top.has_Sup, ..with_top.bounded_order, ..with_top.lattice } noncomputable instance with_top.with_bot.complete_linear_order {α : Type*} [conditionally_complete_linear_order α] : complete_linear_order (with_top (with_bot α)) := { .. with_top.with_bot.complete_lattice, .. with_top.linear_order } lemma with_top.supr_coe_eq_top {ι : Sort*} {α : Type*} [conditionally_complete_linear_order_bot α] (f : ι → α) : (⨆ x, (f x : with_top α)) = ⊤ ↔ ¬ bdd_above (set.range f) := begin rw [supr_eq_top, not_bdd_above_iff], refine ⟨λ hf r, _, λ hf a ha, _⟩, { rcases hf r (with_top.coe_lt_top r) with ⟨i, hi⟩, exact ⟨f i, ⟨i, rfl⟩, with_top.coe_lt_coe.mp hi⟩ }, { rcases hf (a.untop ha.ne) with ⟨-, ⟨i, rfl⟩, hi⟩, exact ⟨i, by simpa only [with_top.coe_untop _ ha.ne] using with_top.coe_lt_coe.mpr hi⟩ }, end lemma with_top.supr_coe_lt_top {ι : Sort*} {α : Type*} [conditionally_complete_linear_order_bot α] (f : ι → α) : (⨆ x, (f x : with_top α)) < ⊤ ↔ bdd_above (set.range f) := lt_top_iff_ne_top.trans $ (with_top.supr_coe_eq_top f).not.trans not_not end with_top_bot section group variables {ι' : Sort*} [nonempty ι] [nonempty ι'] [conditionally_complete_lattice α] [group α] @[to_additive] lemma le_mul_cinfi [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α} (H : ∀ j, a ≤ g * h j) : a ≤ g * infi h := inv_mul_le_iff_le_mul.mp $ le_cinfi $ λ hi, inv_mul_le_iff_le_mul.mpr $ H _ @[to_additive] lemma mul_csupr_le [covariant_class α α (*) (≤)] {a : α} {g : α} {h : ι → α} (H : ∀ j, g * h j ≤ a) : g * supr h ≤ a := @le_mul_cinfi αᵒᵈ _ _ _ _ _ _ _ _ H @[to_additive] lemma le_cinfi_mul [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α} (H : ∀ i, a ≤ g i * h) : a ≤ infi g * h := mul_inv_le_iff_le_mul.mp $ le_cinfi $ λ gi, mul_inv_le_iff_le_mul.mpr $ H _ @[to_additive] lemma csupr_mul_le [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : α} (H : ∀ i, g i * h ≤ a) : supr g * h ≤ a := @le_cinfi_mul αᵒᵈ _ _ _ _ _ _ _ _ H @[to_additive] lemma le_cinfi_mul_cinfi [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, a ≤ g i * h j) : a ≤ infi g * infi h := le_cinfi_mul $ λ i, le_mul_cinfi $ H _ @[to_additive] lemma csupr_mul_csupr_le [covariant_class α α (*) (≤)] [covariant_class α α (function.swap (*)) (≤)] {a : α} {g : ι → α} {h : ι' → α} (H : ∀ i j, g i * h j ≤ a) : supr g * supr h ≤ a := csupr_mul_le $ λ i, mul_csupr_le $ H _ end group
3d67a39675923674dff34e5d06200c552e79ab0b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/968.lean
904daac779562455c2f4fcbc60b2e71e778aacb3
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
215
lean
variables (A : Type) [inhabited A] definition f (a : A) : A := a #check @f nat nat.inhabited structure foo := (a : A) #check @foo nat nat.inhabited inductive bla | mk : A → bla #check @bla nat nat.inhabited
48802fe18a1362b2aa980b514e05ac646b58b0d3
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/pairing.lean
3b61b8826f8397d41b1d61ef96a48aa8241f81c9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,362
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, Mario Carneiro -/ import data.nat.sqrt import data.set.lattice /-! # Naturals pairing function This file defines a pairing function for the naturals as follows: ```text 0 1 4 9 16 2 3 5 10 17 6 7 8 11 18 12 13 14 15 19 20 21 22 23 24 ``` It has the advantage of being monotone in both directions and sending `⟦0, n^2 - 1⟧` to `⟦0, n - 1⟧²`. -/ open prod decidable function namespace nat /-- Pairing function for the natural numbers. -/ @[pp_nodot] def mkpair (a b : ℕ) : ℕ := if a < b then b*b + a else a*a + a + b /-- Unpairing function for the natural numbers. -/ @[pp_nodot] def unpair (n : ℕ) : ℕ × ℕ := let s := sqrt n in if n - s*s < s then (n - s*s, s) else (s, n - s*s - s) @[simp] theorem mkpair_unpair (n : ℕ) : mkpair (unpair n).1 (unpair n).2 = n := begin dsimp only [unpair], set s := sqrt n, have sm : s * s + (n - s * s) = n := add_tsub_cancel_of_le (sqrt_le _), split_ifs, { simp [mkpair, h, sm] }, { have hl : n - s*s - s ≤ s := tsub_le_iff_left.mpr (tsub_le_iff_left.mpr $ by rw ← add_assoc; apply sqrt_le_add), simp [mkpair, hl.not_lt, add_assoc, add_tsub_cancel_of_le (le_of_not_gt h), sm] } end theorem mkpair_unpair' {n a b} (H : unpair n = (a, b)) : mkpair a b = n := by simpa [H] using mkpair_unpair n @[simp] theorem unpair_mkpair (a b : ℕ) : unpair (mkpair a b) = (a, b) := begin dunfold mkpair, split_ifs, { show unpair (b * b + a) = (a, b), have be : sqrt (b * b + a) = b, from sqrt_add_eq _ (le_trans (le_of_lt h) (nat.le_add_left _ _)), simp [unpair, be, add_tsub_cancel_right, h] }, { show unpair (a * a + a + b) = (a, b), have ae : sqrt (a * a + (a + b)) = a, { rw sqrt_add_eq, exact add_le_add_left (le_of_not_gt h) _ }, simp [unpair, ae, nat.not_lt_zero, add_assoc] } end /-- An equivalence between `ℕ × ℕ` and `ℕ`. -/ @[simps { fully_applied := ff }] def mkpair_equiv : ℕ × ℕ ≃ ℕ := ⟨uncurry mkpair, unpair, λ ⟨a, b⟩, unpair_mkpair a b, mkpair_unpair⟩ lemma surjective_unpair : surjective unpair := mkpair_equiv.symm.surjective @[simp] lemma mkpair_eq_mkpair {a b c d : ℕ} : mkpair a b = mkpair c d ↔ a = c ∧ b = d := mkpair_equiv.injective.eq_iff.trans (@prod.ext_iff ℕ ℕ (a, b) (c, d)) theorem unpair_lt {n : ℕ} (n1 : 1 ≤ n) : (unpair n).1 < n := let s := sqrt n in begin simp [unpair], change sqrt n with s, by_cases h : n - s * s < s; simp [h], { exact lt_of_lt_of_le h (sqrt_le_self _) }, { simp at h, have s0 : 0 < s := sqrt_pos.2 n1, exact lt_of_le_of_lt h (tsub_lt_self n1 (mul_pos s0 s0)) } end @[simp] lemma unpair_zero : unpair 0 = 0 := by { rw unpair, simp } theorem unpair_left_le : ∀ (n : ℕ), (unpair n).1 ≤ n | 0 := by simp | (n+1) := le_of_lt (unpair_lt (nat.succ_pos _)) theorem left_le_mkpair (a b : ℕ) : a ≤ mkpair a b := by simpa using unpair_left_le (mkpair a b) theorem right_le_mkpair (a b : ℕ) : b ≤ mkpair a b := begin by_cases h : a < b; simp [mkpair, h], exact le_trans (le_mul_self _) (nat.le_add_right _ _) end theorem unpair_right_le (n : ℕ) : (unpair n).2 ≤ n := by simpa using right_le_mkpair n.unpair.1 n.unpair.2 theorem mkpair_lt_mkpair_left {a₁ a₂} (b) (h : a₁ < a₂) : mkpair a₁ b < mkpair a₂ b := begin by_cases h₁ : a₁ < b; simp [mkpair, h₁, add_assoc], { by_cases h₂ : a₂ < b; simp [mkpair, h₂, h], simp at h₂, apply add_lt_add_of_le_of_lt, exact mul_self_le_mul_self h₂, exact lt_add_right _ _ _ h }, { simp at h₁, simp [not_lt_of_gt (lt_of_le_of_lt h₁ h)], apply add_lt_add, exact mul_self_lt_mul_self h, apply add_lt_add_right; assumption } end theorem mkpair_lt_mkpair_right (a) {b₁ b₂} (h : b₁ < b₂) : mkpair a b₁ < mkpair a b₂ := begin by_cases h₁ : a < b₁; simp [mkpair, h₁, add_assoc], { simp [mkpair, lt_trans h₁ h, h], exact mul_self_lt_mul_self h }, { by_cases h₂ : a < b₂; simp [mkpair, h₂, h], simp at h₁, rw [add_comm, add_comm _ a, add_assoc, add_lt_add_iff_left], rwa [add_comm, ← sqrt_lt, sqrt_add_eq], exact le_trans h₁ (nat.le_add_left _ _) } end end nat open nat section complete_lattice lemma supr_unpair {α} [complete_lattice α] (f : ℕ → ℕ → α) : (⨆ n : ℕ, f n.unpair.1 n.unpair.2) = ⨆ i j : ℕ, f i j := by rw [← (supr_prod : (⨆ i : ℕ × ℕ, f i.1 i.2) = _), ← nat.surjective_unpair.supr_comp] lemma infi_unpair {α} [complete_lattice α] (f : ℕ → ℕ → α) : (⨅ n : ℕ, f n.unpair.1 n.unpair.2) = ⨅ i j : ℕ, f i j := supr_unpair (show ℕ → ℕ → αᵒᵈ, from f) end complete_lattice namespace set lemma Union_unpair_prod {α β} {s : ℕ → set α} {t : ℕ → set β} : (⋃ n : ℕ, s n.unpair.fst ×ˢ t n.unpair.snd) = (⋃ n, s n) ×ˢ (⋃ n, t n) := by { rw [← Union_prod], convert surjective_unpair.Union_comp _, refl } lemma Union_unpair {α} (f : ℕ → ℕ → set α) : (⋃ n : ℕ, f n.unpair.1 n.unpair.2) = ⋃ i j : ℕ, f i j := supr_unpair f lemma Inter_unpair {α} (f : ℕ → ℕ → set α) : (⋂ n : ℕ, f n.unpair.1 n.unpair.2) = ⋂ i j : ℕ, f i j := infi_unpair f end set
3d2048ccf76ff6f0f258688376353ddfbb337b67
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/preserves/filtered.lean
aab016a35621e71ea6a3703ac0f33efe7889c39b
[ "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,822
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import category_theory.limits.preserves.basic import category_theory.filtered /-! # Preservation of filtered colimits and cofiltered limits. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Typically forgetful functors from algebraic categories preserve filtered colimits (although not general colimits). See e.g. `algebra/category/Mon/filtered_colimits`. ## Future work This could be generalised to allow diagrams in lower universes. -/ open category_theory open category_theory.functor namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables {E : Type u₃} [category.{v} E] variables {J : Type v} [small_category J] {K : J ⥤ C} /-- A functor is said to preserve filtered colimits, if it preserves all colimits of shape `J`, where `J` is a filtered category. -/ class preserves_filtered_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_filtered_colimits : Π (J : Type v) [small_category J] [is_filtered J], preserves_colimits_of_shape J F) attribute [instance, priority 100] preserves_filtered_colimits.preserves_filtered_colimits @[priority 100] instance preserves_colimits.preserves_filtered_colimits (F : C ⥤ D) [preserves_colimits F] : preserves_filtered_colimits F := { preserves_filtered_colimits := infer_instance } instance comp_preserves_filtered_colimits (F : C ⥤ D) (G : D ⥤ E) [preserves_filtered_colimits F] [preserves_filtered_colimits G] : preserves_filtered_colimits (F ⋙ G) := { preserves_filtered_colimits := λ J _ _, by exactI infer_instance } /-- A functor is said to preserve cofiltered limits, if it preserves all limits of shape `J`, where `J` is a cofiltered category. -/ class preserves_cofiltered_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := (preserves_cofiltered_limits : Π (J : Type v) [small_category J] [is_cofiltered J], preserves_limits_of_shape J F) attribute [instance, priority 100] preserves_cofiltered_limits.preserves_cofiltered_limits @[priority 100] instance preserves_limits.preserves_cofiltered_limits (F : C ⥤ D) [preserves_limits F] : preserves_cofiltered_limits F := { preserves_cofiltered_limits := infer_instance } instance comp_preserves_cofiltered_limits (F : C ⥤ D) (G : D ⥤ E) [preserves_cofiltered_limits F] [preserves_cofiltered_limits G] : preserves_cofiltered_limits (F ⋙ G) := { preserves_cofiltered_limits := λ J _ _, by exactI infer_instance } end category_theory.limits
4a9c821e3c692ffe315b070e7101ce59011c0407
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/quot_bug.lean
5b04f7ac632a4edf6a942377e8637859af666fa4
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
277
lean
open quot variables {A : Type} {B : A → Type} variable f : Π a : A, B a local attribute [instance] function.fun_setoid #reduce λ x, quot.lift_on ⟦f⟧ (λf : (Πx : A, B x), f) _ x example (x : A) : quot.lift_on ⟦f⟧ (λf : (Πx : A, B x), f) sorry x = f x := rfl
9b79780afb1e89d9d0b35b400a4dfd07726b2dd6
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep_2/basic_definitions/direct_sum_representation.lean
c6f2a8ababe08fd7f0d825b33d609f838a6a3b23
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
1,190
lean
import basic_definitions.group_representation import linear_algebra.direct_sum_module universes u v w u₁ variables (R : Type u) [ring R] (G : Type v)[group G] (ι : Type w) [decidable_eq ι] (M : ι → Type w) [Π i, add_comm_group (M i)] [Π i, module R (M i)] (ρ : Π i, group_representation G R (M i)) variables (i : ι ) (g : G) (x y : M i) #check ρ i g (x+y) example : ρ i g (x+y) = ρ i g (x) +ρ i g (y) := begin rw (ρ i g).map_add, end #check direct_sum ι M #check direct_sum.lof R ι M i #check direct_sum.to_module R ι ( direct_sum ι M ) (λ i, (direct_sum.lof R ι M i) ⊚ ( ρ i g)) #check to_module_lof open direct_sum #check to_module_lof R i x def direct_sum_representation : group_representation G R (direct_sum ι M) := { to_fun := λ g, direct_sum.to_module R ι ( direct_sum ι M ) (λ i, (direct_sum.lof R ι M i) ⊚ ( ρ i g)), map_one' := begin ext,let t := @to_module_lof R _ ι _ M _ _ (direct_sum ι M) _ _ (λ i, (direct_sum.lof R ι M i) ⊚ ( ρ i 1)) i (x i), let h := lof_apply R i (x i), end, map_mul' := _ }
430dd54e78fe5b79023224afd507dd495810fa5e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/int/comp_lemmas.lean
454b818322624cce6aea6c58c16cfc38c7663f6a
[]
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
4,329
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 Auxiliary lemmas used to compare int numerals. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.int.order namespace Mathlib namespace int /- Auxiliary lemmas for proving that to int numerals are different -/ /- 1. Lemmas for reducing the problem to the case where the numerals are positive -/ protected theorem ne_neg_of_ne {a : ℤ} {b : ℤ} : a ≠ b → -a ≠ -b := fun (h₁ : a ≠ b) (h₂ : -a = -b) => absurd (int.neg_inj h₂) h₁ protected theorem neg_ne_zero_of_ne {a : ℤ} : a ≠ 0 → -a ≠ 0 := fun (h₁ : a ≠ 0) (h₂ : -a = 0) => (fun (this : -a = -0) => (fun (this : a = 0) => absurd this h₁) (int.neg_inj this)) (eq.mpr (id (Eq._oldrec (Eq.refl (-a = -0)) int.neg_zero)) h₂) protected theorem zero_ne_neg_of_ne {a : ℤ} (h : 0 ≠ a) : 0 ≠ -a := ne.symm (int.neg_ne_zero_of_ne (ne.symm h)) protected theorem neg_ne_of_pos {a : ℤ} {b : ℤ} : a > 0 → b > 0 → -a ≠ b := sorry protected theorem ne_neg_of_pos {a : ℤ} {b : ℤ} : a > 0 → b > 0 → a ≠ -b := fun (h₁ : a > 0) (h₂ : b > 0) => ne.symm (int.neg_ne_of_pos h₂ h₁) /- 2. Lemmas for proving that positive int numerals are nonneg and positive -/ protected theorem one_pos : 1 > 0 := int.zero_lt_one protected theorem bit0_pos {a : ℤ} : a > 0 → bit0 a > 0 := fun (h : a > 0) => int.add_pos h h protected theorem bit1_pos {a : ℤ} : a ≥ 0 → bit1 a > 0 := fun (h : a ≥ 0) => int.lt_add_of_le_of_pos (int.add_nonneg h h) int.zero_lt_one protected theorem zero_nonneg : 0 ≥ 0 := le_refl 0 protected theorem one_nonneg : 1 ≥ 0 := le_of_lt int.zero_lt_one protected theorem bit0_nonneg {a : ℤ} : a ≥ 0 → bit0 a ≥ 0 := fun (h : a ≥ 0) => int.add_nonneg h h protected theorem bit1_nonneg {a : ℤ} : a ≥ 0 → bit1 a ≥ 0 := fun (h : a ≥ 0) => le_of_lt (int.bit1_pos h) protected theorem nonneg_of_pos {a : ℤ} : a > 0 → a ≥ 0 := le_of_lt /- 3. nat_abs auxiliary lemmas -/ theorem neg_succ_of_nat_lt_zero (n : ℕ) : Int.negSucc n < 0 := sorry theorem of_nat_ge_zero (n : ℕ) : Int.ofNat n ≥ 0 := le.intro (eq.mpr (id (Eq._oldrec (Eq.refl (0 + ↑n = Int.ofNat n)) (int.zero_add ↑n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n = Int.ofNat n)) (int.coe_nat_eq n))) (Eq.refl (Int.ofNat n)))) theorem of_nat_nat_abs_eq_of_nonneg {a : ℤ} : a ≥ 0 → Int.ofNat (nat_abs a) = a := sorry theorem ne_of_nat_abs_ne_nat_abs_of_nonneg {a : ℤ} {b : ℤ} (ha : a ≥ 0) (hb : b ≥ 0) (h : nat_abs a ≠ nat_abs b) : a ≠ b := sorry protected theorem ne_of_nat_ne_nonneg_case {a : ℤ} {b : ℤ} {n : ℕ} {m : ℕ} (ha : a ≥ 0) (hb : b ≥ 0) (e1 : nat_abs a = n) (e2 : nat_abs b = m) (h : n ≠ m) : a ≠ b := (fun (this : nat_abs a ≠ nat_abs b) => ne_of_nat_abs_ne_nat_abs_of_nonneg ha hb this) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a ≠ nat_abs b)) e1)) (eq.mpr (id (Eq._oldrec (Eq.refl (n ≠ nat_abs b)) e2)) h)) /- 4. Aux lemmas for pushing nat_abs inside numerals nat_abs_zero and nat_abs_one are defined at init/data/int/basic.lean -/ theorem nat_abs_of_nat_core (n : ℕ) : nat_abs (Int.ofNat n) = n := rfl theorem nat_abs_of_neg_succ_of_nat (n : ℕ) : nat_abs (Int.negSucc n) = Nat.succ n := rfl protected theorem nat_abs_add_nonneg {a : ℤ} {b : ℤ} : a ≥ 0 → b ≥ 0 → nat_abs (a + b) = nat_abs a + nat_abs b := sorry protected theorem nat_abs_add_neg {a : ℤ} {b : ℤ} : a < 0 → b < 0 → nat_abs (a + b) = nat_abs a + nat_abs b := sorry protected theorem nat_abs_bit0 (a : ℤ) : nat_abs (bit0 a) = bit0 (nat_abs a) := sorry protected theorem nat_abs_bit0_step {a : ℤ} {n : ℕ} (h : nat_abs a = n) : nat_abs (bit0 a) = bit0 n := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs (bit0 a) = bit0 n)) (Eq.symm h))) (int.nat_abs_bit0 a) protected theorem nat_abs_bit1_nonneg {a : ℤ} (h : a ≥ 0) : nat_abs (bit1 a) = bit1 (nat_abs a) := sorry protected theorem nat_abs_bit1_nonneg_step {a : ℤ} {n : ℕ} (h₁ : a ≥ 0) (h₂ : nat_abs a = n) : nat_abs (bit1 a) = bit1 n := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs (bit1 a) = bit1 n)) (Eq.symm h₂))) (int.nat_abs_bit1_nonneg h₁)
d9d067b427850977e74b3f10c788e5b916d2cf9e
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/zsqrtd/gaussian_int.lean
46db43962f5832eb0361ed18fe3eee6f567d4ff1
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
12,705
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.zsqrtd.basic import data.complex.basic import ring_theory.principal_ideal_domain import number_theory.quadratic_reciprocity /-! # Gaussian integers The Gaussian integers are complex integer, complex numbers whose real and imaginary parts are both integers. ## Main definitions The Euclidean domain structure on `ℤ[i]` is defined in this file. The homomorphism `to_complex` into the complex numbers is also defined in this file. ## Main statements `prime_iff_mod_four_eq_three_of_nat_prime` A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` ## Notations This file uses the local notation `ℤ[i]` for `gaussian_int` ## Implementation notes Gaussian integers are implemented using the more general definition `zsqrtd`, the type of integers adjoined a square root of `d`, in this case `-1`. The definition is reducible, so that properties and definitions about `zsqrtd` can easily be used. -/ open zsqrtd complex @[reducible] def gaussian_int : Type := zsqrtd (-1) local notation `ℤ[i]` := gaussian_int namespace gaussian_int instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩ instance : comm_ring ℤ[i] := zsqrtd.comm_ring section local attribute [-instance] complex.field -- Avoid making things noncomputable unnecessarily. /-- The embedding of the Gaussian integers into the complex numbers, as a ring homomorphism. -/ def to_complex : ℤ[i] →+* ℂ := begin refine_struct { to_fun := λ x : ℤ[i], (x.re + x.im * I : ℂ), .. }; intros; apply complex.ext; dsimp; norm_cast; simp; abel end end instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩ lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def] lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ := by apply complex.ext; simp [to_complex_def] @[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def] @[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def] @[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def] @[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def] @[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := to_complex.map_add _ _ @[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := to_complex.map_mul _ _ @[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := to_complex.map_one @[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := to_complex.map_zero @[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := to_complex.map_neg _ @[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := to_complex.map_sub _ _ @[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y := by cases x; cases y; simp [to_complex_def₂] @[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 := by rw [← to_complex_zero, to_complex_inj] @[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq := by rw [norm, norm_sq]; simp @[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq := by cases x; rw [norm, norm_sq]; simp lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg trivial _ @[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 := by rw [← @int.cast_inj ℝ _ _ _]; simp lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 := by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg] @[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm := int.nat_abs_of_nonneg (norm_nonneg _) @[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α] (x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm := by rw [← int.cast_coe_nat, coe_nat_abs_norm] lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs = x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs := int.coe_nat_inj $ begin simp, simp [norm] end protected def div (x y : ℤ[i]) : ℤ[i] := let n := (rat.of_int (norm y))⁻¹ in let c := y.conj in ⟨round (rat.of_int (x * c).re * n : ℚ), round (rat.of_int (x * c).im * n : ℚ)⟩ instance : has_div ℤ[i] := ⟨gaussian_int.div⟩ lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ := show zsqrtd.mk _ _ = _, by simp [rat.of_int_eq_mk, rat.mk_eq_div, div_eq_mul_inv] lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) := by rw [div_def, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) := by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] local notation `abs'` := _root_.abs lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re) (him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq := by rw [norm_sq, norm_sq, ← _root_.abs_mul_self, _root_.abs_mul, ← _root_.abs_mul_self y.re, _root_.abs_mul y.re, ← _root_.abs_mul_self x.im, _root_.abs_mul x.im, ← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact (add_le_add (mul_self_le_mul_self (abs_nonneg _) hre) (mul_self_le_mul_self (abs_nonneg _) him)) lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) : ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 := calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq = ((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re + ((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq : congr_arg _ $ by apply complex.ext; simp ... ≤ (1 / 2 + 1 / 2 * I).norm_sq : have abs' (2 / (2 * 2) : ℝ) = 1 / 2, by rw _root_.abs_of_nonneg; norm_num, norm_sq_le_norm_sq_of_re_le_of_im_le (by rw [to_complex_div_re]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).re) (by rw [to_complex_div_im]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).im) ... < 1 : by simp [norm_sq]; norm_num protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y) instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩ lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm := have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj], (@int.cast_lt ℝ _ _ _).1 $ calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def] ... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq : by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this] ... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _) (norm_sq_pos.2 this) ... = norm y : by simp lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm.nat_abs < y.norm.nat_abs := int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy]) lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (norm x).nat_abs ≤ (norm (x * y)).nat_abs := by rw [norm_mul, int.nat_abs_mul]; exact le_mul_of_one_le_right (nat.zero_le _) (int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact norm_pos.2 hy)) instance : nontrivial ℤ[i] := ⟨⟨0, 1, dec_trivial⟩⟩ instance : euclidean_domain ℤ[i] := { quotient := (/), remainder := (%), quotient_zero := λ _, by simp [div_def]; refl, quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def], r := _, r_well_founded := measure_wf (int.nat_abs ∘ norm), remainder_lt := nat_abs_norm_mod_lt, mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0, .. gaussian_int.comm_ring, .. gaussian_int.nontrivial } open principal_ideal_ring lemma mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact p.prime] (hpi : prime (p : ℤ[i])) : p % 4 = 3 := hp.eq_two_or_odd.elim (λ hp2, absurd hpi (mt irreducible_iff_prime.2 $ λ ⟨hu, h⟩, begin have := h ⟨1, 1⟩ ⟨1, -1⟩ (hp2.symm ▸ rfl), rw [← norm_eq_one_iff, ← norm_eq_one_iff] at this, exact absurd this dec_trivial end)) (λ hp1, by_contradiction $ λ hp3 : p % 4 ≠ 3, have hp41 : p % 4 = 1, begin rw [← nat.mod_mul_left_mod p 2 2, show 2 * 2 = 4, from rfl] at hp1, have := nat.mod_lt p (show 0 < 4, from dec_trivial), revert this hp3 hp1, generalize : p % 4 = m, dec_trivial!, end, let ⟨k, hk⟩ := (zmod.exists_pow_two_eq_neg_one_iff_mod_four_ne_three p).2 $ by rw hp41; exact dec_trivial in begin obtain ⟨k, k_lt_p, rfl⟩ : ∃ (k' : ℕ) (h : k' < p), (k' : zmod p) = k, { refine ⟨k.val, k.val_lt, zmod.cast_val k⟩ }, have hpk : p ∣ k ^ 2 + 1, by rw [← char_p.cast_eq_zero_iff (zmod p) p]; simp *, have hkmul : (k ^ 2 + 1 : ℤ[i]) = ⟨k, 1⟩ * ⟨k, -1⟩ := by simp [_root_.pow_two, zsqrtd.ext], have hpne1 : p ≠ 1, from (ne_of_lt (hp.one_lt)).symm, have hkltp : 1 + k * k < p * p, from calc 1 + k * k ≤ k + k * k : add_le_add_right (nat.pos_of_ne_zero (λ hk0, by clear_aux_decl; simp [*, nat.pow_succ] at *)) _ ... = k * (k + 1) : by simp [add_comm, mul_add] ... < p * p : mul_lt_mul k_lt_p k_lt_p (nat.succ_pos _) (nat.zero_le _), have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k, -1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, -1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k, 1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, 1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 (by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.one_lt).symm h.1), obtain ⟨y, hy⟩ := hpk, have := hpi.2.2 ⟨k, 1⟩ ⟨k, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩, clear_aux_decl, tauto end) lemma sum_two_squares_of_nat_prime_of_not_irreducible (p : ℕ) [hp : fact p.prime] (hpi : ¬irreducible (p : ℤ[i])) : ∃ a b, a^2 + b^2 = p := have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 $ by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.one_lt).symm h.1, have hab : ∃ a b, (p : ℤ[i]) = a * b ∧ ¬ is_unit a ∧ ¬ is_unit b, by simpa [irreducible, hpu, not_forall, not_or_distrib] using hpi, let ⟨a, b, hpab, hau, hbu⟩ := hab in have hnap : (norm a).nat_abs = p, from ((hp.mul_eq_prime_pow_two_iff (mt norm_eq_one_iff.1 hau) (mt norm_eq_one_iff.1 hbu)).1 $ by rw [← int.coe_nat_inj', int.coe_nat_pow, _root_.pow_two, ← @norm_nat_cast (-1), hpab]; simp).1, ⟨a.re.nat_abs, a.im.nat_abs, by simpa [nat_abs_norm_eq, nat.pow_two] using hnap⟩ lemma prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact p.prime] (hp3 : p % 4 = 3) : prime (p : ℤ[i]) := irreducible_iff_prime.1 $ classical.by_contradiction $ λ hpi, let ⟨a, b, hab⟩ := sum_two_squares_of_nat_prime_of_not_irreducible p hpi in have ∀ a b : zmod 4, a^2 + b^2 ≠ p, by erw [← zmod.cast_mod_nat 4 p, hp3]; exact dec_trivial, this a b (hab ▸ by simp) /-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/ lemma prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact p.prime] : prime (p : ℤ[i]) ↔ p % 4 = 3 := ⟨mod_four_eq_three_of_nat_prime_of_prime p, prime_of_nat_prime_of_mod_four_eq_three p⟩ end gaussian_int
e5a6cdce7cc3887f1e844a75df4ea3a4668c7245
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/mllist.lean
9fb03eafa8f7d61706ce6ef6f0a584336c0d0f2b
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,149
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Keeley Hoek, Simon Hudon, Scott Morrison -/ import data.option.defs /-! # Monadic lazy lists. An alternative construction of lazy lists (see also `data.lazy_list`), with "lazyness" controlled by an arbitrary monad. The inductive construction is not allowed outside of meta (indeed, we can build infinite objects). This isn't so bad, as the typical use is with the tactic monad, in any case. As we're in meta anyway, we don't bother with proofs about these constructions. -/ universes u v namespace tactic -- We hide this away in the tactic namespace, just because it's all meta. /-- A monadic lazy list, controlled by an arbitrary monad. -/ meta inductive mllist (m : Type u → Type u) (α : Type u) : Type u | nil : mllist | cons : m (option α × mllist) → mllist namespace mllist variables {α β : Type u} {m : Type u → Type u} [alternative m] /-- Construct an `mllist` recursively. -/ meta def fix (f : α → m α) : α → mllist m α | x := cons $ (λ a, (some x, fix a)) <$> f x <|> pure (some x, nil) variables [monad m] /-- Repeatedly apply a function `f : α → m (α × list β)` to an initial `a : α`, accumulating the elements of the resulting `list β` as a single monadic lazy list. (This variant allows starting with a specified `list β` of elements, as well. )-/ meta def fixl_with (f : α → m (α × list β)) : α → list β → mllist m β | s (b :: rest) := cons $ pure (some b, fixl_with s rest) | s [] := cons $ do { (s', l) ← f s, match l with | (b :: rest) := pure (some b, fixl_with s' rest) | [] := pure (none, fixl_with s' []) end } <|> pure (none, nil) /-- Repeatedly apply a function `f : α → m (α × list β)` to an initial `a : α`, accumulating the elements of the resulting `list β` as a single monadic lazy list. -/ meta def fixl (f : α → m (α × list β)) (s : α) : mllist m β := fixl_with f s [] /-- Deconstruct an `mllist`, returning inside the monad an optional pair `α × mllist m α` representing the head and tail of the list. -/ meta def uncons {α : Type u} : mllist m α → m (option (α × mllist m α)) | nil := pure none | (cons l) := do (x, xs) ← l, some x ← return x | uncons xs, return (x, xs) /-- Compute, inside the monad, whether an `mllist` is empty. -/ meta def empty {α : Type u} (xs : mllist m α) : m (ulift bool) := (ulift.up ∘ option.is_some) <$> uncons xs /-- Convert a `list` to an `mllist`. -/ meta def of_list {α : Type u} : list α → mllist m α | [] := nil | (h :: t) := cons (pure (h, of_list t)) /-- Convert a `list` of values inside the monad into an `mllist`. -/ meta def m_of_list {α : Type u} : list (m α) → mllist m α | [] := nil | (h :: t) := cons ((λ x, (x, m_of_list t)) <$> some <$> h) /-- Extract a list inside the monad from an `mllist`. -/ meta def force {α} : mllist m α → m (list α) | nil := pure [] | (cons l) := do (x, xs) ← l, some x ← pure x | force xs, (::) x <$> (force xs) /-- Take the first `n` elements, as a list inside the monad. -/ meta def take {α} : mllist m α → ℕ → m (list α) | nil _ := pure [] | _ 0 := pure [] | (cons l) (n+1) := do (x, xs) ← l, some x ← pure x | take xs (n+1), (::) x <$> (take xs n) /-- Apply a function to every element of an `mllist`. -/ meta def map {α β : Type u} (f : α → β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (x, xs) ← l, pure (f <$> x, map xs) /-- Apply a function which returns values in the monad to every element of an `mllist`. -/ meta def mmap {α β : Type u} (f : α → m β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (x, xs) ← l, b ← x.traverse f, return (b, mmap xs) /-- Filter a `mllist`. -/ meta def filter {α : Type u} (p : α → Prop) [decidable_pred p] : mllist m α → mllist m α | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, filter r), return (if p a then some a else none, filter r) /-- Filter a `mllist` using a function which returns values in the (alternative) monad. Whenever the function "succeeds", we accept the element, and reject otherwise. -/ meta def mfilter [alternative m] {α β : Type u} (p : α → m β) : mllist m α → mllist m α | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, mfilter r), (p a >> return (a, mfilter r)) <|> return (none , mfilter r) /-- Filter and transform a `mllist` using an `option` valued function. -/ meta def filter_map {α β : Type u} (f : α → option β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, filter_map r), match f a with | (some b) := return (some b, filter_map r) | none := return (none, filter_map r) end /-- Filter and transform a `mllist` using a function that returns values inside the monad. We discard elements where the function fails. -/ meta def mfilter_map [alternative m] {α β : Type u} (f : α → m β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, mfilter_map r), (f a >>= (λ b, return (some b, mfilter_map r))) <|> return (none, mfilter_map r) /-- Concatenate two monadic lazty lists. -/ meta def append {α : Type u} : mllist m α → mllist m α → mllist m α | nil ys := ys | (cons xs) ys := cons $ do (x, xs) ← xs, return (x, append xs ys) /-- Join a monadic lazy list of monadic lazy lists into a single monadic lazy list. -/ meta def join {α : Type u} : mllist m (mllist m α) → mllist m α | nil := nil | (cons l) := cons $ do (xs,r) ← l, some xs ← return xs | return (none, join r), match xs with | nil := return (none, join r) | cons m := do (a,n) ← m, return (a, join (cons $ return (n, r))) end /-- Lift a monadic lazy list inside the monad to a monadic lazy list. -/ meta def squash {α} (t : m (mllist m α)) : mllist m α := (mllist.m_of_list [t]).join /-- Enumerate the elements of a monadic lazy list, starting at a specified offset. -/ meta def enum_from {α : Type u} : ℕ → mllist m α → mllist m (ℕ × α) | _ nil := nil | n (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, enum_from n r), return ((n, a), (enum_from (n + 1) r)) /-- Enumerate the elements of a monadic lazy list. -/ meta def enum {α : Type u} : mllist m α → mllist m (ℕ × α) := enum_from 0 /-- The infinite monadic lazy list of natural numbers.-/ meta def range {m : Type → Type} [alternative m] : mllist m ℕ := mllist.fix (λ n, pure (n + 1)) 0 /-- Add one element to the end of a monadic lazy list. -/ meta def concat {α : Type u} : mllist m α → α → mllist m α | L a := (mllist.of_list [L, mllist.of_list [a]]).join /-- Apply a function returning a monadic lazy list to each element of a monadic lazy list, joining the results. -/ meta def bind_ {α β : Type u} : mllist m α → (α → mllist m β) → mllist m β | nil f := nil | (cons ll) f := cons $ do (x, xs) ← ll, some x ← return x | return (none, bind_ xs f), return (none, append (f x) (bind_ xs f)) /-- Convert any value in the monad to the singleton monadic lazy list. -/ meta def monad_lift {α} (x : m α) : mllist m α := cons $ (flip prod.mk nil ∘ some) <$> x /-- Return the head of a monadic lazy list, as a value in the monad. -/ meta def head [alternative m] {α} (L : mllist m α) : m α := do some (r, _) ← L.uncons | failure, return r /-- Apply a function returning values inside the monad to a monadic lazy list, returning only the first successful result. -/ meta def mfirst [alternative m] {α β} (L : mllist m α) (f : α → m β) : m β := (L.mfilter_map f).head end mllist end tactic
8b60ee2a19a0c61e18139b069027e1817c9a3455
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/derivation.lean
6e81b19f8e9bf79542147b88fbbcd05925a2d014
[ "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
8,361
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import algebra.lie.of_associative import ring_theory.algebra_tower /-! # Derivations This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an `R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`. ## Notation The notation `⁅D1, D2⁆` is used for the commutator of two derivations. TODO: this file is just a stub to go on with some PRs in the geometry section. It only implements the definition of derivations in commutative algebra. This will soon change: as soon as bimodules will be there in mathlib I will change this file to take into account the non-commutative case. Any development on the theory of derivations is discouraged until the definitive definition of derivation will be implemented. -/ open algebra ring_hom /-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz` equality. TODO: update this when bimodules are defined. -/ @[protect_proj] structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] (M : Type*) [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] extends A →ₗ[R] M := (leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a) namespace derivation section variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] variables [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩ instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) := ⟨λ D, D.to_linear_map⟩ @[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl @[simp, norm_cast] lemma coe_fn_coe (f : derivation R A M) : ⇑(f : A →ₗ[R] M) = f := rfl lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 := by { cases D1, cases D2, congr', exact linear_map.coe_injective H } @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := coe_injective $ funext H @[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b @[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D @[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a @[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] lemma map_one_eq_zero : D 1 = 0 := begin have h : D 1 = D (1 * 1) := by rw mul_one, rwa [leibniz D 1 1, one_smul, self_eq_add_right] at h end @[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 := by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero] instance : has_zero (derivation R A M) := ⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply, linear_map.to_fun_eq_coe, smul_zero]⟩⟩ instance : inhabited (derivation R A M) := ⟨0⟩ instance : add_comm_monoid (derivation R A M) := { add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply, linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩, add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _, zero_add := λ D, ext $ λ a, zero_add _, add_zero := λ D, ext $ λ a, add_zero _, add_comm := λ D E, ext $ λ a, add_comm _ _, ..derivation.has_zero } @[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl @[priority 100] instance derivation.Rsemimodule : semimodule R (derivation R A M) := { smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz, linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul _ _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul _ _ } @[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl @[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl instance : semimodule A (derivation R A M) := { smul := λ a D, ⟨a • D, λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm a, add_comm] }⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul A _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul A _ } @[simp] lemma smul_apply : (a • D) b = a • D b := rfl instance : is_scalar_tower R A (derivation R A M) := ⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩ end section variables {R : Type*} [comm_ring R] variables {A : Type*} [comm_ring A] [algebra R A] section variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) @[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a @[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b instance : add_comm_group (derivation R A M) := { neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩, sub := λ D1 D2, ⟨D1 - D2, λ a b, by { simp only [linear_map.to_fun_eq_coe, linear_map.sub_apply, leibniz, coe_fn_coe, smul_sub], abel }⟩, sub_eq_add_neg := λ D1 D2, ext (λ i, sub_eq_add_neg _ _), add_left_neg := λ D, ext $ λ a, add_left_neg _, ..derivation.add_comm_monoid } @[simp] lemma sub_apply : (D1 - D2) a = D1 a - D2 a := rfl end section lie_structures /-! # Lie structures -/ variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A) /-- The commutator of derivations is again a derivation. -/ def commutator (D1 D2 : derivation R A A) : derivation R A A := { leibniz' := λ a b, by { simp only [ring.lie_def, map_add, id.smul_eq_mul, linear_map.mul_apply, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring, }, ..⁅(D1 : module.End R A), (D2 : module.End R A)⁆, } instance : has_bracket (derivation R A A) (derivation R A A) := ⟨derivation.commutator⟩ @[simp] lemma commutator_coe_linear_map : ↑⁅D1, D2⁆ = ⁅(D1 : module.End R A), (D2 : module.End R A)⁆ := rfl lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl instance : lie_ring (derivation R A A) := { add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, leibniz_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, sub_apply, map_sub], ring, } } instance : lie_algebra R (derivation R A A) := { lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]}, ..derivation.Rsemimodule } end lie_structures end end derivation section comp_der namespace linear_map variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M] variables {N : Type*} [add_cancel_comm_monoid N] [semimodule A N] [semimodule R N] variables [is_scalar_tower R A M] [is_scalar_tower R A N] /-- The composition of a linear map and a derivation is a derivation. -/ def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N := { to_fun := λ a, f (D a), map_add' := λ a1 a2, by rw [D.map_add, f.map_add], map_smul' := λ r a, by rw [derivation.map_smul, map_smul_of_tower], leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add, add_comm] } @[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) : f.comp_der D a = f (D a) := rfl end linear_map end comp_der
9be072cbb890935be9a585048fe317d9cd0bf75c
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/group_theory/semidirect_product.lean
6049fb991a8a2fcdc988d0a224733e5cb492a60c
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
6,999
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.mul_add logic.function.basic group_theory.subgroup /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* N ⋊[φ] G` and `inr : G →* N ⋊[φ] G`, and `lift` can be used to define maps `N ⋊[φ] G →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `N ⋊[φ] G` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (N : Type*) (G : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure semidirect_product (φ : G →* mul_aut N) := (left : N) (right : G) attribute [pp_using_anonymous_constructor] semidirect_product notation N` ⋊[`:35 φ:35`] `:0 G :35 := semidirect_product N G φ namespace semidirect_product variables {N G} {φ : G →* mul_aut N} private def one_aux : N ⋊[φ] G := ⟨1, 1⟩ private def mul_aux (a b : N ⋊[φ] G) : N ⋊[φ] G := ⟨a.1 * φ a.2 b.1, a.right * b.right⟩ private def inv_aux (a : N ⋊[φ] G) : N ⋊[φ] G := let i := a.2⁻¹ in ⟨φ i a.1⁻¹, i⟩ private lemma mul_assoc_aux (a b c : N ⋊[φ] G) : mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) := by simp [mul_aux, mul_assoc, mul_equiv.map_mul] private lemma mul_one_aux (a : N ⋊[φ] G) : mul_aux a one_aux = a := by cases a; simp [mul_aux, one_aux] private lemma one_mul_aux (a : N ⋊[φ] G) : mul_aux one_aux a = a := by cases a; simp [mul_aux, one_aux] private lemma mul_left_inv_aux (a : N ⋊[φ] G) : mul_aux (inv_aux a) a = one_aux := by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp instance : group (N ⋊[φ] G) := { one := one_aux, inv := inv_aux, mul := mul_aux, mul_assoc := mul_assoc_aux, one_mul := one_mul_aux, mul_one := mul_one_aux, mul_left_inv := mul_left_inv_aux } instance : inhabited (N ⋊[φ] G) := ⟨1⟩ @[simp] lemma one_left : (1 : N ⋊[φ] G).left = 1 := rfl @[simp] lemma one_right : (1 : N ⋊[φ] G).right = 1 := rfl @[simp] lemma inv_left (a : N ⋊[φ] G) : (a⁻¹).left = φ a.right⁻¹ a.left⁻¹ := rfl @[simp] lemma inv_right (a : N ⋊[φ] G) : (a⁻¹).right = a.right⁻¹ := rfl @[simp] lemma mul_left (a b : N ⋊[φ] G) : (a * b).left = a.left * φ a.right b.left := rfl @[simp] lemma mul_right (a b : N ⋊[φ] G) : (a * b).right = a.right * b.right := rfl /-- The canonical map `N →* N ⋊[φ] G` sending `n` to `⟨n, 1⟩` -/ def inl : N →* N ⋊[φ] G := { to_fun := λ n, ⟨n, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (n : N) : (inl n : N ⋊[φ] G).left = n := rfl @[simp] lemma right_inl (n : N) : (inl n : N ⋊[φ] G).right = 1 := rfl lemma inl_injective : function.injective (inl : N → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {n₁ n₂ : N} : (inl n₁ : N ⋊[φ] G) = inl n₂ ↔ n₁ = n₂ := inl_injective.eq_iff /-- The canonical map `G →* N ⋊[φ] G` sending `g` to `⟨1, g⟩` -/ def inr : G →* N ⋊[φ] G := { to_fun := λ g, ⟨1, g⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (g : G) : (inr g : N ⋊[φ] G).left = 1 := rfl @[simp] lemma right_inr (g : G) : (inr g : N ⋊[φ] G).right = g := rfl lemma inr_injective : function.injective (inr : G → N ⋊[φ] G) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {g₁ g₂ : G} : (inr g₁ : N ⋊[φ] G) = inr g₂ ↔ g₁ = g₂ := inr_injective.eq_iff lemma inl_aut (g : G) (n : N) : (inl (φ g n) : N ⋊[φ] G) = inr g * inl n * inr g⁻¹ := by ext; simp lemma inl_left_mul_inr_right (x : N ⋊[φ] G) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `N ⋊[φ] G →* G`, as a group hom. -/ def right_hom : N ⋊[φ] G →* G := { to_fun := semidirect_product.right, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma right_hom_eq_right : (right_hom : N ⋊[φ] G → G) = right := rfl @[simp] lemma right_hom_comp_inl : (right_hom : N ⋊[φ] G →* G).comp inl = 1 := by ext; simp [right_hom] @[simp] lemma right_hom_comp_inr : (right_hom : N ⋊[φ] G →* G).comp inr = monoid_hom.id _ := by ext; simp [right_hom] @[simp] lemma right_hom_inl (n : N) : right_hom (inl n : N ⋊[φ] G) = 1 := by simp [right_hom] @[simp] lemma right_hom_inr (g : G) : right_hom (inr g : N ⋊[φ] G) = g := by simp [right_hom] lemma right_hom_surjective : function.surjective (right_hom : N ⋊[φ] G → G) := function.surjective_iff_has_right_inverse.2 ⟨inr, right_hom_inr⟩ lemma range_inl_eq_ker_right_hom : (inl : N →* N ⋊[φ] G).range = right_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.left, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `N ⋊[φ] G →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) : N ⋊[φ] G →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.to_monoid_hom_apply] at this, simp [this, mul_assoc] end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma lift_unique (F : N ⋊[φ] G →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end end lift end semidirect_product
6a7bacdd55f0e70dbba577a358d1a292bd734559
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/set/intervals/basic.lean
593f7f53c35aa21052d4a49baf3b7fb99992da71
[ "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
35,853
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot, Yury Kudryashov -/ import algebra.order_functions import data.set.basic /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ universe u namespace set open set section intervals variables {α : Type u} [preorder α] {a a₁ a₂ b b₁ b₂ x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} lemma Ioo_def (a b : α) : {x | a < x ∧ x < b} = Ioo a b := rfl lemma Ico_def (a b : α) : {x | a ≤ x ∧ x < b} = Ico a b := rfl lemma Iio_def (a : α) : {x | x < a} = Iio a := rfl lemma Icc_def (a b : α) : {x | a ≤ x ∧ x ≤ b} = Icc a b := rfl lemma Iic_def (b : α) : {x | x ≤ b} = Iic b := rfl lemma Ioc_def (a b : α) : {x | a < x ∧ x ≤ b} = Ioc a b := rfl lemma Ici_def (a : α) : {x | a ≤ x} = Ici a := rfl lemma Ioi_def (a : α) : {x | a < x} = Ioi a := rfl @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : @Ici (order_dual α) _ a = @Iic α _ a := rfl @[simp] lemma dual_Iic : @Iic (order_dual α) _ a = @Ici α _ a := rfl @[simp] lemma dual_Ioi : @Ioi (order_dual α) _ a = @Iio α _ a := rfl @[simp] lemma dual_Iio : @Iio (order_dual α) _ a = @Ioi α _ a := rfl @[simp] lemma dual_Icc : @Icc (order_dual α) _ a b = @Icc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : @Ioc (order_dual α) _ a b = @Ico α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : @Ico (order_dual α) _ a b = @Ioc α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : @Ioo (order_dual α) _ a b = @Ioo α _ b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, le_trans hx.1 hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_le_of_lt hx.1 hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, lt_of_lt_of_le hx.1 hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, lt_trans ha hb, dense⟩ @[simp] lemma nonempty_Ioi [no_top_order α] : (Ioi a).nonempty := no_top a @[simp] lemma nonempty_Iio [no_bot_order α] : (Iio a).nonempty := no_bot a lemma nonempty_Icc_subtype (h : a ≤ b) : nonempty (Icc a b) := nonempty.to_subtype (nonempty_Icc.mpr h) lemma nonempty_Ico_subtype (h : a < b) : nonempty (Ico a b) := nonempty.to_subtype (nonempty_Ico.mpr h) lemma nonempty_Ioc_subtype (h : a < b) : nonempty (Ioc a b) := nonempty.to_subtype (nonempty_Ioc.mpr h) /-- An interval `Ici a` is nonempty. -/ instance nonempty_Ici_subtype : nonempty (Ici a) := nonempty.to_subtype nonempty_Ici /-- An interval `Iic a` is nonempty. -/ instance nonempty_Iic_subtype : nonempty (Iic a) := nonempty.to_subtype nonempty_Iic lemma nonempty_Ioo_subtype [densely_ordered α] (h : a < b) : nonempty (Ioo a b) := nonempty.to_subtype (nonempty_Ioo.mpr h) /-- In a `no_top_order`, the intervals `Ioi` are nonempty. -/ instance nonempty_Ioi_subtype [no_top_order α] : nonempty (Ioi a) := nonempty.to_subtype nonempty_Ioi /-- In a `no_bot_order`, the intervals `Iio` are nonempty. -/ instance nonempty_Iio_subtype [no_bot_order α] : nonempty (Iio a) := nonempty.to_subtype nonempty_Iio @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, le_trans h hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici (order_dual α) _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, lt_of_lt_of_le h hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨lt_of_lt_of_le ha hx.1, lt_of_le_of_lt hx.2 hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', lt_of_le_of_lt h' h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λx hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λx hx, le_of_lt hx lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λx hx, lt_of_le_of_lt h hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λx hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl end intervals section partial_order variables {α : Type u} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] @[simp] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] @[simp] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] @[simp] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] @[simp] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] @[simp] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] @[simp] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] @[simp] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] @[simp] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] @[simp] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] @[simp] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } @[simp] lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] @[simp] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] @[simp] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] @[simp] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by rw [← Ioi_union_left, union_subset_iff]; simp *) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset (order_dual α) _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end lemma mem_Ioo_or_eq_endpoints_of_mem_Icc {x : α} (hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b := begin rw [mem_Icc, le_iff_lt_or_eq, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb | hxb⟩, { exact or.inr (or.inr ⟨hxa, hxb⟩) }, { exact or.inr (or.inl hxb) }, all_goals { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_left_of_mem_Ico {x : α} (hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b := begin rw [mem_Ico, le_iff_lt_or_eq] at hmem, rcases hmem with ⟨hxa | hxa, hxb⟩, { exact or.inr ⟨hxa, hxb⟩ }, { exact or.inl hxa.symm } end lemma mem_Ioo_or_eq_right_of_mem_Ioc {x : α} (hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b := begin have := @mem_Ioo_or_eq_left_of_mem_Ico (order_dual α) _ b a x, rw [dual_Ioo, dual_Ico] at this, exact this hmem end lemma Ici_singleton_of_top {a : α} (h_top : ∀ x, x ≤ a) : Ici a = {a} := begin ext, exact ⟨λ h, le_antisymm (h_top _) h, λ h, le_of_eq h.symm⟩, end lemma Iic_singleton_of_bot {a : α} (h_bot : ∀ x, a ≤ x) : Iic a = {a} := @Ici_singleton_of_top (order_dual α) _ a h_bot end partial_order section order_top_or_bot variables {α : Type u} @[simp] lemma Ici_top [order_top α] : Ici (⊤ : α) = {⊤} := Ici_singleton_of_top (λ _, le_top) @[simp] lemma Ici_bot [order_bot α] : Iic (⊥ : α) = {⊥} := Iic_singleton_of_bot (λ _, bot_le) end order_top_or_bot section linear_order variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le @[simp] lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le @[simp] lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt @[simp] lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt @[simp] lemma Ici_diff_Ici : Ici a \ Ici b = Ico a b := by rw [diff_eq, compl_Ici, Ici_inter_Iio] @[simp] lemma Ici_diff_Ioi : Ici a \ Ioi b = Icc a b := by rw [diff_eq, compl_Ioi, Ici_inter_Iic] @[simp] lemma Ioi_diff_Ioi : Ioi a \ Ioi b = Ioc a b := by rw [diff_eq, compl_Ioi, Ioi_inter_Iic] @[simp] lemma Ioi_diff_Ici : Ioi a \ Ici b = Ioo a b := by rw [diff_eq, compl_Ici, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iic : Iic b \ Iic a = Ioc a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iic] @[simp] lemma Iio_diff_Iic : Iio b \ Iic a = Ioo a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iio : Iic b \ Iio a = Icc a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iic] @[simp] lemma Iio_diff_Iio : Iio b \ Iio a = Ico a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iio] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λh, _, λh, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := dense (not_le.mp ba), exact lt_irrefl _ (lt_of_lt_of_le ca (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λh, _, λh, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := by rw [← diff_eq_empty, Iio_diff_Iic, Ioo_eq_empty_iff] /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Ico_union_Ici lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_le_of_lt h)) Ioi_subset_Ioc_union_Ioi lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (λ hx, le_trans h (le_of_lt hx))) Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left (lt_of_lt_of_le h)) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left (le_trans h)) Ici_subset_Icc_union_Ici /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans (le_of_lt hx) h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_lt_of_le hx h) and.right) Iio_subset_Iio_union_Ico lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Ioc lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ioo lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, le_trans hx h) and.right) Iic_subset_Iic_union_Icc lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx, lt_of_le_of_lt hx h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ variable {c : α} lemma Ioo_subset_Ioo_union_Ico : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ico lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_lt_of_le hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans (le_of_lt hx.2) h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ (le_of_lt hx.1), hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_le_of_lt h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, lt_of_le_of_lt hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨le_trans h₁ hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, le_trans hx.2 h₂⟩) (λ hx, ⟨lt_of_lt_of_le h₁ hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc end linear_order section lattice section inf variables {α : Type u} [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Iio_inter_Iio [is_total α (≤)] {a b : α} : Iio a ∩ Iio b = Iio (a ⊓ b) := by { ext x, simp [Iio] } end inf section sup variables {α : Type u} [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ioi_inter_Ioi [is_total α (≤)] {a b : α} : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := by { ext x, simp [Ioi] } end sup section both variables {α : Type u} [lattice α] [ht : is_total α (≤)] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] include ht lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl end both end lattice section decidable_linear_order variables {α : Type u} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} @[simp] lemma Ico_diff_Iio : Ico a b \ Iio c = Ico (max a c) b := ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio : Ico a b ∩ Iio c = Ico a (min b c) := ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} lemma Ioc_union_Ioc (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { ext x, simp [iff_def, and_imp, or_imp_distrib, (h₂.lt_or_le x).symm, h₁.lt_or_le] { contextual := tt } }, all_goals { simp [*] } end @[simp] lemma Ioc_union_Ioc_right : Ioc a b ∪ Ioc a c = Ioc a (max b c) := by rw [Ioc_union_Ioc, min_self]; exact (min_le_left _ _).trans (le_max_left _ _) @[simp] lemma Ioc_union_Ioc_left : Ioc a c ∪ Ioc b c = Ioc (min a b) c := by rw [Ioc_union_Ioc, max_self]; exact (min_le_right _ _).trans (le_max_right _ _) @[simp] lemma Ioc_union_Ioc_symm : Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) := by { rw max_comm, apply Ioc_union_Ioc; rw max_comm; exact min_le_max } @[simp] lemma Ioc_union_Ioc_union_Ioc_cycle : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) := begin rw [Ioc_union_Ioc, Ioc_union_Ioc], ac_refl, all_goals { solve_by_elim [min_le_left_of_le, min_le_right_of_le, le_max_left_of_le, le_max_right_of_le, le_refl] { max_depth := 5 }} end end decidable_linear_order section decidable_linear_ordered_add_comm_group variables {α : Type u} [decidable_linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp* }, { use max x (x + dy), simp [*, le_refl] } end end decidable_linear_ordered_add_comm_group end set
3f8e53bc95cb92633a5dd8f4c0a4f258f1ec52b7
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/options.lean
ee8601d81345bac9120f64856aae71eb7e426dcf
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,286
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.name universe u meta constant options : Type meta constant options.size : options → nat meta constant options.mk : options meta constant options.contains : options → name → bool meta constant options.set_bool : options → name → bool → options meta constant options.set_nat : options → name → nat → options meta constant options.set_string : options → name → string → options meta constant options.get_bool : options → name → bool → bool meta constant options.get_nat : options → name → nat → nat meta constant options.get_string : options → name → string → string meta constant options.join : options → options → options meta constant options.fold {α : Type u} : options → α → (name → α → α) → α meta constant options.has_decidable_eq : decidable_eq options attribute [instance] options.has_decidable_eq meta instance : has_add options := ⟨options.join⟩ meta instance : inhabited options := ⟨options.mk⟩
8f803869c3e793d2d5f7bc132a04f722244b5d85
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Data.lean
eba3145383b807111d251c10a125de34bca9083d
[ "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
524
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Data.Format import Lean.Data.FormatMacro import Lean.Data.Json import Lean.Data.JsonRpc import Lean.Data.KVMap import Lean.Data.LBool import Lean.Data.LOption import Lean.Data.Lsp import Lean.Data.Name import Lean.Data.Occurrences import Lean.Data.OpenDecl import Lean.Data.Options import Lean.Data.Position import Lean.Data.SMap import Lean.Data.Trie
0d72097fadd11ccd0aed5683d1fd533823508e26
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/extractClosedMutualBlock.lean
1af9b8b333d9b168c4104e140d68a3930c03d40c
[ "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
418
lean
inductive Foo | mk: (Int -> Foo) -> Foo | terminal: Foo deriving Inhabited mutual partial def even (_: Unit) : Foo := Foo.mk (fun i => odd () ) partial def odd (_: Unit) : Foo := Foo.mk (fun i => even ()) end def hasLayer (f: Foo) : Bool := match f with | Foo.mk _ => true | Foo.terminal => false def main : IO Unit := do IO.println (if hasLayer (odd ()) then "LAYER" else "TERMINAL") return ()
5b20c76b6f02424abaf8f9a1a7cc7f9cf21d1aa5
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/metric_space/closeds.lean
9c8d0b126c6565e555f4a8b4c10f9192ab2cf3bf
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,421
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance import analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical open_locale topological_space universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right inf_edist_le_inf_edist_add_edist _ ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm, -subtype.val_eq_coe] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa hs.closure_eq at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ennreal) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.div_def, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.div_def, ennreal.inv_pow], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto y_lim begin simp only [exists_prop, set.mem_Union, filter.eventually_at_top, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine fs.finite_subsets.subset (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := (fs.subset t0s).is_compact.is_closed, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [s.property.2.is_closed.closure_eq, t.property.2.is_closed.closure_eq] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ is_compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, s.property.is_complete⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding).2 $ nonempty_compacts.is_closed_in_closeds.is_complete /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine (countable_set_of_finite_subset cs).mono (λx hx, _), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply subtype.val_injective.inj_on }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases exists_between εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := af.image _, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := ‹finite b›.subset (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.is_compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
5c480834744d2c84272f26b7d052f813b6a7c948
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/asymptotics/asymptotics.lean
d3af26c25320c0809d8a580ccbd9a5cd91881b5b
[ "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
73,611
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov -/ import analysis.normed_space.basic import topology.algebra.order.liminf_limsup import topology.local_homeomorph /-! # Asymptotics We introduce these relations: * `is_O_with c l f g` : "f is big O of g along l with constant c"; * `f =O[l] g` : "f is big O of g along l"; * `f =o[l] g` : "f is little o of g along l". Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. The relation `is_O_with c` is introduced to factor out common algebraic arguments in the proofs of similar properties of `is_O` and `is_o`. Usually proofs outside of this file should use `is_O` instead. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `f =O[l] g ↔ (λ x, ‖f x‖) =O[l] (λ x, ‖g x‖)`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `f =o[l] g ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter set open_locale topological_space big_operators classical filter nnreal namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {E'' : Type*} {F'' : Type*} {G'' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] variables [seminormed_add_comm_group E'] [seminormed_add_comm_group F'] [seminormed_add_comm_group G'] [normed_add_comm_group E''] [normed_add_comm_group F''] [normed_add_comm_group G''] [semi_normed_ring R] [semi_normed_ring R'] variables [normed_field 𝕜] [normed_field 𝕜'] variables {c c' c₁ c₂ : ℝ} {f : α → E} {g : α → F} {k : α → G} variables {f' : α → E'} {g' : α → F'} {k' : α → G'} variables {f'' : α → E''} {g'' : α → F''} {k'' : α → G''} variables {l l' : filter α} section defs /-! ### Definitions -/ /-- This version of the Landau notation `is_O_with C l f g` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `‖f‖` is bounded by `C * ‖g‖`. In other words, `‖f‖ / ‖g‖` is eventually bounded by `C`, modulo division by zero issues that are avoided by this definition. Probably you want to use `is_O` instead of this relation. -/ @[irreducible] def is_O_with (c : ℝ) (l : filter α) (f : α → E) (g : α → F) : Prop := ∀ᶠ x in l, ‖ f x ‖ ≤ c * ‖ g x ‖ /-- Definition of `is_O_with`. We record it in a lemma as `is_O_with` is irreducible. -/ lemma is_O_with_iff : is_O_with c l f g ↔ ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖ := by rw is_O_with alias is_O_with_iff ↔ is_O_with.bound is_O_with.of_bound /-- The Landau notation `f =O[l] g` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `‖f‖` is bounded by a constant multiple of `‖g‖`. In other words, `‖f‖ / ‖g‖` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ @[irreducible] def is_O (l : filter α) (f : α → E) (g : α → F) : Prop := ∃ c : ℝ, is_O_with c l f g notation f ` =O[`:100 l `] ` g:100 := is_O l f g /-- Definition of `is_O` in terms of `is_O_with`. We record it in a lemma as `is_O` is irreducible. -/ lemma is_O_iff_is_O_with : f =O[l] g ↔ ∃ c : ℝ, is_O_with c l f g := by rw is_O /-- Definition of `is_O` in terms of filters. We record it in a lemma as we will set `is_O` to be irreducible at the end of this file. -/ lemma is_O_iff : f =O[l] g ↔ ∃ c : ℝ, ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖ := by simp only [is_O, is_O_with] lemma is_O.of_bound (c : ℝ) (h : ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖) : f =O[l] g := is_O_iff.2 ⟨c, h⟩ lemma is_O.of_bound' (h : ∀ᶠ x in l, ‖f x‖ ≤ ‖g x‖) : f =O[l] g := is_O.of_bound 1 $ by { simp_rw one_mul, exact h } lemma is_O.bound : f =O[l] g → ∃ c : ℝ, ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖ := is_O_iff.1 /-- The Landau notation `f =o[l] g` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `‖f‖` is bounded by an arbitrarily small constant multiple of `‖g‖`. In other words, `‖f‖ / ‖g‖` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ @[irreducible] def is_o (l : filter α) (f : α → E) (g : α → F) : Prop := ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c l f g notation f ` =o[`:100 l `] ` g:100 := is_o l f g /-- Definition of `is_o` in terms of `is_O_with`. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff_forall_is_O_with : f =o[l] g ↔ ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c l f g := by rw is_o alias is_o_iff_forall_is_O_with ↔ is_o.forall_is_O_with is_o.of_is_O_with /-- Definition of `is_o` in terms of filters. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff : f =o[l] g ↔ ∀ ⦃c : ℝ⦄, 0 < c → ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖ := by simp only [is_o, is_O_with] alias is_o_iff ↔ is_o.bound is_o.of_bound lemma is_o.def (h : f =o[l] g) (hc : 0 < c) : ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖ := is_o_iff.1 h hc lemma is_o.def' (h : f =o[l] g) (hc : 0 < c) : is_O_with c l f g := is_O_with_iff.2 $ is_o_iff.1 h hc end defs /-! ### Conversions -/ theorem is_O_with.is_O (h : is_O_with c l f g) : f =O[l] g := by rw is_O; exact ⟨c, h⟩ theorem is_o.is_O_with (hgf : f =o[l] g) : is_O_with 1 l f g := hgf.def' zero_lt_one theorem is_o.is_O (hgf : f =o[l] g) : f =O[l] g := hgf.is_O_with.is_O lemma is_O.is_O_with : f =O[l] g → ∃ c : ℝ, is_O_with c l f g := is_O_iff_is_O_with.1 theorem is_O_with.weaken (h : is_O_with c l f g') (hc : c ≤ c') : is_O_with c' l f g' := is_O_with.of_bound $ mem_of_superset h.bound $ λ x hx, calc ‖f x‖ ≤ c * ‖g' x‖ : hx ... ≤ _ : mul_le_mul_of_nonneg_right hc (norm_nonneg _) theorem is_O_with.exists_pos (h : is_O_with c l f g') : ∃ c' (H : 0 < c'), is_O_with c' l f g' := ⟨max c 1, lt_of_lt_of_le zero_lt_one (le_max_right c 1), h.weaken $ le_max_left c 1⟩ theorem is_O.exists_pos (h : f =O[l] g') : ∃ c (H : 0 < c), is_O_with c l f g' := let ⟨c, hc⟩ := h.is_O_with in hc.exists_pos theorem is_O_with.exists_nonneg (h : is_O_with c l f g') : ∃ c' (H : 0 ≤ c'), is_O_with c' l f g' := let ⟨c, cpos, hc⟩ := h.exists_pos in ⟨c, le_of_lt cpos, hc⟩ theorem is_O.exists_nonneg (h : f =O[l] g') : ∃ c (H : 0 ≤ c), is_O_with c l f g' := let ⟨c, hc⟩ := h.is_O_with in hc.exists_nonneg /-- `f = O(g)` if and only if `is_O_with c f g` for all sufficiently large `c`. -/ lemma is_O_iff_eventually_is_O_with : f =O[l] g' ↔ ∀ᶠ c in at_top, is_O_with c l f g' := is_O_iff_is_O_with.trans ⟨λ ⟨c, hc⟩, mem_at_top_sets.2 ⟨c, λ c' hc', hc.weaken hc'⟩, λ h, h.exists⟩ /-- `f = O(g)` if and only if `∀ᶠ x in l, ‖f x‖ ≤ c * ‖g x‖` for all sufficiently large `c`. -/ lemma is_O_iff_eventually : f =O[l] g' ↔ ∀ᶠ c in at_top, ∀ᶠ x in l, ‖f x‖ ≤ c * ‖g' x‖ := is_O_iff_eventually_is_O_with.trans $ by simp only [is_O_with] lemma is_O.exists_mem_basis {ι} {p : ι → Prop} {s : ι → set α} (h : f =O[l] g') (hb : l.has_basis p s) : ∃ (c : ℝ) (hc : 0 < c) (i : ι) (hi : p i), ∀ x ∈ s i, ‖f x‖ ≤ c * ‖g' x‖ := flip Exists₂.imp h.exists_pos $ λ c hc h, by simpa only [is_O_with_iff, hb.eventually_iff, exists_prop] using h lemma is_O_with_inv (hc : 0 < c) : is_O_with c⁻¹ l f g ↔ ∀ᶠ x in l, c * ‖f x‖ ≤ ‖g x‖ := by simp only [is_O_with, ← div_eq_inv_mul, le_div_iff' hc] -- We prove this lemma with strange assumptions to get two lemmas below automatically lemma is_o_iff_nat_mul_le_aux (h₀ : (∀ x, 0 ≤ ‖f x‖) ∨ ∀ x, 0 ≤ ‖g x‖) : f =o[l] g ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ‖f x‖ ≤ ‖g x‖ := begin split, { rintro H (_|n), { refine (H.def one_pos).mono (λ x h₀', _), rw [nat.cast_zero, zero_mul], refine h₀.elim (λ hf, (hf x).trans _) (λ hg, hg x), rwa one_mul at h₀' }, { have : (0 : ℝ) < n.succ, from nat.cast_pos.2 n.succ_pos, exact (is_O_with_inv this).1 (H.def' $ inv_pos.2 this) } }, { refine λ H, is_o_iff.2 (λ ε ε0, _), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have hn₀ : (0 : ℝ) < n, from (inv_pos.2 ε0).trans hn, refine ((is_O_with_inv hn₀).2 (H n)).bound.mono (λ x hfg, _), refine hfg.trans (mul_le_mul_of_nonneg_right (inv_le_of_inv_le ε0 hn.le) _), refine h₀.elim (λ hf, nonneg_of_mul_nonneg_right ((hf x).trans hfg) _) (λ h, h x), exact inv_pos.2 hn₀ } end lemma is_o_iff_nat_mul_le : f =o[l] g' ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ‖f x‖ ≤ ‖g' x‖ := is_o_iff_nat_mul_le_aux (or.inr $ λ x, norm_nonneg _) lemma is_o_iff_nat_mul_le' : f' =o[l] g ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ‖f' x‖ ≤ ‖g x‖ := is_o_iff_nat_mul_le_aux (or.inl $ λ x, norm_nonneg _) /-! ### Subsingleton -/ @[nontriviality] lemma is_o_of_subsingleton [subsingleton E'] : f' =o[l] g' := is_o.of_bound $ λ c hc, by simp [subsingleton.elim (f' _) 0, mul_nonneg hc.le] @[nontriviality] lemma is_O_of_subsingleton [subsingleton E'] : f' =O[l] g' := is_o_of_subsingleton.is_O section congr variables {f₁ f₂ : α → E} {g₁ g₂ : α → F} /-! ### Congruence -/ theorem is_O_with_congr (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₁ l f₁ g₁ ↔ is_O_with c₂ l f₂ g₂ := begin unfold is_O_with, subst c₂, apply filter.eventually_congr, filter_upwards [hf, hg] with _ e₁ e₂, rw [e₁, e₂], end theorem is_O_with.congr' (h : is_O_with c₁ l f₁ g₁) (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₂ l f₂ g₂ := (is_O_with_congr hc hf hg).mp h theorem is_O_with.congr (h : is_O_with c₁ l f₁ g₁) (hc : c₁ = c₂) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c₂ l f₂ g₂ := h.congr' hc (univ_mem' hf) (univ_mem' hg) theorem is_O_with.congr_left (h : is_O_with c l f₁ g) (hf : ∀ x, f₁ x = f₂ x) : is_O_with c l f₂ g := h.congr rfl hf (λ _, rfl) theorem is_O_with.congr_right (h : is_O_with c l f g₁) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c l f g₂ := h.congr rfl (λ _, rfl) hg theorem is_O_with.congr_const (h : is_O_with c₁ l f g) (hc : c₁ = c₂) : is_O_with c₂ l f g := h.congr hc (λ _, rfl) (λ _, rfl) theorem is_O_congr (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₁ =O[l] g₁ ↔ f₂ =O[l] g₂ := by { unfold is_O, exact exists_congr (λ c, is_O_with_congr rfl hf hg) } theorem is_O.congr' (h : f₁ =O[l] g₁) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₂ =O[l] g₂ := (is_O_congr hf hg).mp h theorem is_O.congr (h : f₁ =O[l] g₁) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : f₂ =O[l] g₂ := h.congr' (univ_mem' hf) (univ_mem' hg) theorem is_O.congr_left (h : f₁ =O[l] g) (hf : ∀ x, f₁ x = f₂ x) : f₂ =O[l] g := h.congr hf (λ _, rfl) theorem is_O.congr_right (h : f =O[l] g₁) (hg : ∀ x, g₁ x = g₂ x) : f =O[l] g₂ := h.congr (λ _, rfl) hg theorem is_o_congr (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₁ =o[l] g₁ ↔ f₂ =o[l] g₂ := by { unfold is_o, exact forall₂_congr (λ c hc, is_O_with_congr (eq.refl c) hf hg) } theorem is_o.congr' (h : f₁ =o[l] g₁) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : f₂ =o[l] g₂ := (is_o_congr hf hg).mp h theorem is_o.congr (h : f₁ =o[l] g₁) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : f₂ =o[l] g₂ := h.congr' (univ_mem' hf) (univ_mem' hg) theorem is_o.congr_left (h : f₁ =o[l] g) (hf : ∀ x, f₁ x = f₂ x) : f₂ =o[l] g := h.congr hf (λ _, rfl) theorem is_o.congr_right (h : f =o[l] g₁) (hg : ∀ x, g₁ x = g₂ x) : f =o[l] g₂ := h.congr (λ _, rfl) hg @[trans] theorem _root_.filter.eventually_eq.trans_is_O {f₁ f₂ : α → E} {g : α → F} (hf : f₁ =ᶠ[l] f₂) (h : f₂ =O[l] g) : f₁ =O[l] g := h.congr' hf.symm eventually_eq.rfl @[trans] theorem _root_.filter.eventually_eq.trans_is_o {f₁ f₂ : α → E} {g : α → F} (hf : f₁ =ᶠ[l] f₂) (h : f₂ =o[l] g) : f₁ =o[l] g := h.congr' hf.symm eventually_eq.rfl @[trans] theorem is_O.trans_eventually_eq {f : α → E} {g₁ g₂ : α → F} (h : f =O[l] g₁) (hg : g₁ =ᶠ[l] g₂) : f =O[l] g₂ := h.congr' eventually_eq.rfl hg @[trans] theorem is_o.trans_eventually_eq {f : α → E} {g₁ g₂ : α → F} (h : f =o[l] g₁) (hg : g₁ =ᶠ[l] g₂) : f =o[l] g₂ := h.congr' eventually_eq.rfl hg end congr /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto (hcfg : is_O_with c l f g) {k : β → α} {l' : filter β} (hk : tendsto k l' l): is_O_with c l' (f ∘ k) (g ∘ k) := is_O_with.of_bound $ hk hcfg.bound theorem is_O.comp_tendsto (hfg : f =O[l] g) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : (f ∘ k) =O[l'] (g ∘ k) := is_O_iff_is_O_with.2 $ hfg.is_O_with.imp (λ c h, h.comp_tendsto hk) theorem is_o.comp_tendsto (hfg : f =o[l] g) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : (f ∘ k) =o[l'] (g ∘ k) := is_o.of_is_O_with $ λ c cpos, (hfg.forall_is_O_with cpos).comp_tendsto hk @[simp] theorem is_O_with_map {k : β → α} {l : filter β} : is_O_with c (map k l) f g ↔ is_O_with c l (f ∘ k) (g ∘ k) := by { unfold is_O_with, exact eventually_map } @[simp] theorem is_O_map {k : β → α} {l : filter β} : f =O[map k l] g ↔ (f ∘ k) =O[l] (g ∘ k) := by simp only [is_O, is_O_with_map] @[simp] theorem is_o_map {k : β → α} {l : filter β} : f =o[map k l] g ↔ (f ∘ k) =o[l] (g ∘ k) := by simp only [is_o, is_O_with_map] theorem is_O_with.mono (h : is_O_with c l' f g) (hl : l ≤ l') : is_O_with c l f g := is_O_with.of_bound $ hl h.bound theorem is_O.mono (h : f =O[l'] g) (hl : l ≤ l') : f =O[l] g := is_O_iff_is_O_with.2 $ h.is_O_with.imp (λ c h, h.mono hl) theorem is_o.mono (h : f =o[l'] g) (hl : l ≤ l') : f =o[l] g := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).mono hl theorem is_O_with.trans (hfg : is_O_with c l f g) (hgk : is_O_with c' l g k) (hc : 0 ≤ c) : is_O_with (c * c') l f k := begin unfold is_O_with at *, filter_upwards [hfg, hgk] with x hx hx', calc ‖f x‖ ≤ c * ‖g x‖ : hx ... ≤ c * (c' * ‖k x‖) : mul_le_mul_of_nonneg_left hx' hc ... = c * c' * ‖k x‖ : (mul_assoc _ _ _).symm end @[trans] theorem is_O.trans {f : α → E} {g : α → F'} {k : α → G} (hfg : f =O[l] g) (hgk : g =O[l] k) : f =O[l] k := let ⟨c, cnonneg, hc⟩ := hfg.exists_nonneg, ⟨c', hc'⟩ := hgk.is_O_with in (hc.trans hc' cnonneg).is_O theorem is_o.trans_is_O_with (hfg : f =o[l] g) (hgk : is_O_with c l g k) (hc : 0 < c) : f =o[l] k := begin unfold is_o at *, intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact ((hfg this).trans hgk this.le).congr_const (div_mul_cancel _ hc.ne') end @[trans] theorem is_o.trans_is_O {f : α → E} {g : α → F} {k : α → G'} (hfg : f =o[l] g) (hgk : g =O[l] k) : f =o[l] k := let ⟨c, cpos, hc⟩ := hgk.exists_pos in hfg.trans_is_O_with hc cpos theorem is_O_with.trans_is_o (hfg : is_O_with c l f g) (hgk : g =o[l] k) (hc : 0 < c) : f =o[l] k := begin unfold is_o at *, intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact (hfg.trans (hgk this) hc.le).congr_const (mul_div_cancel' _ hc.ne') end @[trans] theorem is_O.trans_is_o {f : α → E} {g : α → F'} {k : α → G} (hfg : f =O[l] g) (hgk : g =o[l] k) : f =o[l] k := let ⟨c, cpos, hc⟩ := hfg.exists_pos in hc.trans_is_o hgk cpos @[trans] theorem is_o.trans {f : α → E} {g : α → F} {k : α → G} (hfg : f =o[l] g) (hgk : g =o[l] k) : f =o[l] k := hfg.trans_is_O_with hgk.is_O_with one_pos lemma _root_.filter.eventually.trans_is_O {f : α → E} {g : α → F'} {k : α → G} (hfg : ∀ᶠ x in l, ‖f x‖ ≤ ‖g x‖) (hgk : g =O[l] k) : f =O[l] k := (is_O.of_bound' hfg).trans hgk lemma _root_.filter.eventually.is_O {f : α → E} {g : α → ℝ} {l : filter α} (hfg : ∀ᶠ x in l, ‖f x‖ ≤ g x) : f =O[l] g := is_O.of_bound' $ hfg.mono $ λ x hx, hx.trans $ real.le_norm_self _ section variable (l) theorem is_O_with_of_le' (hfg : ∀ x, ‖f x‖ ≤ c * ‖g x‖) : is_O_with c l f g := is_O_with.of_bound $ univ_mem' hfg theorem is_O_with_of_le (hfg : ∀ x, ‖f x‖ ≤ ‖g x‖) : is_O_with 1 l f g := is_O_with_of_le' l $ λ x, by { rw one_mul, exact hfg x } theorem is_O_of_le' (hfg : ∀ x, ‖f x‖ ≤ c * ‖g x‖) : f =O[l] g := (is_O_with_of_le' l hfg).is_O theorem is_O_of_le (hfg : ∀ x, ‖f x‖ ≤ ‖g x‖) : f =O[l] g := (is_O_with_of_le l hfg).is_O end theorem is_O_with_refl (f : α → E) (l : filter α) : is_O_with 1 l f f := is_O_with_of_le l $ λ _, le_rfl theorem is_O_refl (f : α → E) (l : filter α) : f =O[l] f := (is_O_with_refl f l).is_O theorem is_O_with.trans_le (hfg : is_O_with c l f g) (hgk : ∀ x, ‖g x‖ ≤ ‖k x‖) (hc : 0 ≤ c) : is_O_with c l f k := (hfg.trans (is_O_with_of_le l hgk) hc).congr_const $ mul_one c theorem is_O.trans_le (hfg : f =O[l] g') (hgk : ∀ x, ‖g' x‖ ≤ ‖k x‖) : f =O[l] k := hfg.trans (is_O_of_le l hgk) theorem is_o.trans_le (hfg : f =o[l] g) (hgk : ∀ x, ‖g x‖ ≤ ‖k x‖) : f =o[l] k := hfg.trans_is_O_with (is_O_with_of_le _ hgk) zero_lt_one theorem is_o_irrefl' (h : ∃ᶠ x in l, ‖f' x‖ ≠ 0) : ¬f' =o[l] f' := begin intro ho, rcases ((ho.bound one_half_pos).and_frequently h).exists with ⟨x, hle, hne⟩, rw [one_div, ← div_eq_inv_mul] at hle, exact (half_lt_self (lt_of_le_of_ne (norm_nonneg _) hne.symm)).not_le hle end theorem is_o_irrefl (h : ∃ᶠ x in l, f'' x ≠ 0) : ¬f'' =o[l] f'' := is_o_irrefl' $ h.mono $ λ x, norm_ne_zero_iff.mpr theorem is_O.not_is_o (h : f'' =O[l] g') (hf : ∃ᶠ x in l, f'' x ≠ 0) : ¬g' =o[l] f'' := λ h', is_o_irrefl hf (h.trans_is_o h') theorem is_o.not_is_O (h : f'' =o[l] g') (hf : ∃ᶠ x in l, f'' x ≠ 0) : ¬g' =O[l] f'' := λ h', is_o_irrefl hf (h.trans_is_O h') section bot variables (c f g) @[simp] theorem is_O_with_bot : is_O_with c ⊥ f g := is_O_with.of_bound $ trivial @[simp] theorem is_O_bot : f =O[⊥] g := (is_O_with_bot 1 f g).is_O @[simp] theorem is_o_bot : f =o[⊥] g := is_o.of_is_O_with $ λ c _, is_O_with_bot c f g end bot @[simp] theorem is_O_with_pure {x} : is_O_with c (pure x) f g ↔ ‖f x‖ ≤ c * ‖g x‖ := is_O_with_iff theorem is_O_with.sup (h : is_O_with c l f g) (h' : is_O_with c l' f g) : is_O_with c (l ⊔ l') f g := is_O_with.of_bound $ mem_sup.2 ⟨h.bound, h'.bound⟩ theorem is_O_with.sup' (h : is_O_with c l f g') (h' : is_O_with c' l' f g') : is_O_with (max c c') (l ⊔ l') f g' := is_O_with.of_bound $ mem_sup.2 ⟨(h.weaken $ le_max_left c c').bound, (h'.weaken $ le_max_right c c').bound⟩ theorem is_O.sup (h : f =O[l] g') (h' : f =O[l'] g') : f =O[l ⊔ l'] g' := let ⟨c, hc⟩ := h.is_O_with, ⟨c', hc'⟩ := h'.is_O_with in (hc.sup' hc').is_O theorem is_o.sup (h : f =o[l] g) (h' : f =o[l'] g) : f =o[l ⊔ l'] g := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).sup (h'.forall_is_O_with cpos) @[simp] lemma is_O_sup : f =O[l ⊔ l'] g' ↔ f =O[l] g' ∧ f =O[l'] g' := ⟨λ h, ⟨h.mono le_sup_left, h.mono le_sup_right⟩, λ h, h.1.sup h.2⟩ @[simp] lemma is_o_sup : f =o[l ⊔ l'] g ↔ f =o[l] g ∧ f =o[l'] g := ⟨λ h, ⟨h.mono le_sup_left, h.mono le_sup_right⟩, λ h, h.1.sup h.2⟩ lemma is_O_with_insert [topological_space α] {x : α} {s : set α} {C : ℝ} {g : α → E} {g' : α → F} (h : ‖g x‖ ≤ C * ‖g' x‖) : is_O_with C (𝓝[insert x s] x) g g' ↔ is_O_with C (𝓝[s] x) g g' := by simp_rw [is_O_with, nhds_within_insert, eventually_sup, eventually_pure, h, true_and] lemma is_O_with.insert [topological_space α] {x : α} {s : set α} {C : ℝ} {g : α → E} {g' : α → F} (h1 : is_O_with C (𝓝[s] x) g g') (h2 : ‖g x‖ ≤ C * ‖g' x‖) : is_O_with C (𝓝[insert x s] x) g g' := (is_O_with_insert h2).mpr h1 lemma is_o_insert [topological_space α] {x : α} {s : set α} {g : α → E'} {g' : α → F'} (h : g x = 0) : g =o[𝓝[insert x s] x] g' ↔ g =o[𝓝[s] x] g' := begin simp_rw [is_o], refine forall_congr (λ c, forall_congr (λ hc, _)), rw [is_O_with_insert], rw [h, norm_zero], exact mul_nonneg hc.le (norm_nonneg _) end lemma is_o.insert [topological_space α] {x : α} {s : set α} {g : α → E'} {g' : α → F'} (h1 : g =o[𝓝[s] x] g') (h2 : g x = 0) : g =o[𝓝[insert x s] x] g' := (is_o_insert h2).mpr h1 /-! ### Simplification : norm, abs -/ section norm_abs variables {u v : α → ℝ} @[simp] theorem is_O_with_norm_right : is_O_with c l f (λ x, ‖g' x‖) ↔ is_O_with c l f g' := by simp only [is_O_with, norm_norm] @[simp] theorem is_O_with_abs_right : is_O_with c l f (λ x, |u x|) ↔ is_O_with c l f u := @is_O_with_norm_right _ _ _ _ _ _ f u l alias is_O_with_norm_right ↔ is_O_with.of_norm_right is_O_with.norm_right alias is_O_with_abs_right ↔ is_O_with.of_abs_right is_O_with.abs_right @[simp] theorem is_O_norm_right : f =O[l] (λ x, ‖g' x‖) ↔ f =O[l] g' := by { unfold is_O, exact exists_congr (λ _, is_O_with_norm_right) } @[simp] theorem is_O_abs_right : f =O[l] (λ x, |u x|) ↔ f =O[l] u := @is_O_norm_right _ _ ℝ _ _ _ _ _ alias is_O_norm_right ↔ is_O.of_norm_right is_O.norm_right alias is_O_abs_right ↔ is_O.of_abs_right is_O.abs_right @[simp] theorem is_o_norm_right : f =o[l] (λ x, ‖g' x‖) ↔ f =o[l] g' := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_norm_right) } @[simp] theorem is_o_abs_right : f =o[l] (λ x, |u x|) ↔ f =o[l] u := @is_o_norm_right _ _ ℝ _ _ _ _ _ alias is_o_norm_right ↔ is_o.of_norm_right is_o.norm_right alias is_o_abs_right ↔ is_o.of_abs_right is_o.abs_right @[simp] theorem is_O_with_norm_left : is_O_with c l (λ x, ‖f' x‖) g ↔ is_O_with c l f' g := by simp only [is_O_with, norm_norm] @[simp] theorem is_O_with_abs_left : is_O_with c l (λ x, |u x|) g ↔ is_O_with c l u g := @is_O_with_norm_left _ _ _ _ _ _ g u l alias is_O_with_norm_left ↔ is_O_with.of_norm_left is_O_with.norm_left alias is_O_with_abs_left ↔ is_O_with.of_abs_left is_O_with.abs_left @[simp] theorem is_O_norm_left : (λ x, ‖f' x‖) =O[l] g ↔ f' =O[l] g := by { unfold is_O, exact exists_congr (λ _, is_O_with_norm_left) } @[simp] theorem is_O_abs_left : (λ x, |u x|) =O[l] g ↔ u =O[l] g := @is_O_norm_left _ _ _ _ _ g u l alias is_O_norm_left ↔ is_O.of_norm_left is_O.norm_left alias is_O_abs_left ↔ is_O.of_abs_left is_O.abs_left @[simp] theorem is_o_norm_left : (λ x, ‖f' x‖) =o[l] g ↔ f' =o[l] g := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_norm_left) } @[simp] theorem is_o_abs_left : (λ x, |u x|) =o[l] g ↔ u =o[l] g := @is_o_norm_left _ _ _ _ _ g u l alias is_o_norm_left ↔ is_o.of_norm_left is_o.norm_left alias is_o_abs_left ↔ is_o.of_abs_left is_o.abs_left theorem is_O_with_norm_norm : is_O_with c l (λ x, ‖f' x‖) (λ x, ‖g' x‖) ↔ is_O_with c l f' g' := is_O_with_norm_left.trans is_O_with_norm_right theorem is_O_with_abs_abs : is_O_with c l (λ x, |u x|) (λ x, |v x|) ↔ is_O_with c l u v := is_O_with_abs_left.trans is_O_with_abs_right alias is_O_with_norm_norm ↔ is_O_with.of_norm_norm is_O_with.norm_norm alias is_O_with_abs_abs ↔ is_O_with.of_abs_abs is_O_with.abs_abs theorem is_O_norm_norm : (λ x, ‖f' x‖) =O[l] (λ x, ‖g' x‖) ↔ f' =O[l] g' := is_O_norm_left.trans is_O_norm_right theorem is_O_abs_abs : (λ x, |u x|) =O[l] (λ x, |v x|) ↔ u =O[l] v := is_O_abs_left.trans is_O_abs_right alias is_O_norm_norm ↔ is_O.of_norm_norm is_O.norm_norm alias is_O_abs_abs ↔ is_O.of_abs_abs is_O.abs_abs theorem is_o_norm_norm : (λ x, ‖f' x‖) =o[l] (λ x, ‖g' x‖) ↔ f' =o[l] g' := is_o_norm_left.trans is_o_norm_right theorem is_o_abs_abs : (λ x, |u x|) =o[l] (λ x, |v x|) ↔ u =o[l] v := is_o_abs_left.trans is_o_abs_right alias is_o_norm_norm ↔ is_o.of_norm_norm is_o.norm_norm alias is_o_abs_abs ↔ is_o.of_abs_abs is_o.abs_abs end norm_abs /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right : is_O_with c l f (λ x, -(g' x)) ↔ is_O_with c l f g' := by simp only [is_O_with, norm_neg] alias is_O_with_neg_right ↔ is_O_with.of_neg_right is_O_with.neg_right @[simp] theorem is_O_neg_right : f =O[l] (λ x, -(g' x)) ↔ f =O[l] g' := by { unfold is_O, exact exists_congr (λ _, is_O_with_neg_right) } alias is_O_neg_right ↔ is_O.of_neg_right is_O.neg_right @[simp] theorem is_o_neg_right : f =o[l] (λ x, -(g' x)) ↔ f =o[l] g' := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_neg_right) } alias is_o_neg_right ↔ is_o.of_neg_right is_o.neg_right @[simp] theorem is_O_with_neg_left : is_O_with c l (λ x, -(f' x)) g ↔ is_O_with c l f' g := by simp only [is_O_with, norm_neg] alias is_O_with_neg_left ↔ is_O_with.of_neg_left is_O_with.neg_left @[simp] theorem is_O_neg_left : (λ x, -(f' x)) =O[l] g ↔ f' =O[l] g := by { unfold is_O, exact exists_congr (λ _, is_O_with_neg_left) } alias is_O_neg_left ↔ is_O.of_neg_left is_O.neg_left @[simp] theorem is_o_neg_left : (λ x, -(f' x)) =o[l] g ↔ f' =o[l] g := by { unfold is_o, exact forall₂_congr (λ _ _, is_O_with_neg_left) } alias is_o_neg_left ↔ is_o.of_neg_right is_o.neg_left /-! ### Product of functions (right) -/ lemma is_O_with_fst_prod : is_O_with 1 l f' (λ x, (f' x, g' x)) := is_O_with_of_le l $ λ x, le_max_left _ _ lemma is_O_with_snd_prod : is_O_with 1 l g' (λ x, (f' x, g' x)) := is_O_with_of_le l $ λ x, le_max_right _ _ lemma is_O_fst_prod : f' =O[l] (λ x, (f' x, g' x)) := is_O_with_fst_prod.is_O lemma is_O_snd_prod : g' =O[l] (λ x, (f' x, g' x)) := is_O_with_snd_prod.is_O lemma is_O_fst_prod' {f' : α → E' × F'} : (λ x, (f' x).1) =O[l] f' := by simpa [is_O, is_O_with] using is_O_fst_prod lemma is_O_snd_prod' {f' : α → E' × F'} : (λ x, (f' x).2) =O[l] f' := by simpa [is_O, is_O_with] using is_O_snd_prod section variables (f' k') lemma is_O_with.prod_rightl (h : is_O_with c l f g') (hc : 0 ≤ c) : is_O_with c l f (λ x, (g' x, k' x)) := (h.trans is_O_with_fst_prod hc).congr_const (mul_one c) lemma is_O.prod_rightl (h : f =O[l] g') : f =O[l] (λ x, (g' x, k' x)) := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightl k' cnonneg).is_O lemma is_o.prod_rightl (h : f =o[l] g') : f =o[l] (λ x, (g' x, k' x)) := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).prod_rightl k' cpos.le lemma is_O_with.prod_rightr (h : is_O_with c l f g') (hc : 0 ≤ c) : is_O_with c l f (λ x, (f' x, g' x)) := (h.trans is_O_with_snd_prod hc).congr_const (mul_one c) lemma is_O.prod_rightr (h : f =O[l] g') : f =O[l] (λ x, (f' x, g' x)) := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightr f' cnonneg).is_O lemma is_o.prod_rightr (h : f =o[l] g') : f =o[l] (λx, (f' x, g' x)) := is_o.of_is_O_with $ λ c cpos, (h.forall_is_O_with cpos).prod_rightr f' cpos.le end lemma is_O_with.prod_left_same (hf : is_O_with c l f' k') (hg : is_O_with c l g' k') : is_O_with c l (λ x, (f' x, g' x)) k' := by rw is_O_with_iff at *; filter_upwards [hf, hg] with x using max_le lemma is_O_with.prod_left (hf : is_O_with c l f' k') (hg : is_O_with c' l g' k') : is_O_with (max c c') l (λ x, (f' x, g' x)) k' := (hf.weaken $ le_max_left c c').prod_left_same (hg.weaken $ le_max_right c c') lemma is_O_with.prod_left_fst (h : is_O_with c l (λ x, (f' x, g' x)) k') : is_O_with c l f' k' := (is_O_with_fst_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with.prod_left_snd (h : is_O_with c l (λ x, (f' x, g' x)) k') : is_O_with c l g' k' := (is_O_with_snd_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with_prod_left : is_O_with c l (λ x, (f' x, g' x)) k' ↔ is_O_with c l f' k' ∧ is_O_with c l g' k' := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left_same h.2⟩ lemma is_O.prod_left (hf : f' =O[l] k') (hg : g' =O[l] k') : (λ x, (f' x, g' x)) =O[l] k' := let ⟨c, hf⟩ := hf.is_O_with, ⟨c', hg⟩ := hg.is_O_with in (hf.prod_left hg).is_O lemma is_O.prod_left_fst : (λ x, (f' x, g' x)) =O[l] k' → f' =O[l] k' := is_O.trans is_O_fst_prod lemma is_O.prod_left_snd : (λ x, (f' x, g' x)) =O[l] k' → g' =O[l] k' := is_O.trans is_O_snd_prod @[simp] lemma is_O_prod_left : (λ x, (f' x, g' x)) =O[l] k' ↔ f' =O[l] k' ∧ g' =O[l] k' := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_o.prod_left (hf : f' =o[l] k') (hg : g' =o[l] k') : (λ x, (f' x, g' x)) =o[l] k' := is_o.of_is_O_with $ λ c hc, (hf.forall_is_O_with hc).prod_left_same (hg.forall_is_O_with hc) lemma is_o.prod_left_fst : (λ x, (f' x, g' x)) =o[l] k' → f' =o[l] k' := is_O.trans_is_o is_O_fst_prod lemma is_o.prod_left_snd : (λ x, (f' x, g' x)) =o[l] k' → g' =o[l] k' := is_O.trans_is_o is_O_snd_prod @[simp] lemma is_o_prod_left : (λ x, (f' x, g' x)) =o[l] k' ↔ f' =o[l] k' ∧ g' =o[l] k' := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_O_with.eq_zero_imp (h : is_O_with c l f'' g'') : ∀ᶠ x in l, g'' x = 0 → f'' x = 0 := eventually.mono h.bound $ λ x hx hg, norm_le_zero_iff.1 $ by simpa [hg] using hx lemma is_O.eq_zero_imp (h : f'' =O[l] g'') : ∀ᶠ x in l, g'' x = 0 → f'' x = 0 := let ⟨C, hC⟩ := h.is_O_with in hC.eq_zero_imp /-! ### Addition and subtraction -/ section add_sub variables {f₁ f₂ : α → E'} {g₁ g₂ : α → F'} theorem is_O_with.add (h₁ : is_O_with c₁ l f₁ g) (h₂ : is_O_with c₂ l f₂ g) : is_O_with (c₁ + c₂) l (λ x, f₁ x + f₂ x) g := by rw is_O_with at *; filter_upwards [h₁, h₂] with x hx₁ hx₂ using calc ‖f₁ x + f₂ x‖ ≤ c₁ * ‖g x‖ + c₂ * ‖g x‖ : norm_add_le_of_le hx₁ hx₂ ... = (c₁ + c₂) * ‖g x‖ : (add_mul _ _ _).symm theorem is_O.add (h₁ : f₁ =O[l] g) (h₂ : f₂ =O[l] g) : (λ x, f₁ x + f₂ x) =O[l] g := let ⟨c₁, hc₁⟩ := h₁.is_O_with, ⟨c₂, hc₂⟩ := h₂.is_O_with in (hc₁.add hc₂).is_O theorem is_o.add (h₁ : f₁ =o[l] g) (h₂ : f₂ =o[l] g) : (λ x, f₁ x + f₂ x) =o[l] g := is_o.of_is_O_with $ λ c cpos, ((h₁.forall_is_O_with $ half_pos cpos).add (h₂.forall_is_O_with $ half_pos cpos)).congr_const (add_halves c) theorem is_o.add_add (h₁ : f₁ =o[l] g₁) (h₂ : f₂ =o[l] g₂) : (λ x, f₁ x + f₂ x) =o[l] (λ x, ‖g₁ x‖ + ‖g₂ x‖) := by refine (h₁.trans_le $ λ x, _).add (h₂.trans_le _); simp [abs_of_nonneg, add_nonneg] theorem is_O.add_is_o (h₁ : f₁ =O[l] g) (h₂ : f₂ =o[l] g) : (λ x, f₁ x + f₂ x) =O[l] g := h₁.add h₂.is_O theorem is_o.add_is_O (h₁ : f₁ =o[l] g) (h₂ : f₂ =O[l] g) : (λ x, f₁ x + f₂ x) =O[l] g := h₁.is_O.add h₂ theorem is_O_with.add_is_o (h₁ : is_O_with c₁ l f₁ g) (h₂ : f₂ =o[l] g) (hc : c₁ < c₂) : is_O_with c₂ l (λx, f₁ x + f₂ x) g := (h₁.add (h₂.forall_is_O_with (sub_pos.2 hc))).congr_const (add_sub_cancel'_right _ _) theorem is_o.add_is_O_with (h₁ : f₁ =o[l] g) (h₂ : is_O_with c₁ l f₂ g) (hc : c₁ < c₂) : is_O_with c₂ l (λx, f₁ x + f₂ x) g := (h₂.add_is_o h₁ hc).congr_left $ λ _, add_comm _ _ theorem is_O_with.sub (h₁ : is_O_with c₁ l f₁ g) (h₂ : is_O_with c₂ l f₂ g) : is_O_with (c₁ + c₂) l (λ x, f₁ x - f₂ x) g := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left theorem is_O_with.sub_is_o (h₁ : is_O_with c₁ l f₁ g) (h₂ : f₂ =o[l] g) (hc : c₁ < c₂) : is_O_with c₂ l (λ x, f₁ x - f₂ x) g := by simpa only [sub_eq_add_neg] using h₁.add_is_o h₂.neg_left hc theorem is_O.sub (h₁ : f₁ =O[l] g) (h₂ : f₂ =O[l] g) : (λ x, f₁ x - f₂ x) =O[l] g := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left theorem is_o.sub (h₁ : f₁ =o[l] g) (h₂ : f₂ =o[l] g) : (λ x, f₁ x - f₂ x) =o[l] g := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left end add_sub /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ section is_oO_as_rel variables {f₁ f₂ f₃ : α → E'} theorem is_O_with.symm (h : is_O_with c l (λ x, f₁ x - f₂ x) g) : is_O_with c l (λ x, f₂ x - f₁ x) g := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_with_comm : is_O_with c l (λ x, f₁ x - f₂ x) g ↔ is_O_with c l (λ x, f₂ x - f₁ x) g := ⟨is_O_with.symm, is_O_with.symm⟩ theorem is_O.symm (h : (λ x, f₁ x - f₂ x) =O[l] g) : (λ x, f₂ x - f₁ x) =O[l] g := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_comm : (λ x, f₁ x - f₂ x) =O[l] g ↔ (λ x, f₂ x - f₁ x) =O[l] g := ⟨is_O.symm, is_O.symm⟩ theorem is_o.symm (h : (λ x, f₁ x - f₂ x) =o[l] g) : (λ x, f₂ x - f₁ x) =o[l] g := by simpa only [neg_sub] using h.neg_left theorem is_o_comm : (λ x, f₁ x - f₂ x) =o[l] g ↔ (λ x, f₂ x - f₁ x) =o[l] g := ⟨is_o.symm, is_o.symm⟩ theorem is_O_with.triangle (h₁ : is_O_with c l (λ x, f₁ x - f₂ x) g) (h₂ : is_O_with c' l (λ x, f₂ x - f₃ x) g) : is_O_with (c + c') l (λ x, f₁ x - f₃ x) g := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.triangle (h₁ : (λ x, f₁ x - f₂ x) =O[l] g) (h₂ : (λ x, f₂ x - f₃ x) =O[l] g) : (λ x, f₁ x - f₃ x) =O[l] g := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_o.triangle (h₁ : (λ x, f₁ x - f₂ x) =o[l] g) (h₂ : (λ x, f₂ x - f₃ x) =o[l] g) : (λ x, f₁ x - f₃ x) =o[l] g := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.congr_of_sub (h : (λ x, f₁ x - f₂ x) =O[l] g) : f₁ =O[l] g ↔ f₂ =O[l] g := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o.congr_of_sub (h : (λ x, f₁ x - f₂ x) =o[l] g) : f₁ =o[l] g ↔ f₂ =o[l] g := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ end is_oO_as_rel /-! ### Zero, one, and other constants -/ section zero_const variables (g g' l) theorem is_o_zero : (λ x, (0 : E')) =o[l] g' := is_o.of_bound $ λ c hc, univ_mem' $ λ x, by simpa using mul_nonneg hc.le (norm_nonneg $ g' x) theorem is_O_with_zero (hc : 0 ≤ c) : is_O_with c l (λ x, (0 : E')) g' := is_O_with.of_bound $ univ_mem' $ λ x, by simpa using mul_nonneg hc (norm_nonneg $ g' x) theorem is_O_with_zero' : is_O_with 0 l (λ x, (0 : E')) g := is_O_with.of_bound $ univ_mem' $ λ x, by simp theorem is_O_zero : (λ x, (0 : E')) =O[l] g := is_O_iff_is_O_with.2 ⟨0, is_O_with_zero' _ _⟩ theorem is_O_refl_left : (λ x, f' x - f' x) =O[l] g' := (is_O_zero g' l).congr_left $ λ x, (sub_self _).symm theorem is_o_refl_left : (λ x, f' x - f' x) =o[l] g' := (is_o_zero g' l).congr_left $ λ x, (sub_self _).symm variables {g g' l} @[simp] theorem is_O_with_zero_right_iff : is_O_with c l f'' (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := by simp only [is_O_with, exists_prop, true_and, norm_zero, mul_zero, norm_le_zero_iff, eventually_eq, pi.zero_apply] @[simp] theorem is_O_zero_right_iff : f'' =O[l] (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := ⟨λ h, let ⟨c, hc⟩ := h.is_O_with in is_O_with_zero_right_iff.1 hc, λ h, (is_O_with_zero_right_iff.2 h : is_O_with 1 _ _ _).is_O⟩ @[simp] theorem is_o_zero_right_iff : f'' =o[l] (λ x, (0 : F')) ↔ f'' =ᶠ[l] 0 := ⟨λ h, is_O_zero_right_iff.1 h.is_O, λ h, is_o.of_is_O_with $ λ c hc, is_O_with_zero_right_iff.2 h⟩ theorem is_O_with_const_const (c : E) {c' : F''} (hc' : c' ≠ 0) (l : filter α) : is_O_with (‖c‖ / ‖c'‖) l (λ x : α, c) (λ x, c') := begin unfold is_O_with, apply univ_mem', intro x, rw [mem_set_of_eq, div_mul_cancel], rwa [ne.def, norm_eq_zero] end theorem is_O_const_const (c : E) {c' : F''} (hc' : c' ≠ 0) (l : filter α) : (λ x : α, c) =O[l] (λ x, c') := (is_O_with_const_const c hc' l).is_O @[simp] theorem is_O_const_const_iff {c : E''} {c' : F''} (l : filter α) [l.ne_bot] : (λ x : α, c) =O[l] (λ x, c') ↔ (c' = 0 → c = 0) := begin rcases eq_or_ne c' 0 with rfl|hc', { simp [eventually_eq] }, { simp [hc', is_O_const_const _ hc'] } end @[simp] lemma is_O_pure {x} : f'' =O[pure x] g'' ↔ (g'' x = 0 → f'' x = 0) := calc f'' =O[pure x] g'' ↔ (λ y : α, f'' x) =O[pure x] (λ _, g'' x) : is_O_congr rfl rfl ... ↔ g'' x = 0 → f'' x = 0 : is_O_const_const_iff _ end zero_const @[simp] lemma is_O_with_top : is_O_with c ⊤ f g ↔ ∀ x, ‖f x‖ ≤ c * ‖g x‖ := by rw is_O_with; refl @[simp] lemma is_O_top : f =O[⊤] g ↔ ∃ C, ∀ x, ‖f x‖ ≤ C * ‖g x‖ := by rw is_O_iff; refl @[simp] lemma is_o_top : f'' =o[⊤] g'' ↔ ∀ x, f'' x = 0 := begin refine ⟨_, λ h, (is_o_zero g'' ⊤).congr (λ x, (h x).symm) (λ x, rfl)⟩, simp only [is_o_iff, eventually_top], refine λ h x, norm_le_zero_iff.1 _, have : tendsto (λ c : ℝ, c * ‖g'' x‖) (𝓝[>] 0) (𝓝 0) := ((continuous_id.mul continuous_const).tendsto' _ _ (zero_mul _)).mono_left inf_le_left, exact le_of_tendsto_of_tendsto tendsto_const_nhds this (eventually_nhds_within_iff.2 $ eventually_of_forall $ λ c hc, h hc x) end @[simp] lemma is_O_with_principal {s : set α} : is_O_with c (𝓟 s) f g ↔ ∀ x ∈ s, ‖f x‖ ≤ c * ‖g x‖ := by rw is_O_with; refl lemma is_O_principal {s : set α} : f =O[𝓟 s] g ↔ ∃ c, ∀ x ∈ s, ‖f x‖ ≤ c * ‖g x‖ := by rw is_O_iff; refl section variables (F) [has_one F] [norm_one_class F] theorem is_O_with_const_one (c : E) (l : filter α) : is_O_with ‖c‖ l (λ x : α, c) (λ x, (1 : F)) := by simp [is_O_with_iff] theorem is_O_const_one (c : E) (l : filter α) : (λ x : α, c) =O[l] (λ x, (1 : F)) := (is_O_with_const_one F c l).is_O theorem is_o_const_iff_is_o_one {c : F''} (hc : c ≠ 0) : f =o[l] (λ x, c) ↔ f =o[l] (λ x, (1 : F)) := ⟨λ h, h.trans_is_O_with (is_O_with_const_one _ _ _) (norm_pos_iff.2 hc), λ h, h.trans_is_O $ is_O_const_const _ hc _⟩ @[simp] theorem is_o_one_iff : f' =o[l] (λ x, 1 : α → F) ↔ tendsto f' l (𝓝 0) := by simp only [is_o_iff, norm_one, mul_one, metric.nhds_basis_closed_ball.tendsto_right_iff, metric.mem_closed_ball, dist_zero_right] @[simp] theorem is_O_one_iff : f =O[l] (λ x, 1 : α → F) ↔ is_bounded_under (≤) l (λ x, ‖f x‖) := by { simp only [is_O_iff, norm_one, mul_one], refl } alias is_O_one_iff ↔ _ _root_.filter.is_bounded_under.is_O_one @[simp] theorem is_o_one_left_iff : (λ x, 1 : α → F) =o[l] f ↔ tendsto (λ x, ‖f x‖) l at_top := calc (λ x, 1 : α → F) =o[l] f ↔ ∀ n : ℕ, ∀ᶠ x in l, ↑n * ‖(1 : F)‖ ≤ ‖f x‖ : is_o_iff_nat_mul_le_aux $ or.inl $ λ x, by simp only [norm_one, zero_le_one] ... ↔ ∀ n : ℕ, true → ∀ᶠ x in l, ‖f x‖ ∈ Ici (n : ℝ) : by simp only [norm_one, mul_one, true_implies_iff, mem_Ici] ... ↔ tendsto (λ x, ‖f x‖) l at_top : at_top_countable_basis_of_archimedean.1.tendsto_right_iff.symm theorem _root_.filter.tendsto.is_O_one {c : E'} (h : tendsto f' l (𝓝 c)) : f' =O[l] (λ x, 1 : α → F) := h.norm.is_bounded_under_le.is_O_one F theorem is_O.trans_tendsto_nhds (hfg : f =O[l] g') {y : F'} (hg : tendsto g' l (𝓝 y)) : f =O[l] (λ x, 1 : α → F) := hfg.trans $ hg.is_O_one F end theorem is_o_const_iff {c : F''} (hc : c ≠ 0) : f'' =o[l] (λ x, c) ↔ tendsto f'' l (𝓝 0) := (is_o_const_iff_is_o_one ℝ hc).trans (is_o_one_iff _) lemma is_o_id_const {c : F''} (hc : c ≠ 0) : (λ (x : E''), x) =o[𝓝 0] (λ x, c) := (is_o_const_iff hc).mpr (continuous_id.tendsto 0) theorem _root_.filter.is_bounded_under.is_O_const (h : is_bounded_under (≤) l (norm ∘ f)) {c : F''} (hc : c ≠ 0) : f =O[l] (λ x, c) := (h.is_O_one ℝ).trans (is_O_const_const _ hc _) theorem is_O_const_of_tendsto {y : E''} (h : tendsto f'' l (𝓝 y)) {c : F''} (hc : c ≠ 0) : f'' =O[l] (λ x, c) := h.norm.is_bounded_under_le.is_O_const hc lemma is_O.is_bounded_under_le {c : F} (h : f =O[l] (λ x, c)) : is_bounded_under (≤) l (norm ∘ f) := let ⟨c', hc'⟩ := h.bound in ⟨c' * ‖c‖, eventually_map.2 hc'⟩ theorem is_O_const_of_ne {c : F''} (hc : c ≠ 0) : f =O[l] (λ x, c) ↔ is_bounded_under (≤) l (norm ∘ f) := ⟨λ h, h.is_bounded_under_le, λ h, h.is_O_const hc⟩ theorem is_O_const_iff {c : F''} : f'' =O[l] (λ x, c) ↔ (c = 0 → f'' =ᶠ[l] 0) ∧ is_bounded_under (≤) l (λ x, ‖f'' x‖) := begin refine ⟨λ h, ⟨λ hc, is_O_zero_right_iff.1 (by rwa ← hc), h.is_bounded_under_le⟩, _⟩, rintro ⟨hcf, hf⟩, rcases eq_or_ne c 0 with hc|hc, exacts [(hcf hc).trans_is_O (is_O_zero _ _), hf.is_O_const hc] end theorem is_O_iff_is_bounded_under_le_div (h : ∀ᶠ x in l, g'' x ≠ 0) : f =O[l] g'' ↔ is_bounded_under (≤) l (λ x, ‖f x‖ / ‖g'' x‖) := begin simp only [is_O_iff, is_bounded_under, is_bounded, eventually_map], exact exists_congr (λ c, eventually_congr $ h.mono $ λ x hx, (div_le_iff $ norm_pos_iff.2 hx).symm) end /-- `(λ x, c) =O[l] f` if and only if `f` is bounded away from zero. -/ lemma is_O_const_left_iff_pos_le_norm {c : E''} (hc : c ≠ 0) : (λ x, c) =O[l] f' ↔ ∃ b, 0 < b ∧ ∀ᶠ x in l, b ≤ ‖f' x‖ := begin split, { intro h, rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨‖c‖ / C, div_pos (norm_pos_iff.2 hc) hC₀, _⟩, exact hC.bound.mono (λ x, (div_le_iff' hC₀).2) }, { rintro ⟨b, hb₀, hb⟩, refine is_O.of_bound (‖c‖ / b) (hb.mono $ λ x hx, _), rw [div_mul_eq_mul_div, mul_div_assoc], exact le_mul_of_one_le_right (norm_nonneg _) ((one_le_div hb₀).2 hx) } end section variable (𝕜) end theorem is_O.trans_tendsto (hfg : f'' =O[l] g'') (hg : tendsto g'' l (𝓝 0)) : tendsto f'' l (𝓝 0) := (is_o_one_iff ℝ).1 $ hfg.trans_is_o $ (is_o_one_iff ℝ).2 hg theorem is_o.trans_tendsto (hfg : f'' =o[l] g'') (hg : tendsto g'' l (𝓝 0)) : tendsto f'' l (𝓝 0) := hfg.is_O.trans_tendsto hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O_with ‖c‖ l (λ x, c * f x) f := is_O_with_of_le' _ $ λ x, norm_mul_le _ _ theorem is_O_const_mul_self (c : R) (f : α → R) (l : filter α) : (λ x, c * f x) =O[l] f := (is_O_with_const_mul_self c f l).is_O theorem is_O_with.const_mul_left {f : α → R} (h : is_O_with c l f g) (c' : R) : is_O_with (‖c'‖ * c) l (λ x, c' * f x) g := (is_O_with_const_mul_self c' f l).trans h (norm_nonneg c') theorem is_O.const_mul_left {f : α → R} (h : f =O[l] g) (c' : R) : (λ x, c' * f x) =O[l] g := let ⟨c, hc⟩ := h.is_O_with in (hc.const_mul_left c').is_O theorem is_O_with_self_const_mul' (u : Rˣ) (f : α → R) (l : filter α) : is_O_with ‖(↑u⁻¹:R)‖ l f (λ x, ↑u * f x) := (is_O_with_const_mul_self ↑u⁻¹ _ l).congr_left $ λ x, u.inv_mul_cancel_left (f x) theorem is_O_with_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with ‖c‖⁻¹ l f (λ x, c * f x) := (is_O_with_self_const_mul' (units.mk0 c hc) f l).congr_const $ norm_inv c theorem is_O_self_const_mul' {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : f =O[l] (λ x, c * f x) := let ⟨u, hu⟩ := hc in hu ▸ (is_O_with_self_const_mul' u f l).is_O theorem is_O_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : f =O[l] (λ x, c * f x) := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : (λ x, c * f x) =O[l] g ↔ f =O[l] g := ⟨(is_O_self_const_mul' hc f l).trans, λ h, h.const_mul_left c⟩ theorem is_O_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : (λ x, c * f x) =O[l] g ↔ f =O[l] g := is_O_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_o.const_mul_left {f : α → R} (h : f =o[l] g) (c : R) : (λ x, c * f x) =o[l] g := (is_O_const_mul_self c f l).trans_is_o h theorem is_o_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : (λ x, c * f x) =o[l] g ↔ f =o[l] g := ⟨(is_O_self_const_mul' hc f l).trans_is_o, λ h, h.const_mul_left c⟩ theorem is_o_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : (λ x, c * f x) =o[l] g ↔ f =o[l] g := is_o_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_O_with.of_const_mul_right {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' l f (λ x, c * g x)) : is_O_with (c' * ‖c‖) l f g := h.trans (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {g : α → R} {c : R} (h : f =O[l] (λ x, c * g x)) : f =O[l] g := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.of_const_mul_right cnonneg).is_O theorem is_O_with.const_mul_right' {g : α → R} {u : Rˣ} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' l f g) : is_O_with (c' * ‖(↑u⁻¹:R)‖) l f (λ x, ↑u * g x) := h.trans (is_O_with_self_const_mul' _ _ _) hc' theorem is_O_with.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' l f g) : is_O_with (c' * ‖c‖⁻¹) l f (λ x, c * g x) := h.trans (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : f =O[l] g) : f =O[l] (λ x, c * g x) := h.trans (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : f =O[l] g) : f =O[l] (λ x, c * g x) := h.const_mul_right' $ is_unit.mk0 c hc theorem is_O_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : f =O[l] (λ x, c * g x) ↔ f =O[l] g := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_O_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : f =O[l] (λ x, c * g x) ↔ f =O[l] g := is_O_const_mul_right_iff' $ is_unit.mk0 c hc theorem is_o.of_const_mul_right {g : α → R} {c : R} (h : f =o[l] (λ x, c * g x)) : f =o[l] g := h.trans_is_O (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : f =o[l] g) : f =o[l] (λ x, c * g x) := h.trans_is_O (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : f =o[l] g) : f =o[l] (λ x, c * g x) := h.const_mul_right' $ is_unit.mk0 c hc theorem is_o_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : f =o[l] (λ x, c * g x) ↔ f =o[l] g := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_o_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : f =o[l] (λ x, c * g x) ↔ f =o[l] g := is_o_const_mul_right_iff' $ is_unit.mk0 c hc /-! ### Multiplication -/ theorem is_O_with.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} {c₁ c₂ : ℝ} (h₁ : is_O_with c₁ l f₁ g₁) (h₂ : is_O_with c₂ l f₂ g₂) : is_O_with (c₁ * c₂) l (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) := begin unfold is_O_with at *, filter_upwards [h₁, h₂] with _ hx₁ hx₂, apply le_trans (norm_mul_le _ _), convert mul_le_mul hx₁ hx₂ (norm_nonneg _) (le_trans (norm_nonneg _) hx₁) using 1, rw [norm_mul, mul_mul_mul_comm] end theorem is_O.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =O[l] g₁) (h₂ : f₂ =O[l] g₂) : (λ x, f₁ x * f₂ x) =O[l] (λ x, g₁ x * g₂ x) := let ⟨c, hc⟩ := h₁.is_O_with, ⟨c', hc'⟩ := h₂.is_O_with in (hc.mul hc').is_O theorem is_O.mul_is_o {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =O[l] g₁) (h₂ : f₂ =o[l] g₂) : (λ x, f₁ x * f₂ x) =o[l] (λ x, g₁ x * g₂ x) := begin unfold is_o at *, intros c cpos, rcases h₁.exists_pos with ⟨c', c'pos, hc'⟩, exact (hc'.mul (h₂ (div_pos cpos c'pos))).congr_const (mul_div_cancel' _ (ne_of_gt c'pos)) end theorem is_o.mul_is_O {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =o[l] g₁) (h₂ : f₂ =O[l] g₂) : (λ x, f₁ x * f₂ x) =o[l] (λ x, g₁ x * g₂ x) := begin unfold is_o at *, intros c cpos, rcases h₂.exists_pos with ⟨c', c'pos, hc'⟩, exact ((h₁ (div_pos cpos c'pos)).mul hc').congr_const (div_mul_cancel _ (ne_of_gt c'pos)) end theorem is_o.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : f₁ =o[l] g₁) (h₂ : f₂ =o[l] g₂) : (λ x, f₁ x * f₂ x) =o[l] (λ x, g₁ x * g₂ x) := h₁.mul_is_O h₂.is_O theorem is_O_with.pow' {f : α → R} {g : α → 𝕜} (h : is_O_with c l f g) : ∀ n : ℕ, is_O_with (nat.cases_on n ‖(1 : R)‖ (λ n, c ^ (n + 1))) l (λ x, f x ^ n) (λ x, g x ^ n) | 0 := by simpa using is_O_with_const_const (1 : R) (one_ne_zero' 𝕜) l | 1 := by simpa | (n + 2) := by simpa [pow_succ] using h.mul (is_O_with.pow' (n + 1)) theorem is_O_with.pow [norm_one_class R] {f : α → R} {g : α → 𝕜} (h : is_O_with c l f g) : ∀ n : ℕ, is_O_with (c ^ n) l (λ x, f x ^ n) (λ x, g x ^ n) | 0 := by simpa using h.pow' 0 | (n + 1) := h.pow' (n + 1) theorem is_O_with.of_pow {n : ℕ} {f : α → 𝕜} {g : α → R} (h : is_O_with c l (f ^ n) (g ^ n)) (hn : n ≠ 0) (hc : c ≤ c' ^ n) (hc' : 0 ≤ c') : is_O_with c' l f g := is_O_with.of_bound $ (h.weaken hc).bound.mono $ λ x hx, le_of_pow_le_pow n (mul_nonneg hc' $ norm_nonneg _) hn.bot_lt $ calc ‖f x‖ ^ n = ‖(f x) ^ n‖ : (norm_pow _ _).symm ... ≤ c' ^ n * ‖(g x) ^ n‖ : hx ... ≤ c' ^ n * ‖g x‖ ^ n : mul_le_mul_of_nonneg_left (norm_pow_le' _ hn.bot_lt) (pow_nonneg hc' _) ... = (c' * ‖g x‖) ^ n : (mul_pow _ _ _).symm theorem is_O.pow {f : α → R} {g : α → 𝕜} (h : f =O[l] g) (n : ℕ) : (λ x, f x ^ n) =O[l] (λ x, g x ^ n) := let ⟨C, hC⟩ := h.is_O_with in is_O_iff_is_O_with.2 ⟨_, hC.pow' n⟩ theorem is_O.of_pow {f : α → 𝕜} {g : α → R} {n : ℕ} (hn : n ≠ 0) (h : (f ^ n) =O[l] (g ^ n)) : f =O[l] g := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, obtain ⟨c, hc₀, hc⟩ : ∃ c : ℝ, 0 ≤ c ∧ C ≤ c ^ n, from ((eventually_ge_at_top _).and $ (tendsto_pow_at_top hn).eventually_ge_at_top C).exists, exact (hC.of_pow hn hc hc₀).is_O end theorem is_o.pow {f : α → R} {g : α → 𝕜} (h : f =o[l] g) {n : ℕ} (hn : 0 < n) : (λ x, f x ^ n) =o[l] (λ x, g x ^ n) := begin cases n, exact hn.false.elim, clear hn, induction n with n ihn, { simpa only [pow_one] }, convert h.mul ihn; simp [pow_succ] end theorem is_o.of_pow {f : α → 𝕜} {g : α → R} {n : ℕ} (h : (f ^ n) =o[l] (g ^ n)) (hn : n ≠ 0) : f =o[l] g := is_o.of_is_O_with $ λ c hc, (h.def' $ pow_pos hc _).of_pow hn le_rfl hc.le /-! ### Inverse -/ theorem is_O_with.inv_rev {f : α → 𝕜} {g : α → 𝕜'} (h : is_O_with c l f g) (h₀ : ∀ᶠ x in l, f x = 0 → g x = 0) : is_O_with c l (λ x, (g x)⁻¹) (λ x, (f x)⁻¹) := begin refine is_O_with.of_bound (h.bound.mp (h₀.mono $ λ x h₀ hle, _)), cases eq_or_ne (f x) 0 with hx hx, { simp only [hx, h₀ hx, inv_zero, norm_zero, mul_zero] }, { have hc : 0 < c, from pos_of_mul_pos_left ((norm_pos_iff.2 hx).trans_le hle) (norm_nonneg _), replace hle := inv_le_inv_of_le (norm_pos_iff.2 hx) hle, simpa only [norm_inv, mul_inv, ← div_eq_inv_mul, div_le_iff hc] using hle } end theorem is_O.inv_rev {f : α → 𝕜} {g : α → 𝕜'} (h : f =O[l] g) (h₀ : ∀ᶠ x in l, f x = 0 → g x = 0) : (λ x, (g x)⁻¹) =O[l] (λ x, (f x)⁻¹) := let ⟨c, hc⟩ := h.is_O_with in (hc.inv_rev h₀).is_O theorem is_o.inv_rev {f : α → 𝕜} {g : α → 𝕜'} (h : f =o[l] g) (h₀ : ∀ᶠ x in l, f x = 0 → g x = 0) : (λ x, (g x)⁻¹) =o[l] (λ x, (f x)⁻¹) := is_o.of_is_O_with $ λ c hc, (h.def' hc).inv_rev h₀ /-! ### Scalar multiplication -/ section smul_const variables [normed_space 𝕜 E'] theorem is_O_with.const_smul_left (h : is_O_with c l f' g) (c' : 𝕜) : is_O_with (‖c'‖ * c) l (λ x, c' • f' x) g := is_O_with.of_norm_left $ by simpa only [← norm_smul, norm_norm] using h.norm_left.const_mul_left (‖c'‖) lemma is_O.const_smul_left (h : f' =O[l] g) (c : 𝕜) : (c • f') =O[l] g := let ⟨b, hb⟩ := h.is_O_with in (hb.const_smul_left _).is_O lemma is_o.const_smul_left (h : f' =o[l] g) (c : 𝕜) : (c • f') =o[l] g := is_o.of_norm_left $ by simpa only [← norm_smul] using h.norm_left.const_mul_left (‖c‖) theorem is_O_const_smul_left {c : 𝕜} (hc : c ≠ 0) : (λ x, c • f' x) =O[l] g ↔ f' =O[l] g := begin have cne0 : ‖c‖ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left], end theorem is_o_const_smul_left {c : 𝕜} (hc : c ≠ 0) : (λ x, c • f' x) =o[l] g ↔ f' =o[l] g := begin have cne0 : ‖c‖ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end theorem is_O_const_smul_right {c : 𝕜} (hc : c ≠ 0) : f =O[l] (λ x, c • f' x) ↔ f =O[l] f' := begin have cne0 : ‖c‖ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {c : 𝕜} (hc : c ≠ 0) : f =o[l] (λ x, c • f' x) ↔ f =o[l] f' := begin have cne0 : ‖c‖ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right_iff cne0, is_o_norm_right] end end smul_const section smul variables [normed_space 𝕜 E'] [normed_space 𝕜' F'] {k₁ : α → 𝕜} {k₂ : α → 𝕜'} theorem is_O_with.smul (h₁ : is_O_with c l k₁ k₂) (h₂ : is_O_with c' l f' g') : is_O_with (c * c') l (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr rfl _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul (h₁ : k₁ =O[l] k₂) (h₂ : f' =O[l] g') : (λ x, k₁ x • f' x) =O[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul_is_o (h₁ : k₁ =O[l] k₂) (h₂ : f' =o[l] g') : (λ x, k₁ x • f' x) =o[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul_is_o h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul_is_O (h₁ : k₁ =o[l] k₂) (h₂ : f' =O[l] g') : (λ x, k₁ x • f' x) =o[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul_is_O h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul (h₁ : k₁ =o[l] k₂) (h₂ : f' =o[l] g') : (λ x, k₁ x • f' x) =o[l] (λ x, k₂ x • g' x) := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] end smul /-! ### Sum -/ section sum variables {ι : Type*} {A : ι → α → E'} {C : ι → ℝ} {s : finset ι} theorem is_O_with.sum (h : ∀ i ∈ s, is_O_with (C i) l (A i) g) : is_O_with (∑ i in s, C i) l (λ x, ∑ i in s, A i x) g := begin induction s using finset.induction_on with i s is IH, { simp only [is_O_with_zero', finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end theorem is_O.sum (h : ∀ i ∈ s, A i =O[l] g) : (λ x, ∑ i in s, A i x) =O[l] g := begin unfold is_O at *, choose! C hC using h, exact ⟨_, is_O_with.sum hC⟩, end theorem is_o.sum (h : ∀ i ∈ s, (A i) =o[l] g') : (λ x, ∑ i in s, A i x) =o[l] g' := begin induction s using finset.induction_on with i s is IH, { simp only [is_o_zero, finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end end sum /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_div_nhds_zero {f g : α → 𝕜} (h : f =o[l] g) : tendsto (λ x, f x / (g x)) l (𝓝 0) := (is_o_one_iff 𝕜).mp $ calc (λ x, f x / g x) =o[l] (λ x, g x / g x) : by simpa only [div_eq_mul_inv] using h.mul_is_O (is_O_refl _ _) ... =O[l] (λ x, (1 : 𝕜)) : is_O_of_le _ (λ x, by simp [div_self_le_one]) theorem is_o.tendsto_inv_smul_nhds_zero [normed_space 𝕜 E'] {f : α → E'} {g : α → 𝕜} {l : filter α} (h : f =o[l] g) : tendsto (λ x, (g x)⁻¹ • f x) l (𝓝 0) := by simpa only [div_eq_inv_mul, ← norm_inv, ← norm_smul, ← tendsto_zero_iff_norm_tendsto_zero] using h.norm_norm.tendsto_div_nhds_zero theorem is_o_iff_tendsto' {f g : α → 𝕜} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) : f =o[l] g ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := ⟨is_o.tendsto_div_nhds_zero, λ h, (((is_o_one_iff _).mpr h).mul_is_O (is_O_refl g l)).congr' (hgf.mono $ λ x, div_mul_cancel_of_imp) (eventually_of_forall $ λ x, one_mul _)⟩ theorem is_o_iff_tendsto {f g : α → 𝕜} (hgf : ∀ x, g x = 0 → f x = 0) : f =o[l] g ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := is_o_iff_tendsto' (eventually_of_forall hgf) alias is_o_iff_tendsto' ↔ _ is_o_of_tendsto' alias is_o_iff_tendsto ↔ _ is_o_of_tendsto lemma is_o_const_left_of_ne {c : E''} (hc : c ≠ 0) : (λ x, c) =o[l] g ↔ tendsto (λ x, ‖g x‖) l at_top := begin simp only [← is_o_one_left_iff ℝ], exact ⟨(is_O_const_const (1 : ℝ) hc l).trans_is_o, (is_O_const_one ℝ c l).trans_is_o⟩ end @[simp] lemma is_o_const_left {c : E''} : (λ x, c) =o[l] g'' ↔ c = 0 ∨ tendsto (norm ∘ g'') l at_top := begin rcases eq_or_ne c 0 with rfl | hc, { simp only [is_o_zero, eq_self_iff_true, true_or] }, { simp only [hc, false_or, is_o_const_left_of_ne hc] } end @[simp] theorem is_o_const_const_iff [ne_bot l] {d : E''} {c : F''} : (λ x, d) =o[l] (λ x, c) ↔ d = 0 := have ¬tendsto (function.const α ‖c‖) l at_top, from not_tendsto_at_top_of_tendsto_nhds tendsto_const_nhds, by simp [function.const, this] @[simp] lemma is_o_pure {x} : f'' =o[pure x] g'' ↔ f'' x = 0 := calc f'' =o[pure x] g'' ↔ (λ y : α, f'' x) =o[pure x] (λ _, g'' x) : is_o_congr rfl rfl ... ↔ f'' x = 0 : is_o_const_const_iff lemma is_o_const_id_comap_norm_at_top (c : F'') : (λ x : E'', c) =o[comap norm at_top] id := is_o_const_left.2 $ or.inr tendsto_comap lemma is_o_const_id_at_top (c : E'') : (λ x : ℝ, c) =o[at_top] id := is_o_const_left.2 $ or.inr tendsto_abs_at_top_at_top lemma is_o_const_id_at_bot (c : E'') : (λ x : ℝ, c) =o[at_bot] id := is_o_const_left.2 $ or.inr tendsto_abs_at_bot_at_top /-! ### Eventually (u / v) * v = u If `u` and `v` are linked by an `is_O_with` relation, then we eventually have `(u / v) * v = u`, even if `v` vanishes. -/ section eventually_mul_div_cancel variables {u v : α → 𝕜} lemma is_O_with.eventually_mul_div_cancel (h : is_O_with c l u v) : (u / v) * v =ᶠ[l] u := eventually.mono h.bound (λ y hy, div_mul_cancel_of_imp $ λ hv, by simpa [hv] using hy) /-- If `u = O(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ lemma is_O.eventually_mul_div_cancel (h : u =O[l] v) : (u / v) * v =ᶠ[l] u := let ⟨c, hc⟩ := h.is_O_with in hc.eventually_mul_div_cancel /-- If `u = o(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ lemma is_o.eventually_mul_div_cancel (h : u =o[l] v) : (u / v) * v =ᶠ[l] u := (h.forall_is_O_with zero_lt_one).eventually_mul_div_cancel end eventually_mul_div_cancel /-! ### Equivalent definitions of the form `∃ φ, u =ᶠ[l] φ * v` in a `normed_field`. -/ section exists_mul_eq variables {u v : α → 𝕜} /-- If `‖φ‖` is eventually bounded by `c`, and `u =ᶠ[l] φ * v`, then we have `is_O_with c u v l`. This does not require any assumptions on `c`, which is why we keep this version along with `is_O_with_iff_exists_eq_mul`. -/ lemma is_O_with_of_eq_mul (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ‖φ x‖ ≤ c) (h : u =ᶠ[l] φ * v) : is_O_with c l u v := begin unfold is_O_with, refine h.symm.rw (λ x a, ‖a‖ ≤ c * ‖v x‖) (hφ.mono $ λ x hx, _), simp only [norm_mul, pi.mul_apply], exact mul_le_mul_of_nonneg_right hx (norm_nonneg _) end lemma is_O_with_iff_exists_eq_mul (hc : 0 ≤ c) : is_O_with c l u v ↔ ∃ (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ‖φ x‖ ≤ c), u =ᶠ[l] φ * v := begin split, { intro h, use (λ x, u x / v x), refine ⟨eventually.mono h.bound (λ y hy, _), h.eventually_mul_div_cancel.symm⟩, simpa using div_le_of_nonneg_of_le_mul (norm_nonneg _) hc hy }, { rintros ⟨φ, hφ, h⟩, exact is_O_with_of_eq_mul φ hφ h } end lemma is_O_with.exists_eq_mul (h : is_O_with c l u v) (hc : 0 ≤ c) : ∃ (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ‖φ x‖ ≤ c), u =ᶠ[l] φ * v := (is_O_with_iff_exists_eq_mul hc).mp h lemma is_O_iff_exists_eq_mul : u =O[l] v ↔ ∃ (φ : α → 𝕜) (hφ : l.is_bounded_under (≤) (norm ∘ φ)), u =ᶠ[l] φ * v := begin split, { rintros h, rcases h.exists_nonneg with ⟨c, hnnc, hc⟩, rcases hc.exists_eq_mul hnnc with ⟨φ, hφ, huvφ⟩, exact ⟨φ, ⟨c, hφ⟩, huvφ⟩ }, { rintros ⟨φ, ⟨c, hφ⟩, huvφ⟩, exact is_O_iff_is_O_with.2 ⟨c, is_O_with_of_eq_mul φ hφ huvφ⟩ } end alias is_O_iff_exists_eq_mul ↔ is_O.exists_eq_mul _ lemma is_o_iff_exists_eq_mul : u =o[l] v ↔ ∃ (φ : α → 𝕜) (hφ : tendsto φ l (𝓝 0)), u =ᶠ[l] φ * v := begin split, { exact λ h, ⟨λ x, u x / v x, h.tendsto_div_nhds_zero, h.eventually_mul_div_cancel.symm⟩ }, { unfold is_o, rintros ⟨φ, hφ, huvφ⟩ c hpos, rw normed_add_comm_group.tendsto_nhds_zero at hφ, exact is_O_with_of_eq_mul _ ((hφ c hpos).mono $ λ x, le_of_lt) huvφ } end alias is_o_iff_exists_eq_mul ↔ is_o.exists_eq_mul _ end exists_mul_eq /-! ### Miscellanous lemmas -/ theorem div_is_bounded_under_of_is_O {α : Type*} {l : filter α} {f g : α → 𝕜} (h : f =O[l] g) : is_bounded_under (≤) l (λ x, ‖f x / g x‖) := begin obtain ⟨c, h₀, hc⟩ := h.exists_nonneg, refine ⟨c, eventually_map.2 (hc.bound.mono (λ x hx, _))⟩, rw [norm_div], exact div_le_of_nonneg_of_le_mul (norm_nonneg _) h₀ hx, end theorem is_O_iff_div_is_bounded_under {α : Type*} {l : filter α} {f g : α → 𝕜} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) : f =O[l] g ↔ is_bounded_under (≤) l (λ x, ‖f x / g x‖) := begin refine ⟨div_is_bounded_under_of_is_O, λ h, _⟩, obtain ⟨c, hc⟩ := h, simp only [eventually_map, norm_div] at hc, refine is_O.of_bound c (hc.mp $ hgf.mono (λ x hx₁ hx₂, _)), by_cases hgx : g x = 0, { simp [hx₁ hgx, hgx] }, { exact (div_le_iff (norm_pos_iff.2 hgx)).mp hx₂ }, end theorem is_O_of_div_tendsto_nhds {α : Type*} {l : filter α} {f g : α → 𝕜} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) (c : 𝕜) (H : filter.tendsto (f / g) l (𝓝 c)) : f =O[l] g := (is_O_iff_div_is_bounded_under hgf).2 $ H.norm.is_bounded_under_le lemma is_o.tendsto_zero_of_tendsto {α E 𝕜 : Type*} [normed_add_comm_group E] [normed_field 𝕜] {u : α → E} {v : α → 𝕜} {l : filter α} {y : 𝕜} (huv : u =o[l] v) (hv : tendsto v l (𝓝 y)) : tendsto u l (𝓝 0) := begin suffices h : u =o[l] (λ x, (1 : 𝕜)), { rwa is_o_one_iff at h }, exact huv.trans_is_O (hv.is_O_one 𝕜), end theorem is_o_pow_pow {m n : ℕ} (h : m < n) : (λ x : 𝕜, x ^ n) =o[𝓝 0] (λ x, x ^ m) := begin rcases lt_iff_exists_add.1 h with ⟨p, hp0 : 0 < p, rfl⟩, suffices : (λ x : 𝕜, x ^ m * x ^ p) =o[𝓝 0] (λ x, x ^ m * 1 ^ p), by simpa only [pow_add, one_pow, mul_one], exact is_O.mul_is_o (is_O_refl _ _) (is_o.pow ((is_o_one_iff _).2 tendsto_id) hp0) end theorem is_o_norm_pow_norm_pow {m n : ℕ} (h : m < n) : (λ x : E', ‖x‖^n) =o[𝓝 0] (λ x, ‖x‖^m) := (is_o_pow_pow h).comp_tendsto tendsto_norm_zero theorem is_o_pow_id {n : ℕ} (h : 1 < n) : (λ x : 𝕜, x^n) =o[𝓝 0] (λ x, x) := by { convert is_o_pow_pow h, simp only [pow_one] } theorem is_o_norm_pow_id {n : ℕ} (h : 1 < n) : (λ x : E', ‖x‖^n) =o[𝓝 0] (λ x, x) := by simpa only [pow_one, is_o_norm_right] using @is_o_norm_pow_norm_pow E' _ _ _ h lemma is_O.eq_zero_of_norm_pow_within {f : E'' → F''} {s : set E''} {x₀ : E''} {n : ℕ} (h : f =O[𝓝[s] x₀] λ x, ‖x - x₀‖ ^ n) (hx₀ : x₀ ∈ s) (hn : 0 < n) : f x₀ = 0 := mem_of_mem_nhds_within hx₀ h.eq_zero_imp $ by simp_rw [sub_self, norm_zero, zero_pow hn] lemma is_O.eq_zero_of_norm_pow {f : E'' → F''} {x₀ : E''} {n : ℕ} (h : f =O[𝓝 x₀] λ x, ‖x - x₀‖ ^ n) (hn : 0 < n) : f x₀ = 0 := by { rw [← nhds_within_univ] at h, exact h.eq_zero_of_norm_pow_within (mem_univ _) hn } lemma is_o_pow_sub_pow_sub (x₀ : E') {n m : ℕ} (h : n < m) : (λ x, ‖x - x₀‖ ^ m) =o[𝓝 x₀] λ x, ‖x - x₀‖^n := begin have : tendsto (λ x, ‖x - x₀‖) (𝓝 x₀) (𝓝 0), { apply tendsto_norm_zero.comp, rw ← sub_self x₀, exact tendsto_id.sub tendsto_const_nhds }, exact (is_o_pow_pow h).comp_tendsto this end lemma is_o_pow_sub_sub (x₀ : E') {m : ℕ} (h : 1 < m) : (λ x, ‖x - x₀‖^m) =o[𝓝 x₀] λ x, x - x₀ := by simpa only [is_o_norm_right, pow_one] using is_o_pow_sub_pow_sub x₀ h theorem is_O_with.right_le_sub_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c l f₁ f₂) (hc : c < 1) : is_O_with (1 / (1 - c)) l f₂ (λx, f₂ x - f₁ x) := is_O_with.of_bound $ mem_of_superset h.bound $ λ x hx, begin simp only [mem_set_of_eq] at hx ⊢, rw [mul_comm, one_div, ← div_eq_mul_inv, le_div_iff, mul_sub, mul_one, mul_comm], { exact le_trans (sub_le_sub_left hx _) (norm_sub_norm_le _ _) }, { exact sub_pos.2 hc } end theorem is_O_with.right_le_add_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c l f₁ f₂) (hc : c < 1) : is_O_with (1 / (1 - c)) l f₂ (λx, f₁ x + f₂ x) := (h.neg_right.right_le_sub_of_lt_1 hc).neg_right.of_neg_left.congr rfl (λ x, rfl) (λ x, by rw [neg_sub, sub_neg_eq_add]) theorem is_o.right_is_O_sub {f₁ f₂ : α → E'} (h : f₁ =o[l] f₂) : f₂ =O[l] (λx, f₂ x - f₁ x) := ((h.def' one_half_pos).right_le_sub_of_lt_1 one_half_lt_one).is_O theorem is_o.right_is_O_add {f₁ f₂ : α → E'} (h : f₁ =o[l] f₂) : f₂ =O[l] (λx, f₁ x + f₂ x) := ((h.def' one_half_pos).right_le_add_of_lt_1 one_half_lt_one).is_O /-- If `f x = O(g x)` along `cofinite`, then there exists a positive constant `C` such that `‖f x‖ ≤ C * ‖g x‖` whenever `g x ≠ 0`. -/ theorem bound_of_is_O_cofinite (h : f =O[cofinite] g'') : ∃ C > 0, ∀ ⦃x⦄, g'' x ≠ 0 → ‖f x‖ ≤ C * ‖g'' x‖ := begin rcases h.exists_pos with ⟨C, C₀, hC⟩, rw [is_O_with, eventually_cofinite] at hC, rcases (hC.to_finset.image (λ x, ‖f x‖ / ‖g'' x‖)).exists_le with ⟨C', hC'⟩, have : ∀ x, C * ‖g'' x‖ < ‖f x‖ → ‖f x‖ / ‖g'' x‖ ≤ C', by simpa using hC', refine ⟨max C C', lt_max_iff.2 (or.inl C₀), λ x h₀, _⟩, rw [max_mul_of_nonneg _ _ (norm_nonneg _), le_max_iff, or_iff_not_imp_left, not_le], exact λ hx, (div_le_iff (norm_pos_iff.2 h₀)).1 (this _ hx) end theorem is_O_cofinite_iff (h : ∀ x, g'' x = 0 → f'' x = 0) : f'' =O[cofinite] g'' ↔ ∃ C, ∀ x, ‖f'' x‖ ≤ C * ‖g'' x‖ := ⟨λ h', let ⟨C, C₀, hC⟩ := bound_of_is_O_cofinite h' in ⟨C, λ x, if hx : g'' x = 0 then by simp [h _ hx, hx] else hC hx⟩, λ h, (is_O_top.2 h).mono le_top⟩ theorem bound_of_is_O_nat_at_top {f : ℕ → E} {g'' : ℕ → E''} (h : f =O[at_top] g'') : ∃ C > 0, ∀ ⦃x⦄, g'' x ≠ 0 → ‖f x‖ ≤ C * ‖g'' x‖ := bound_of_is_O_cofinite $ by rwa nat.cofinite_eq_at_top theorem is_O_nat_at_top_iff {f : ℕ → E''} {g : ℕ → F''} (h : ∀ x, g x = 0 → f x = 0) : f =O[at_top] g ↔ ∃ C, ∀ x, ‖f x‖ ≤ C * ‖g x‖ := by rw [← nat.cofinite_eq_at_top, is_O_cofinite_iff h] theorem is_O_one_nat_at_top_iff {f : ℕ → E''} : f =O[at_top] (λ n, 1 : ℕ → ℝ) ↔ ∃ C, ∀ n, ‖f n‖ ≤ C := iff.trans (is_O_nat_at_top_iff (λ n h, (one_ne_zero h).elim)) $ by simp only [norm_one, mul_one] theorem is_O_with_pi {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_add_comm_group (E' i)] {f : α → Π i, E' i} {C : ℝ} (hC : 0 ≤ C) : is_O_with C l f g' ↔ ∀ i, is_O_with C l (λ x, f x i) g' := have ∀ x, 0 ≤ C * ‖g' x‖, from λ x, mul_nonneg hC (norm_nonneg _), by simp only [is_O_with_iff, pi_norm_le_iff_of_nonneg (this _), eventually_all] @[simp] theorem is_O_pi {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_add_comm_group (E' i)] {f : α → Π i, E' i} : f =O[l] g' ↔ ∀ i, (λ x, f x i) =O[l] g' := begin simp only [is_O_iff_eventually_is_O_with, ← eventually_all], exact eventually_congr (eventually_at_top.2 ⟨0, λ c, is_O_with_pi⟩) end @[simp] theorem is_o_pi {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_add_comm_group (E' i)] {f : α → Π i, E' i} : f =o[l] g' ↔ ∀ i, (λ x, f x i) =o[l] g' := begin simp only [is_o, is_O_with_pi, le_of_lt] { contextual := tt }, exact ⟨λ h i c hc, h hc i, λ h c hc i, h i hc⟩ end end asymptotics open asymptotics lemma summable_of_is_O {ι E} [normed_add_comm_group E] [complete_space E] {f : ι → E} {g : ι → ℝ} (hg : summable g) (h : f =O[cofinite] g) : summable f := let ⟨C, hC⟩ := h.is_O_with in summable_of_norm_bounded_eventually (λ x, C * ‖g x‖) (hg.abs.mul_left _) hC.bound lemma summable_of_is_O_nat {E} [normed_add_comm_group E] [complete_space E] {f : ℕ → E} {g : ℕ → ℝ} (hg : summable g) (h : f =O[at_top] g) : summable f := summable_of_is_O hg $ nat.cofinite_eq_at_top.symm ▸ h namespace local_homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] /-- Transfer `is_O_with` over a `local_homeomorph`. -/ lemma is_O_with_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} {C : ℝ} : is_O_with C (𝓝 b) f g ↔ is_O_with C (𝓝 (e.symm b)) (f ∘ e) (g ∘ e) := ⟨λ h, h.comp_tendsto $ by { convert e.continuous_at (e.map_target hb), exact (e.right_inv hb).symm }, λ h, (h.comp_tendsto (e.continuous_at_symm hb)).congr' rfl ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg f hx) ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg g hx)⟩ /-- Transfer `is_O` over a `local_homeomorph`. -/ lemma is_O_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : f =O[𝓝 b] g ↔ (f ∘ e) =O[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_O, exact exists_congr (λ C, e.is_O_with_congr hb) } /-- Transfer `is_o` over a `local_homeomorph`. -/ lemma is_o_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : f =o[𝓝 b] g ↔ (f ∘ e) =o[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_o, exact forall₂_congr (λ c hc, e.is_O_with_congr hb) } end local_homeomorph namespace homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `homeomorph`. -/ lemma is_O_with_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} {C : ℝ} : is_O_with C (𝓝 b) f g ↔ is_O_with C (𝓝 (e.symm b)) (f ∘ e) (g ∘ e) := e.to_local_homeomorph.is_O_with_congr trivial /-- Transfer `is_O` over a `homeomorph`. -/ lemma is_O_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : f =O[𝓝 b] g ↔ (f ∘ e) =O[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_O, exact exists_congr (λ C, e.is_O_with_congr) } /-- Transfer `is_o` over a `homeomorph`. -/ lemma is_o_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : f =o[𝓝 b] g ↔ (f ∘ e) =o[𝓝 (e.symm b)] (g ∘ e) := by { unfold is_o, exact forall₂_congr (λ c hc, e.is_O_with_congr) } end homeomorph
c3c09e19a2740b74131aee4d4fcaf45d64259526
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/wilson.lean
4d4e9de4c8c5c0e03d01ff5c0aca4aa2891f3e1a
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
1,554
lean
/- Copyright (c) 2022 John Nicol. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: John Nicol -/ import number_theory.legendre_symbol.gauss_eisenstein_lemmas /-! # Wilson's theorem. This file contains a proof of Wilson's theorem. The heavy lifting is mostly done by the previous `wilsons_lemma`, but here we also prove the other logical direction. This could be generalized to similar results about finite abelian groups. ## References * [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) ## TODO * Move `wilsons_lemma` into this file, and give it a descriptive name. -/ open_locale nat namespace nat variable {n : ℕ} /-- For `n > 1`, `(n-1)!` is congruent to `-1` modulo `n` only if n is prime. --/ lemma prime_of_fac_equiv_neg_one (h : ((n - 1)! : zmod n) = -1) (h1 : 1 < n) : prime n := begin by_contradiction h2, obtain ⟨m, hm1, hm2 : 1 < m, hm3⟩ := exists_dvd_of_not_prime2 h1 h2, have hm : m ∣ (n - 1)! := nat.dvd_factorial (pos_of_gt hm2) (le_pred_of_lt hm3), refine hm2.ne' (nat.dvd_one.mp ((nat.dvd_add_right hm).mp (hm1.trans _))), rw [←zmod.nat_coe_zmod_eq_zero_iff_dvd, cast_add, cast_one, h, add_left_neg], end /-- **Wilson's Theorem**: For `n > 1`, `(n-1)!` is congruent to `-1` modulo `n` iff n is prime. --/ theorem prime_iff_fac_equiv_neg_one (h : 1 < n) : prime n ↔ ((n - 1)! : zmod n) = -1 := begin refine ⟨λ h1, _, λ h2, prime_of_fac_equiv_neg_one h2 h⟩, haveI := fact.mk h1, exact zmod.wilsons_lemma n, end end nat
48ceda5d0d12d690ba7c4a0a224940a118d599fe
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/logic.lean
62362a8d4e60d81a0b5765ad3f4a8412c7fa945f
[]
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
40,993
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, Jeremy Avigad, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.core universes u v w l u_1 r s namespace Mathlib @[simp] theorem opt_param_eq (α : Sort u) (default : α) : optParam α default = α := rfl def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun (b : β) (a : α) => f a b /- implication -/ def implies (a : Prop) (b : Prop) := a → b /-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/ theorem implies.trans {p : Prop} {q : Prop} {r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun (hp : p) => h₂ (h₁ hp) def trivial : True := True.intro /-- We can't have `a` and `¬a`, that would be absurd!-/ def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := False._oldrec (h₂ h₁) theorem not.intro {a : Prop} (h : a → False) : ¬a := h /-- Modus tollens. If an implication is true, then so is its contrapositive. -/ theorem mt {a : Prop} {b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun (ha : a) => h₂ (h₁ ha) /- not -/ theorem not_false : ¬False := id def non_contradictory (a : Prop) := ¬¬a theorem non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := fun (hna : ¬a) => absurd ha hna /- false -/ def false.elim {C : Sort u} (h : False) : C := False._oldrec h /- eq -/ -- proof irrelevance is built in theorem proof_irrel {a : Prop} (h₁ : a) (h₂ : a) : h₁ = h₂ := rfl @[simp] theorem id.def {α : Sort u} (a : α) : id a = a := rfl def eq.mp {α : Sort u} {β : Sort u} : α = β → α → β := eq.rec_on def eq.mpr {α : Sort u} {β : Sort u} : α = β → β → α := fun (h₁ : α = β) (h₂ : β) => eq.rec_on sorry h₂ theorem eq.substr {α : Sort u} {p : α → Prop} {a : α} {b : α} (h₁ : b = a) : p a → p b := Eq.subst (Eq.symm h₁) theorem congr {α : Sort u} {β : Sort v} {f₁ : α → β} {f₂ : α → β} {a₁ : α} {a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := h₁ ▸ h₂ ▸ rfl theorem congr_fun {α : Sort u} {β : α → Sort v} {f : (x : α) → β x} {g : (x : α) → β x} (h : f = g) (a : α) : f a = g a := h ▸ Eq.refl (f a) theorem congr_arg {α : Sort u} {β : Sort v} {a₁ : α} {a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl theorem trans_rel_left {α : Sort u} {a : α} {b : α} {c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ theorem trans_rel_right {α : Sort u} {a : α} {b : α} {c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := Eq.symm h₁ ▸ h₂ theorem of_eq_true {p : Prop} (h : p = True) : p := Eq.symm h ▸ trivial theorem not_of_eq_false {p : Prop} (h : p = False) : ¬p := fun (hp : p) => h ▸ hp def cast {α : Sort u} {β : Sort u} (h : α = β) (a : α) : β := Eq._oldrec a h theorem cast_proof_irrel {α : Sort u} {β : Sort u} (h₁ : α = β) (h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl theorem cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ def ne {α : Sort u} (a : α) (b : α) := ¬a = b infixl:50 " ≠ " => Mathlib.ne @[simp] theorem ne.def {α : Sort u} (a : α) (b : α) : a ≠ b = (¬a = b) := rfl namespace ne theorem intro {α : Sort u} {a : α} {b : α} (h : a = b → False) : a ≠ b := h theorem elim {α : Sort u} {a : α} {b : α} (h : a ≠ b) : a = b → False := h theorem irrefl {α : Sort u} {a : α} (h : a ≠ a) : False := h rfl theorem symm {α : Sort u} {a : α} {b : α} (h : a ≠ b) : b ≠ a := fun (h₁ : b = a) => h (Eq.symm h₁) end ne theorem false_of_ne {α : Sort u} {a : α} : a ≠ a → False := ne.irrefl theorem ne_false_of_self {p : Prop} : p → p ≠ False := fun (hp : p) (heq : p = False) => heq ▸ hp theorem ne_true_of_not {p : Prop} : ¬p → p ≠ True := fun (hnp : ¬p) (heq : p = True) => Eq.subst heq hnp trivial theorem true_ne_false : ¬True = False := ne_false_of_self trivial theorem heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) theorem heq.subst {α : Sort u} {β : Sort u} {a : α} {b : β} {p : (T : Sort u) → T → Prop} : a == b → p α a → p β b := heq.rec_on theorem heq.symm {α : Sort u} {β : Sort u} {a : α} {b : β} (h : a == b) : b == a := heq.rec_on h (HEq.refl a) theorem heq_of_eq {α : Sort u} {a : α} {a' : α} (h : a = a') : a == a' := h ▸ HEq.refl a theorem heq.trans {α : Sort u} {β : Sort u} {φ : Sort u} {a : α} {b : β} {c : φ} (h₁ : a == b) (h₂ : b == c) : a == c := HEq.subst h₂ h₁ theorem heq_of_heq_of_eq {α : Sort u} {β : Sort u} {a : α} {b : β} {b' : β} (h₁ : a == b) (h₂ : b = b') : a == b' := HEq.trans h₁ (heq_of_eq h₂) theorem heq_of_eq_of_heq {α : Sort u} {β : Sort u} {a : α} {a' : α} {b : β} (h₁ : a = a') (h₂ : a' == b) : a == b := HEq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq {α : Sort u} {β : Sort u} {a : α} {b : β} (h : a == b) : α = β := heq.rec_on h (Eq.refl α) theorem eq_rec_heq {α : Sort u} {φ : α → Sort v} {a : α} {a' : α} (h : a = a') (p : φ a) : eq.rec_on h p == p := sorry theorem heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} {a : α} {a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : eq.rec_on e p₁ = p₂) : p₁ == p₂ := sorry theorem heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} {a : α} {a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂) : p₁ == p₂ := sorry theorem of_heq_true {a : Prop} (h : a == True) : a := of_eq_true (eq_of_heq h) theorem eq_rec_compose {α : Sort u} {β : Sort u} {φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α) : eq.rec_on p₁ (eq.rec_on p₂ a) = eq.rec_on (Eq.trans p₂ p₁) a := sorry theorem cast_heq {α : Sort u} {β : Sort u} (h : α = β) (a : α) : cast h a == a := sorry infixr:35 " /\ " => Mathlib.and infixr:35 " ∧ " => Mathlib.and /- and -/ theorem and.elim {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∧ b) (h₂ : a → b → c) : c := And._oldrec h₂ h₁ theorem and.swap {a : Prop} {b : Prop} : a ∧ b → b ∧ a := fun (_x : a ∧ b) => (fun (_a : a ∧ b) => and.dcases_on _a fun (left : a) (right : b) => idRhs (b ∧ a) { left := right, right := left }) _x def and.symm {a : Prop} {b : Prop} : a ∧ b → b ∧ a := and.swap infixr:30 " \/ " => Mathlib.or infixr:30 " ∨ " => Mathlib.or /- or -/ namespace or theorem elim {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := Or._oldrec h₂ h₃ h₁ end or theorem non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := fun (not_em : ¬(a ∨ ¬a)) => (fun (neg_a : ¬a) => absurd (Or.inr neg_a) not_em) fun (pos_a : a) => absurd (Or.inl pos_a) not_em def not_not_em (a : Prop) : ¬¬(a ∨ ¬a) := non_contradictory_em theorem or.swap {a : Prop} {b : Prop} : a ∨ b → b ∨ a := Or._oldrec Or.inr Or.inl def or.symm {a : Prop} {b : Prop} : a ∨ b → b ∨ a := or.swap /- xor -/ def xor (a : Prop) (b : Prop) := a ∧ ¬b ∨ b ∧ ¬a /- iff -/ /-- `iff P Q`, with notation `P ↔ Q`, is the proposition asserting that `P` and `Q` are equivalent, that is, have the same truth value. -/ infixl:20 " <-> " => Mathlib.iff infixl:20 " ↔ " => Mathlib.iff theorem iff.elim {a : Prop} {b : Prop} {c : Prop} : ((a → b) → (b → a) → c) → (a ↔ b) → c := Iff._oldrec theorem iff.elim_left {a : Prop} {b : Prop} : (a ↔ b) → a → b := iff.mp theorem iff.elim_right {a : Prop} {b : Prop} : (a ↔ b) → b → a := iff.mpr theorem iff_iff_implies_and_implies (a : Prop) (b : Prop) : a ↔ b ↔ (a → b) ∧ (b → a) := { mp := fun (h : a ↔ b) => { left := iff.mp h, right := iff.mpr h }, mpr := fun (h : (a → b) ∧ (b → a)) => { mp := and.left h, mpr := and.right h } } theorem iff.refl (a : Prop) : a ↔ a := { mp := fun (h : a) => h, mpr := fun (h : a) => h } theorem iff.rfl {a : Prop} : a ↔ a := iff.refl a theorem iff.trans {a : Prop} {b : Prop} {c : Prop} (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := { mp := fun (ha : a) => iff.mp h₂ (iff.mp h₁ ha), mpr := fun (hc : c) => iff.mpr h₁ (iff.mpr h₂ hc) } theorem iff.symm {a : Prop} {b : Prop} (h : a ↔ b) : b ↔ a := { mp := iff.elim_right h, mpr := iff.elim_left h } theorem iff.comm {a : Prop} {b : Prop} : a ↔ b ↔ (b ↔ a) := { mp := iff.symm, mpr := iff.symm } theorem eq.to_iff {a : Prop} {b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl theorem neq_of_not_iff {a : Prop} {b : Prop} : ¬(a ↔ b) → a ≠ b := fun (h₁ : ¬(a ↔ b)) (h₂ : a = b) => (fun (this : a ↔ b) => absurd this h₁) (h₂ ▸ iff.refl a) theorem not_iff_not_of_iff {a : Prop} {b : Prop} (h₁ : a ↔ b) : ¬a ↔ ¬b := { mp := fun (hna : ¬a) (hb : b) => hna (iff.elim_right h₁ hb), mpr := fun (hnb : ¬b) (ha : a) => hnb (iff.elim_left h₁ ha) } theorem of_iff_true {a : Prop} (h : a ↔ True) : a := iff.mp (iff.symm h) trivial theorem not_of_iff_false {a : Prop} : (a ↔ False) → ¬a := iff.mp theorem iff_true_intro {a : Prop} (h : a) : a ↔ True := { mp := fun (hl : a) => trivial, mpr := fun (hr : True) => h } theorem iff_false_intro {a : Prop} (h : ¬a) : a ↔ False := { mp := h, mpr := False._oldrec } theorem not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := { mp := fun (hl : ¬¬¬a) (ha : a) => hl (non_contradictory_intro ha), mpr := absurd } def not_not_not_iff (a : Prop) : ¬¬¬a ↔ ¬a := not_non_contradictory_iff_absurd theorem imp_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a → b ↔ c → d := { mp := fun (hab : a → b) (hc : c) => iff.mp h₂ (hab (iff.mpr h₁ hc)), mpr := fun (hcd : c → d) (ha : a) => iff.mpr h₂ (hcd (iff.mp h₁ ha)) } theorem imp_congr_ctx {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : a → b ↔ c → d := { mp := fun (hab : a → b) (hc : c) => (fun (ha : a) => (fun (hb : b) => iff.mp (h₂ hc) hb) (hab ha)) (iff.mpr h₁ hc), mpr := fun (hcd : c → d) (ha : a) => (fun (hc : c) => (fun (hd : d) => iff.mpr (h₂ hc) hd) (hcd hc)) (iff.mp h₁ ha) } theorem imp_congr_right {a : Prop} {b : Prop} {c : Prop} (h : a → (b ↔ c)) : a → b ↔ a → c := { mp := fun (hab : a → b) (ha : a) => iff.elim_left (h ha) (hab ha), mpr := fun (hab : a → c) (ha : a) => iff.elim_right (h ha) (hab ha) } theorem not_not_intro {a : Prop} (ha : a) : ¬¬a := fun (hna : ¬a) => hna ha theorem not_of_not_not_not {a : Prop} (h : ¬¬¬a) : ¬a := fun (ha : a) => absurd (not_not_intro ha) h @[simp] theorem not_true : ¬True ↔ False := iff_false_intro (not_not_intro trivial) def not_true_iff : ¬True ↔ False := not_true @[simp] theorem not_false_iff : ¬False ↔ True := iff_true_intro not_false theorem not_congr {a : Prop} {b : Prop} (h : a ↔ b) : ¬a ↔ ¬b := { mp := fun (h₁ : ¬a) (h₂ : b) => h₁ (iff.mpr h h₂), mpr := fun (h₁ : ¬b) (h₂ : a) => h₁ (iff.mp h h₂) } @[simp] theorem ne_self_iff_false {α : Sort u} (a : α) : ¬a = a ↔ False := { mp := false_of_ne, mpr := false.elim } @[simp] theorem eq_self_iff_true {α : Sort u} (a : α) : a = a ↔ True := iff_true_intro rfl @[simp] theorem heq_self_iff_true {α : Sort u} (a : α) : a == a ↔ True := iff_true_intro (HEq.refl a) @[simp] theorem iff_not_self (a : Prop) : a ↔ ¬a ↔ False := iff_false_intro fun (h : a ↔ ¬a) => (fun (h' : ¬a) => h' (iff.mpr h h')) fun (ha : a) => iff.mp h ha ha @[simp] theorem not_iff_self (a : Prop) : ¬a ↔ a ↔ False := iff_false_intro fun (h : ¬a ↔ a) => (fun (h' : ¬a) => h' (iff.mp h h')) fun (ha : a) => iff.mpr h ha ha @[simp] theorem true_iff_false : True ↔ False ↔ False := iff_false_intro fun (h : True ↔ False) => iff.mp h trivial @[simp] theorem false_iff_true : False ↔ True ↔ False := iff_false_intro fun (h : False ↔ True) => iff.mpr h trivial theorem false_of_true_iff_false : (True ↔ False) → False := fun (h : True ↔ False) => iff.mp h trivial theorem false_of_true_eq_false : True = False → False := fun (h : True = False) => h ▸ trivial theorem true_eq_false_of_false : False → True = False := false.elim theorem eq_comm {α : Sort u} {a : α} {b : α} : a = b ↔ b = a := { mp := Eq.symm, mpr := Eq.symm } /- and simp rules -/ theorem and.imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := sorry def and_implies {a : Prop} {b : Prop} {c : Prop} {d : Prop} (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := and.imp theorem and_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a ∧ b ↔ c ∧ d := { mp := and.imp (iff.mp h₁) (iff.mp h₂), mpr := and.imp (iff.mpr h₁) (iff.mpr h₂) } theorem and_congr_right {a : Prop} {b : Prop} {c : Prop} (h : a → (b ↔ c)) : a ∧ b ↔ a ∧ c := sorry theorem and.comm {a : Prop} {b : Prop} : a ∧ b ↔ b ∧ a := { mp := and.swap, mpr := and.swap } theorem and_comm (a : Prop) (b : Prop) : a ∧ b ↔ b ∧ a := and.comm theorem and.assoc {a : Prop} {b : Prop} {c : Prop} : (a ∧ b) ∧ c ↔ a ∧ b ∧ c := sorry theorem and_assoc {c : Prop} (a : Prop) (b : Prop) : (a ∧ b) ∧ c ↔ a ∧ b ∧ c := and.assoc theorem and.left_comm {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∧ c ↔ b ∧ a ∧ c := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) theorem and_iff_left {a : Prop} {b : Prop} (hb : b) : a ∧ b ↔ a := { mp := and.left, mpr := fun (ha : a) => { left := ha, right := hb } } theorem and_iff_right {a : Prop} {b : Prop} (ha : a) : a ∧ b ↔ b := { mp := and.right, mpr := And.intro ha } @[simp] theorem and_true (a : Prop) : a ∧ True ↔ a := and_iff_left trivial @[simp] theorem true_and (a : Prop) : True ∧ a ↔ a := and_iff_right trivial @[simp] theorem and_false (a : Prop) : a ∧ False ↔ False := iff_false_intro and.right @[simp] theorem false_and (a : Prop) : False ∧ a ↔ False := iff_false_intro and.left @[simp] theorem not_and_self (a : Prop) : ¬a ∧ a ↔ False := iff_false_intro fun (h : ¬a ∧ a) => and.elim h fun (h₁ : ¬a) (h₂ : a) => absurd h₂ h₁ @[simp] theorem and_not_self (a : Prop) : a ∧ ¬a ↔ False := iff_false_intro fun (_x : a ∧ ¬a) => (fun (_a : a ∧ ¬a) => and.dcases_on _a fun (left : a) (right : ¬a) => idRhs False (absurd left right)) _x @[simp] theorem and_self (a : Prop) : a ∧ a ↔ a := { mp := and.left, mpr := fun (h : a) => { left := h, right := h } } /- or simp rules -/ theorem or.imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := Or._oldrec (fun (h : a) => Or.inl (h₂ h)) fun (h : b) => Or.inr (h₃ h) theorem or.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a → b) : a ∨ c → b ∨ c := or.imp h id theorem or.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a → b) : c ∨ a → c ∨ b := or.imp id h theorem or_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a ∨ b ↔ c ∨ d := { mp := or.imp (iff.mp h₁) (iff.mp h₂), mpr := or.imp (iff.mpr h₁) (iff.mpr h₂) } theorem or.comm {a : Prop} {b : Prop} : a ∨ b ↔ b ∨ a := { mp := or.swap, mpr := or.swap } theorem or_comm (a : Prop) (b : Prop) : a ∨ b ↔ b ∨ a := or.comm theorem or.assoc {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∨ c ↔ a ∨ b ∨ c := { mp := Or._oldrec (or.imp_right Or.inl) fun (h : c) => Or.inr (Or.inr h), mpr := Or._oldrec (fun (h : a) => Or.inl (Or.inl h)) (or.imp_left Or.inr) } theorem or_assoc {c : Prop} (a : Prop) (b : Prop) : (a ∨ b) ∨ c ↔ a ∨ b ∨ c := or.assoc theorem or.left_comm {a : Prop} {b : Prop} {c : Prop} : a ∨ b ∨ c ↔ b ∨ a ∨ c := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp {a : Prop} {b : Prop} (ha : a → b) : a ∨ b ↔ b := { mp := Or._oldrec ha id, mpr := Or.inr } theorem or_iff_left_of_imp {a : Prop} {b : Prop} (hb : b → a) : a ∨ b ↔ a := { mp := Or._oldrec id hb, mpr := Or.inl } @[simp] theorem or_true (a : Prop) : a ∨ True ↔ True := iff_true_intro (Or.inr trivial) @[simp] theorem true_or (a : Prop) : True ∨ a ↔ True := iff_true_intro (Or.inl trivial) @[simp] theorem or_false (a : Prop) : a ∨ False ↔ a := { mp := Or._oldrec id false.elim, mpr := Or.inl } @[simp] theorem false_or (a : Prop) : False ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] theorem or_self (a : Prop) : a ∨ a ↔ a := { mp := Or._oldrec id id, mpr := Or.inl } theorem not_or {a : Prop} {b : Prop} : ¬a → ¬b → ¬(a ∨ b) := fun (ᾰ : ¬a) (ᾰ_1 : ¬b) (ᾰ_2 : a ∨ b) => or.dcases_on ᾰ_2 (fun (ᾰ_1 : a) => idRhs False (absurd ᾰ_1 ᾰ)) fun (ᾰ_1_1 : b) => idRhs False (absurd ᾰ_1_1 ᾰ_1) /- or resolution rulse -/ def or.resolve_left {a : Prop} {b : Prop} (h : a ∨ b) (na : ¬a) : b := or.elim h (fun (ha : a) => absurd ha na) id def or.neg_resolve_left {a : Prop} {b : Prop} (h : ¬a ∨ b) (ha : a) : b := or.elim h (fun (na : ¬a) => absurd ha na) id def or.resolve_right {a : Prop} {b : Prop} (h : a ∨ b) (nb : ¬b) : a := or.elim h id fun (hb : b) => absurd hb nb def or.neg_resolve_right {a : Prop} {b : Prop} (h : a ∨ ¬b) (hb : b) : a := or.elim h id fun (nb : ¬b) => absurd hb nb /- iff simp rules -/ @[simp] theorem iff_true (a : Prop) : a ↔ True ↔ a := { mp := fun (h : a ↔ True) => iff.mpr h trivial, mpr := iff_true_intro } @[simp] theorem true_iff (a : Prop) : True ↔ a ↔ a := iff.trans iff.comm (iff_true a) @[simp] theorem iff_false (a : Prop) : a ↔ False ↔ ¬a := { mp := iff.mp, mpr := iff_false_intro } @[simp] theorem false_iff (a : Prop) : False ↔ a ↔ ¬a := iff.trans iff.comm (iff_false a) @[simp] theorem iff_self (a : Prop) : a ↔ a ↔ True := iff_true_intro iff.rfl theorem iff_congr {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ↔ c) (h₂ : b ↔ d) : a ↔ b ↔ (c ↔ d) := iff.trans (iff_iff_implies_and_implies a b) (iff.trans (and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)) (iff.symm (iff_iff_implies_and_implies c d))) /- implies simp rule -/ @[simp] theorem implies_true_iff (α : Sort u) : α → True ↔ True := { mp := fun (h : α → True) => trivial, mpr := fun (ha : True) (h : α) => trivial } @[simp] theorem false_implies_iff (a : Prop) : False → a ↔ True := { mp := fun (h : False → a) => trivial, mpr := fun (ha : True) (h : False) => false.elim h } @[simp] theorem true_implies_iff (α : Prop) : True → α ↔ α := { mp := fun (h : True → α) => h trivial, mpr := fun (h : α) (h' : True) => h } /-- The existential quantifier. To prove a goal of the form `⊢ ∃ x, p x`, you can provide a witness `y` with the tactic `existsi y`. If you are working in a project that depends on mathlib, then we recommend the `use` tactic instead. You'll then be left with the goal `⊢ p y`. To extract a witness `x` and proof `hx : p x` from a hypothesis `h : ∃ x, p x`, use the tactic `cases h with x hx`. See also the mathlib tactics `obtain` and `rcases`. -/ def exists.intro {α : Sort u_1} {p : α → Prop} (w : α) (h : p w) : Exists p := Exists.intro theorem exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ (x : α), p x) (h₂ : ∀ (a : α), p a → b) : b := Exists._oldrec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ (x : α), p x ∧ ∀ (y : α), p y → y = x theorem exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ (y : α), p y → y = w) : exists_unique fun (x : α) => p x := exists.intro w { left := h₁, right := h₂ } theorem exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : exists_unique fun (x : α) => p x) (h₁ : ∀ (x : α), p x → (∀ (y : α), p y → y = x) → b) : b := exists.elim h₂ fun (w : α) (hw : (fun (x : α) => p x) w ∧ ∀ (y : α), p y → y = w) => h₁ w (and.left hw) (and.right hw) theorem exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ (x : α), p x) (hunique : ∀ (y₁ y₂ : α), p y₁ → p y₂ → y₁ = y₂) : exists_unique fun (x : α) => p x := exists.elim hex fun (x : α) (px : p x) => exists_unique.intro x px fun (y : α) (this : p y) => hunique y x this px theorem exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : exists_unique fun (x : α) => p x) : ∃ (x : α), p x := exists.elim h fun (x : α) (hx : (fun (x : α) => p x) x ∧ ∀ (y : α), p y → y = x) => Exists.intro x (and.left hx) theorem unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : exists_unique fun (x : α) => p x) {y₁ : α} {y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h fun (x : α) (this : p x) (unique : ∀ (y : α), p y → y = x) => (fun (this : y₁ = y₂) => this) (Eq.trans (unique y₁ py₁) (Eq.symm (unique y₂ py₂))) /- exists, forall, exists unique congruences -/ theorem forall_congr {α : Sort u} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a ↔ q a) : (∀ (a : α), p a) ↔ ∀ (a : α), q a := { mp := fun (p_1 : ∀ (a : α), p a) (a : α) => iff.mp (h a) (p_1 a), mpr := fun (q_1 : ∀ (a : α), q a) (a : α) => iff.mpr (h a) (q_1 a) } theorem exists_imp_exists {α : Sort u} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a → q a) : (∃ (a : α), p a) → ∃ (a : α), q a := fun (p_1 : ∃ (a : α), p a) => exists.elim p_1 fun (a : α) (hp : p a) => Exists.intro a (h a hp) theorem exists_congr {α : Sort u} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a ↔ q a) : Exists p ↔ ∃ (a : α), q a := { mp := exists_imp_exists fun (a : α) => iff.mp (h a), mpr := exists_imp_exists fun (a : α) => iff.mpr (h a) } theorem exists_unique_congr {α : Sort u} {p₁ : α → Prop} {p₂ : α → Prop} (h : ∀ (x : α), p₁ x ↔ p₂ x) : exists_unique p₁ ↔ exists_unique fun (x : α) => p₂ x := exists_congr fun (x : α) => and_congr (h x) (forall_congr fun (y : α) => imp_congr (h y) iff.rfl) theorem forall_not_of_not_exists {α : Sort u} {p : α → Prop} : (¬∃ (x : α), p x) → ∀ (x : α), ¬p x := fun (hne : ¬∃ (x : α), p x) (x : α) (hp : p x) => hne (Exists.intro x hp) /- decidable -/ def decidable.to_bool (p : Prop) [h : Decidable p] : Bool := decidable.cases_on h (fun (h₁ : ¬p) => false) fun (h₂ : p) => tt @[simp] theorem to_bool_true_eq_tt (h : Decidable True) : to_bool True = tt := decidable.cases_on h (fun (h : ¬True) => false.elim (iff.mp not_true h)) fun (_x : True) => rfl @[simp] theorem to_bool_false_eq_ff (h : Decidable False) : to_bool False = false := decidable.cases_on h (fun (h : ¬False) => rfl) fun (h : False) => false.elim h protected instance decidable.true : Decidable True := is_true trivial protected instance decidable.false : Decidable False := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches def dite (c : Prop) [h : Decidable c] {α : Sort u} : (c → α) → (¬c → α) → α := fun (t : c → α) (e : ¬c → α) => decidable.rec_on h e t /- if-then-else -/ def ite (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : α := decidable.rec_on h (fun (hnc : ¬c) => e) fun (hc : c) => t namespace decidable def rec_on_true {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (fun (h : ¬p) => False._oldrec (h h₃)) fun (h : p) => h₄ def rec_on_false {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (fun (h : ¬p) => h₄) fun (h : p) => False._oldrec (h₃ h) def by_cases {p : Prop} {q : Sort u} [φ : Decidable p] : (p → q) → (¬p → q) → q := dite p theorem em (p : Prop) [Decidable p] : p ∨ ¬p := by_cases Or.inl Or.inr theorem by_contradiction {p : Prop} [Decidable p] (h : ¬p → False) : p := dite p (fun (h₁ : p) => h₁) fun (h₁ : ¬p) => False._oldrec (h h₁) theorem of_not_not {p : Prop} [Decidable p] : ¬¬p → p := fun (hnn : ¬¬p) => by_contradiction fun (hn : ¬p) => absurd hn hnn theorem not_not_iff (p : Prop) [Decidable p] : ¬¬p ↔ p := { mp := of_not_not, mpr := not_not_intro } theorem not_and_iff_or_not (p : Prop) (q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬(p ∧ q) ↔ ¬p ∨ ¬q := sorry theorem not_or_iff_and_not (p : Prop) (q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬(p ∨ q) ↔ ¬p ∧ ¬q := sorry end decidable def decidable_of_decidable_of_iff {p : Prop} {q : Prop} (hp : Decidable p) (h : p ↔ q) : Decidable q := dite p (fun (hp : p) => is_true (iff.mp h hp)) fun (hp : ¬p) => is_false sorry def decidable_of_decidable_of_eq {p : Prop} {q : Prop} (hp : Decidable p) (h : p = q) : Decidable q := decidable_of_decidable_of_iff hp (eq.to_iff h) protected def or.by_cases {p : Prop} {q : Prop} [Decidable p] [Decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := dite p (fun (hp : p) => h₁ hp) fun (hp : ¬p) => dite q (fun (hq : q) => h₂ hq) fun (hq : ¬q) => False._oldrec (or.elim h hp hq) protected instance and.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p ∧ q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_true { left := hp, right := hq }) fun (hq : ¬q) => is_false sorry) fun (hp : ¬p) => is_false sorry protected instance or.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p ∨ q) := dite p (fun (hp : p) => is_true (Or.inl hp)) fun (hp : ¬p) => dite q (fun (hq : q) => is_true (Or.inr hq)) fun (hq : ¬q) => is_false (Or._oldrec hp hq) protected instance not.decidable {p : Prop} [Decidable p] : Decidable (¬p) := dite p (fun (hp : p) => is_false (absurd hp)) fun (hp : ¬p) => is_true hp protected instance implies.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p → q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_true sorry) fun (hq : ¬q) => is_false sorry) fun (hp : ¬p) => is_true sorry protected instance iff.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (p ↔ q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_true sorry) fun (hq : ¬q) => is_false sorry) fun (hp : ¬p) => dite q (fun (hq : q) => is_false sorry) fun (hq : ¬q) => is_true sorry protected instance xor.decidable {p : Prop} {q : Prop} [Decidable p] [Decidable q] : Decidable (xor p q) := dite p (fun (hp : p) => dite q (fun (hq : q) => is_false sorry) fun (hq : ¬q) => is_true sorry) fun (hp : ¬p) => dite q (fun (hq : q) => is_true sorry) fun (hq : ¬q) => is_false sorry protected instance exists_prop_decidable {p : Prop} (P : p → Prop) [Dp : Decidable p] [DP : (h : p) → Decidable (P h)] : Decidable (∃ (h : p), P h) := dite p (fun (h : p) => decidable_of_decidable_of_iff (DP h) sorry) fun (h : ¬p) => is_false sorry protected instance forall_prop_decidable {p : Prop} (P : p → Prop) [Dp : Decidable p] [DP : (h : p) → Decidable (P h)] : Decidable (∀ (h : p), P h) := dite p (fun (h : p) => decidable_of_decidable_of_iff (DP h) sorry) fun (h : ¬p) => is_true sorry protected instance ne.decidable {α : Sort u} [DecidableEq α] (a : α) (b : α) : Decidable (a ≠ b) := implies.decidable theorem bool.ff_ne_tt : false = tt → False := fun (ᾰ : false = tt) => eq.dcases_on ᾰ (fun (H_1 : tt = false) => bool.no_confusion H_1) (Eq.refl tt) (HEq.refl ᾰ) def is_dec_eq {α : Sort u} (p : α → α → Bool) := ∀ {x y : α}, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → Bool) := ∀ (x : α), p x x = tt protected instance bool.decidable_eq : DecidableEq Bool := sorry def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → Bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : DecidableEq α := fun (x y : α) => dite (p x y = tt) (fun (hp : p x y = tt) => is_true (h₁ hp)) fun (hp : ¬p x y = tt) => is_false sorry theorem decidable_eq_inl_refl {α : Sort u} [h : DecidableEq α] (a : α) : h a a = is_true (Eq.refl a) := sorry theorem decidable_eq_inr_neg {α : Sort u} [h : DecidableEq α] {a : α} {b : α} (n : a ≠ b) : h a b = is_false n := sorry /- inhabited -/ def arbitrary (α : Sort u) [Inhabited α] : α := Inhabited.default protected instance prop.inhabited : Inhabited Prop := { default := True } protected instance pi.inhabited (α : Sort u) {β : α → Sort v} [(x : α) → Inhabited (β x)] : Inhabited ((x : α) → β x) := { default := fun (a : α) => Inhabited.default } protected instance bool.inhabited : Inhabited Bool := { default := false } protected instance true.inhabited : Inhabited True := { default := trivial } protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := Nonempty._oldrec h₂ h₁ protected instance nonempty_of_inhabited {α : Sort u} [Inhabited α] : Nonempty α := Nonempty.intro Inhabited.default theorem nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ (x : α), p x) → Nonempty α := fun (ᾰ : ∃ (x : α), p x) => Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : p ᾰ_w) => idRhs (Nonempty α) (Nonempty.intro ᾰ_w) /- subsingleton -/ class inductive subsingleton (α : Sort u) where | intro : (∀ (a b : α), a = b) → subsingleton α protected def subsingleton.elim {α : Sort u} [h : subsingleton α] (a : α) (b : α) : a = b := subsingleton._oldrec (fun (p : ∀ (a b : α), a = b) => p) h protected def subsingleton.helim {α : Sort u} {β : Sort u} [h : subsingleton α] : α = β → ∀ (a : α) (b : β), a == b := fun (h_1 : α = β) => eq.rec_on h_1 fun (a b : α) => heq_of_eq (subsingleton.elim a b) protected instance subsingleton_prop (p : Prop) : subsingleton p := subsingleton.intro fun (a b : p) => proof_irrel a b protected instance decidable.subsingleton (p : Prop) : subsingleton (Decidable p) := subsingleton.intro fun (d₁ : Decidable p) => sorry protected theorem rec_subsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := sorry theorem if_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : α} {e : α} : ite c t e = t := sorry theorem if_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : α} {e : α} : ite c t e = e := sorry @[simp] theorem if_t_t (c : Prop) [h : Decidable c] {α : Sort u} (t : α) : ite c t t = t := sorry theorem implies_of_if_pos {c : Prop} {t : Prop} {e : Prop} [Decidable c] (h : ite c t e) : c → t := fun (hc : c) => eq.rec_on (if_pos hc) h theorem implies_of_if_neg {c : Prop} {t : Prop} {e : Prop} [Decidable c] (h : ite c t e) : ¬c → e := fun (hnc : ¬c) => eq.rec_on (if_neg hnc) h theorem if_ctx_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : α} {y : α} {u : α} {v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := sorry theorem if_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : α} {y : α} {u : α} {v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := if_ctx_congr h_c (fun (h : c) => h_t) fun (h : ¬c) => h_e @[simp] theorem if_true {α : Sort u} {h : Decidable True} (t : α) (e : α) : ite True t e = t := if_pos trivial @[simp] theorem if_false {α : Sort u} {h : Decidable False} (t : α) (e : α) : ite False t e = e := if_neg not_false theorem if_ctx_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {v : Prop} [dec_b : Decidable b] [dec_c : Decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := sorry theorem if_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {v : Prop} [dec_b : Decidable b] [dec_c : Decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (fun (h : c) => h_t) fun (h : ¬c) => h_e theorem if_ctx_simp_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {v : Prop} [dec_b : Decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c h_t h_e theorem if_simp_congr_prop {b : Prop} {c : Prop} {x : Prop} {y : Prop} {u : Prop} {v : Prop} [dec_b : Decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_simp_congr_prop h_c (fun (h : c) => h_t) fun (h : ¬c) => h_e @[simp] theorem dif_pos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬c → α} : dite c t e = t hc := sorry @[simp] theorem dif_neg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬c → α} : dite c t e = e hnc := sorry theorem dif_ctx_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] [dec_c : Decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : dite b x y = dite c u v := sorry theorem dif_ctx_simp_congr {α : Sort u} {b : Prop} {c : Prop} [dec_b : Decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : dite b x y = dite c u v := dif_ctx_congr h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem dif_eq_if (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : (dite c (fun (h : c) => t) fun (h : ¬c) => e) = ite c t e := sorry protected instance ite.decidable {c : Prop} {t : Prop} {e : Prop} [d_c : Decidable c] [d_t : Decidable t] [d_e : Decidable e] : Decidable (ite c t e) := sorry protected instance dite.decidable {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : Decidable c] [d_t : (h : c) → Decidable (t h)] [d_e : (h : ¬c) → Decidable (e h)] : Decidable (dite c (fun (h : c) => t h) fun (h : ¬c) => e h) := sorry def as_true (c : Prop) [Decidable c] := ite c True False def as_false (c : Prop) [Decidable c] := ite c False True def of_as_true {c : Prop} [h₁ : Decidable c] (h₂ : as_true c) : c := sorry /-- Universe lifting operation -/ structure ulift (α : Type s) up :: where (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ theorem up_down {α : Type u} (b : ulift α) : up (down b) = b := cases_on b fun (b : α) => idRhs (up (down (up b)) = up (down (up b))) rfl end ulift theorem ulift.down_up {α : Type u} (a : α) : ulift.down (ulift.up a) = a := rfl /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) up :: where (down : α) namespace plift /- Bijection between α and plift α -/ theorem up_down {α : Sort u} (b : plift α) : up (down b) = b := cases_on b fun (b : α) => idRhs (up (down (up b)) = up (down (up b))) rfl end plift theorem plift.down_up {α : Sort u} (a : α) : plift.down (plift.up a) = a := rfl /- Equalities for rewriting let-expressions -/ theorem let_value_eq {α : Sort u} {β : Sort v} {a₁ : α} {a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁; b x) = let x : α := a₂; b x := fun (h : a₁ = a₂) => eq.rec_on h rfl theorem let_value_heq {α : Sort v} {β : α → Sort u} {a₁ : α} {a₂ : α} (b : (x : α) → β x) : a₁ = a₂ → (let x : α := a₁; b x) == let x : α := a₂; b x := fun (h : a₁ = a₂) => eq.rec_on h (HEq.refl (b a₁)) theorem let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ : (x : α) → β x} {b₂ : (x : α) → β x} : (∀ (x : α), b₁ x = b₂ x) → (let x : α := a; b₁ x) = let x : α := a; b₂ x := fun (h : ∀ (x : α), b₁ x = b₂ x) => h a theorem let_eq {α : Sort v} {β : Sort u} {a₁ : α} {a₂ : α} {b₁ : α → β} {b₂ : α → β} : a₁ = a₂ → (∀ (x : α), b₁ x = b₂ x) → (let x : α := a₁; b₁ x) = let x : α := a₂; b₂ x := fun (h₁ : a₁ = a₂) (h₂ : ∀ (x : α), b₁ x = b₂ x) => eq.rec_on h₁ (h₂ a₁) def reflexive {β : Sort v} (r : β → β → Prop) := ∀ (x : β), r x x def symmetric {β : Sort v} (r : β → β → Prop) := ∀ {x y : β}, r x y → r y x def transitive {β : Sort v} (r : β → β → Prop) := ∀ {x y z : β}, r x y → r y z → r x z def equivalence {β : Sort v} (r : β → β → Prop) := reflexive r ∧ symmetric r ∧ transitive r def total {β : Sort v} (r : β → β → Prop) := ∀ (x y : β), r x y ∨ r y x def mk_equivalence {β : Sort v} (r : β → β → Prop) (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := { left := rfl, right := { left := symm, right := trans } } def irreflexive {β : Sort v} (r : β → β → Prop) := ∀ (x : β), ¬r x x def anti_symmetric {β : Sort v} (r : β → β → Prop) := ∀ {x y : β}, r x y → r y x → x = y def empty_relation {α : Sort u} (a₁ : α) (a₂ : α) := False def subrelation {β : Sort v} (q : β → β → Prop) (r : β → β → Prop) := ∀ {x y : β}, q x y → r x y def inv_image {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun (a₁ a₂ : α) => r (f a₁) (f a₂) theorem inv_image.trans {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) (h : transitive r) : transitive (inv_image r f) := fun (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃) => h h₁ h₂ theorem inv_image.irreflexive {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := fun (a : α) (h₁ : inv_image r f a a) => h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop where | base : ∀ (a b : α), r a b → tc r a b | trans : ∀ (a b c : α), tc r a b → tc r b c → tc r a c def commutative {α : Type u} (f : α → α → α) := ∀ (a b : α), f a b = f b a def associative {α : Type u} (f : α → α → α) := ∀ (a b c : α), f (f a b) c = f a (f b c) def left_identity {α : Type u} (f : α → α → α) (one : α) := ∀ (a : α), f one a = a def right_identity {α : Type u} (f : α → α → α) (one : α) := ∀ (a : α), f a one = a def right_inverse {α : Type u} (f : α → α → α) (inv : α → α) (one : α) := ∀ (a : α), f a (inv a) = one def left_cancelative {α : Type u} (f : α → α → α) := ∀ (a b c : α), f a b = f a c → b = c def right_cancelative {α : Type u} (f : α → α → α) := ∀ (a b c : α), f a b = f c b → a = c def left_distributive {α : Type u} (f : α → α → α) (g : α → α → α) := ∀ (a b c : α), f a (g b c) = g (f a b) (f a c) def right_distributive {α : Type u} (f : α → α → α) (g : α → α → α) := ∀ (a b c : α), f (g a b) c = g (f a c) (f b c) def right_commutative {α : Type u} {β : Type v} (h : β → α → β) := ∀ (b : β) (a₁ a₂ : α), h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative {α : Type u} {β : Type v} (h : α → β → β) := ∀ (a₁ a₂ : α) (b : β), h a₁ (h a₂ b) = h a₂ (h a₁ b) theorem left_comm {α : Type u} (f : α → α → α) : commutative f → associative f → left_commutative f := fun (hcomm : commutative f) (hassoc : associative f) (a b c : α) => Eq.trans (Eq.trans (Eq.symm (hassoc a b c)) (hcomm a b ▸ rfl)) (hassoc b a c) theorem right_comm {α : Type u} (f : α → α → α) : commutative f → associative f → right_commutative f := fun (hcomm : commutative f) (hassoc : associative f) (a b c : α) => Eq.trans (Eq.trans (hassoc a b c) (hcomm b c ▸ rfl)) (Eq.symm (hassoc a c b))
aa20218db3578e51ac8488d9edc37675b1b10467
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Kei.lean
b2431909ef4b49b98c57acc95fe41f1d811b8d20
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
5,797
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Kei structure Kei (A : Type) : Type := (linv : (A → (A → A))) (leftDistributive : (∀ {x y z : A} , (linv x (linv y z)) = (linv (linv x y) (linv x z)))) (idempotent_linv : (∀ {x : A} , (linv x x) = x)) (rightSelfInverse_linv : (∀ {x y : A} , (linv (linv x y) y) = x)) open Kei structure Sig (AS : Type) : Type := (linvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftDistributiveP : (∀ {xP yP zP : (Prod A A)} , (linvP xP (linvP yP zP)) = (linvP (linvP xP yP) (linvP xP zP)))) (idempotent_linvP : (∀ {xP : (Prod A A)} , (linvP xP xP) = xP)) (rightSelfInverse_linvP : (∀ {xP yP : (Prod A A)} , (linvP (linvP xP yP) yP) = xP)) structure Hom {A1 : Type} {A2 : Type} (Ke1 : (Kei A1)) (Ke2 : (Kei A2)) : Type := (hom : (A1 → A2)) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Ke1) x1 x2)) = ((linv Ke2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ke1 : (Kei A1)) (Ke2 : (Kei A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Ke1) x1 x2) ((linv Ke2) y1 y2)))))) inductive KeiTerm : Type | linvL : (KeiTerm → (KeiTerm → KeiTerm)) open KeiTerm inductive ClKeiTerm (A : Type) : Type | sing : (A → ClKeiTerm) | linvCl : (ClKeiTerm → (ClKeiTerm → ClKeiTerm)) open ClKeiTerm inductive OpKeiTerm (n : ℕ) : Type | v : ((fin n) → OpKeiTerm) | linvOL : (OpKeiTerm → (OpKeiTerm → OpKeiTerm)) open OpKeiTerm inductive OpKeiTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpKeiTerm2) | sing2 : (A → OpKeiTerm2) | linvOL2 : (OpKeiTerm2 → (OpKeiTerm2 → OpKeiTerm2)) open OpKeiTerm2 def simplifyCl {A : Type} : ((ClKeiTerm A) → (ClKeiTerm A)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpKeiTerm n) → (OpKeiTerm n)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpKeiTerm2 n A) → (OpKeiTerm2 n A)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Kei A) → (KeiTerm → A)) | Ke (linvL x1 x2) := ((linv Ke) (evalB Ke x1) (evalB Ke x2)) def evalCl {A : Type} : ((Kei A) → ((ClKeiTerm A) → A)) | Ke (sing x1) := x1 | Ke (linvCl x1 x2) := ((linv Ke) (evalCl Ke x1) (evalCl Ke x2)) def evalOpB {A : Type} {n : ℕ} : ((Kei A) → ((vector A n) → ((OpKeiTerm n) → A))) | Ke vars (v x1) := (nth vars x1) | Ke vars (linvOL x1 x2) := ((linv Ke) (evalOpB Ke vars x1) (evalOpB Ke vars x2)) def evalOp {A : Type} {n : ℕ} : ((Kei A) → ((vector A n) → ((OpKeiTerm2 n A) → A))) | Ke vars (v2 x1) := (nth vars x1) | Ke vars (sing2 x1) := x1 | Ke vars (linvOL2 x1 x2) := ((linv Ke) (evalOp Ke vars x1) (evalOp Ke vars x2)) def inductionB {P : (KeiTerm → Type)} : ((∀ (x1 x2 : KeiTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → (∀ (x : KeiTerm) , (P x))) | plinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl x1) (inductionB plinvl x2)) def inductionCl {A : Type} {P : ((ClKeiTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClKeiTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → (∀ (x : (ClKeiTerm A)) , (P x)))) | psing plinvcl (sing x1) := (psing x1) | psing plinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl x1) (inductionCl psing plinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpKeiTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpKeiTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → (∀ (x : (OpKeiTerm n)) , (P x)))) | pv plinvol (v x1) := (pv x1) | pv plinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol x1) (inductionOpB pv plinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpKeiTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpKeiTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → (∀ (x : (OpKeiTerm2 n A)) , (P x))))) | pv2 psing2 plinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 plinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 plinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 x1) (inductionOp pv2 psing2 plinvol2 x2)) def stageB : (KeiTerm → (Staged KeiTerm)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClKeiTerm A) → (Staged (ClKeiTerm A))) | (sing x1) := (Now (sing x1)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpKeiTerm n) → (Staged (OpKeiTerm n))) | (v x1) := (const (code (v x1))) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpKeiTerm2 n A) → (Staged (OpKeiTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (linvT : ((Repr A) → ((Repr A) → (Repr A)))) end Kei
76a6aadadd9f2c247dc8103210554c45e3e05a80
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/chain.lean
f6a833023408af99f9565587574ad569eafd4b56
[ "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,141
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Mario Carneiro -/ import tactic.ext open interactive namespace tactic /- This file defines a `chain` tactic, which takes a list of tactics, and exhaustively tries to apply them to the goals, until no tactic succeeds on any goal. Along the way, it generates auxiliary declarations, in order to speed up elaboration time of the resulting (sometimes long!) proofs. This tactic is used by the `tidy` tactic. -/ -- α is the return type of our tactics. When `chain` is called by `tidy`, this is string, -- describing what that tactic did as an interactive tactic. variable {α : Type} inductive tactic_script (α : Type) : Type | base : α → tactic_script | work (index : ℕ) (first : α) (later : list tactic_script) (closed : bool) : tactic_script meta def tactic_script.to_string : tactic_script string → string | (tactic_script.base a) := a | (tactic_script.work n a l c) := "work_on_goal " ++ (to_string (n+1)) ++ " { " ++ (", ".intercalate (a :: l.map tactic_script.to_string)) ++ " }" meta instance : has_to_string (tactic_script string) := { to_string := λ s, s.to_string } meta instance tactic_script_unit_has_to_string : has_to_string (tactic_script unit) := { to_string := λ s, "[chain tactic]" } meta def abstract_if_success (tac : expr → tactic α) (g : expr) : tactic α := do type ← infer_type g, is_lemma ← is_prop type, if is_lemma then -- there's no point making the abstraction, and indeed it's slower tac g else do m ← mk_meta_var type, a ← tac m, do { val ← instantiate_mvars m, guard (val.list_meta_vars = []), c ← new_aux_decl_name, gs ← get_goals, set_goals [g], add_aux_decl c type val ff >>= unify g, set_goals gs } <|> unify m g, return a /-- `chain_many tac` recursively tries `tac` on all goals, working depth-first on generated subgoals, until it no longer succeeds on any goal. `chain_many` automatically makes auxiliary definitions. -/ meta mutual def chain_single, chain_many, chain_iter {α} (tac : tactic α) with chain_single : expr → tactic (α × list (tactic_script α)) | g := do set_goals [g], a ← tac, l ← get_goals >>= chain_many, return (a, l) with chain_many : list expr → tactic (list (tactic_script α)) | [] := return [] | [g] := do { (a, l) ← chain_single g, return (tactic_script.base a :: l) } <|> return [] | gs := chain_iter gs [] with chain_iter : list expr → list expr → tactic (list (tactic_script α)) | [] _ := return [] | (g :: later_goals) stuck_goals := do { (a, l) ← abstract_if_success chain_single g, new_goals ← get_goals, let w := tactic_script.work stuck_goals.length a l (new_goals = []), let current_goals := stuck_goals.reverse ++ new_goals ++ later_goals, set_goals current_goals, -- we keep the goals up to date, so they are correct at the end l' ← chain_many current_goals, return (w :: l') } <|> chain_iter later_goals (g :: stuck_goals) meta def chain_core {α : Type} [has_to_string (tactic_script α)] (tactics : list (tactic α)) : tactic (list string) := do results ← (get_goals >>= chain_many (first tactics)), when results.empty (fail "`chain` tactic made no progress"), return (results.map to_string) variables [has_to_string (tactic_script α)] [has_to_format α] declare_trace chain meta def trace_output (t : tactic α) : tactic α := do tgt ← target, r ← t, name ← decl_name, trace format!"`chain` successfully applied a tactic during elaboration of {name}:", tgt ← pp tgt, trace format!"previous target: {tgt}", trace format!"tactic result: {r}", tgt ← try_core target, tgt ← match tgt with | (some tgt) := pp tgt | none := return "no goals" end, trace format!"new target: {tgt}", pure r meta def chain (tactics : list (tactic α)) : tactic (list string) := chain_core (if is_trace_enabled_for `chain then (tactics.map trace_output) else tactics) end tactic
3d607e37d196695a22e7f0304243eb30afaf22de
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/stage0/src/Lean/Elab/PreDefinition/WF/Main.lean
eaf8d862022d45bccc2734036879818491c58261
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,287
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.PreDefinition.Basic import Lean.Elab.PreDefinition.WF.TerminationHint import Lean.Elab.PreDefinition.WF.PackDomain import Lean.Elab.PreDefinition.WF.PackMutual import Lean.Elab.PreDefinition.WF.Rel import Lean.Elab.PreDefinition.WF.Fix namespace Lean.Elab open WF open Meta private partial def addNonRecPreDefs (preDefs : Array PreDefinition) (preDefNonRec : PreDefinition) : TermElabM Unit := do let Expr.forallE _ domain _ _ ← preDefNonRec.type | unreachable! let us := preDefNonRec.levelParams.map mkLevelParam for fidx in [:preDefs.size] do let preDef := preDefs[fidx] let value ← lambdaTelescope preDef.value fun xs _ => do let mkProd (type : Expr) : MetaM Expr := do mkUnaryArg type xs let rec mkSum (i : Nat) (type : Expr) : MetaM Expr := do if i == preDefs.size - 1 then mkProd type else (← whnfD type).withApp fun f args => do assert! args.size == 2 if i == fidx then return mkApp3 (mkConst ``Sum.inl f.constLevels!) args[0] args[1] (← mkProd args[0]) else let r ← mkSum (i+1) args[1] return mkApp3 (mkConst ``Sum.inr f.constLevels!) args[0] args[1] r let arg ← mkSum 0 domain mkLambdaFVars xs (mkApp (mkConst preDefNonRec.declName us) arg) trace[Elab.definition.wf] "{preDef.declName} := {value}" addNonRec { preDef with value } def wfRecursion (preDefs : Array PreDefinition) (wfStx? : Option Syntax) (decrTactic? : Option Syntax) : TermElabM Unit := do let unaryPreDef ← withoutModifyingEnv do for preDef in preDefs do addAsAxiom preDef let unaryPreDefs ← packDomain preDefs packMutual unaryPreDefs let wfRel ← elabWFRel unaryPreDef wfStx? let preDefNonRec ← withoutModifyingEnv do addAsAxiom unaryPreDef mkFix unaryPreDef wfRel decrTactic? trace[Elab.definition.wf] ">> {preDefNonRec.declName}" addNonRec preDefNonRec addNonRecPreDefs preDefs preDefNonRec addAndCompilePartialRec preDefs builtin_initialize registerTraceClass `Elab.definition.wf end Lean.Elab
c9eab872318bef6b9b4758e229f9fd36e6eff091
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/lebesgue/basic.lean
ba416fc42a780ca1895a08fe8f3494375384470a
[ "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
28,332
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, Sébastien Gouëzel, Yury Kudryashov -/ import dynamics.ergodic.measure_preserving import linear_algebra.determinant import linear_algebra.matrix.diagonal import linear_algebra.matrix.transvection import measure_theory.constructions.pi import measure_theory.measure.stieltjes import measure_theory.measure.haar.of_basis /-! # Lebesgue measure on the real line and on `ℝⁿ` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We show that the Lebesgue measure on the real line (constructed as a particular case of additive Haar measure on inner product spaces) coincides with the Stieltjes measure associated to the function `x ↦ x`. We deduce properties of this measure on `ℝ`, and then of the product Lebesgue measure on `ℝⁿ`. In particular, we prove that they are translation invariant. We show that, on `ℝⁿ`, a linear map acts on Lebesgue measure by rescaling it through the absolute value of its determinant, in `real.map_linear_map_volume_pi_eq_smul_volume_pi`. More properties of the Lebesgue measure are deduced from this in `lebesgue.eq_haar.lean`, where they are proved more generally for any additive Haar measure on a finite-dimensional real vector space. -/ assert_not_exists measure_theory.integral noncomputable theory open classical set filter measure_theory measure_theory.measure topological_space open ennreal (of_real) open_locale big_operators ennreal nnreal topology /-! ### Definition of the Lebesgue measure and lengths of intervals -/ namespace real variables {ι : Type*} [fintype ι] /-- The volume on the real line (as a particular case of the volume on a finite-dimensional inner product space) coincides with the Stieltjes measure coming from the identity function. -/ lemma volume_eq_stieltjes_id : (volume : measure ℝ) = stieltjes_function.id.measure := begin haveI : is_add_left_invariant stieltjes_function.id.measure := ⟨λ a, eq.symm $ real.measure_ext_Ioo_rat $ λ p q, by simp only [measure.map_apply (measurable_const_add a) measurable_set_Ioo, sub_sub_sub_cancel_right, stieltjes_function.measure_Ioo, stieltjes_function.id_left_lim, stieltjes_function.id_apply, id.def, preimage_const_add_Ioo]⟩, have A : stieltjes_function.id.measure (std_orthonormal_basis ℝ ℝ).to_basis.parallelepiped = 1, { change stieltjes_function.id.measure (parallelepiped (std_orthonormal_basis ℝ ℝ)) = 1, rcases parallelepiped_orthonormal_basis_one_dim (std_orthonormal_basis ℝ ℝ) with H|H; simp only [H, stieltjes_function.measure_Icc, stieltjes_function.id_apply, id.def, tsub_zero, stieltjes_function.id_left_lim, sub_neg_eq_add, zero_add, ennreal.of_real_one] }, conv_rhs { rw [add_haar_measure_unique stieltjes_function.id.measure (std_orthonormal_basis ℝ ℝ).to_basis.parallelepiped, A] }, simp only [volume, basis.add_haar, one_smul], end theorem volume_val (s) : volume s = stieltjes_function.id.measure s := by simp [volume_eq_stieltjes_id] @[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := by simp [volume_val] @[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := by simp [volume_val] @[simp] lemma volume_univ : volume (univ : set ℝ) = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, calc (r : ℝ≥0∞) = volume (Icc (0 : ℝ) r) : by simp ... ≤ volume univ : measure_mono (subset_univ _) @[simp] lemma volume_ball (a r : ℝ) : volume (metric.ball a r) = of_real (2 * r) := by rw [ball_eq_Ioo, volume_Ioo, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_closed_ball (a r : ℝ) : volume (metric.closed_ball a r) = of_real (2 * r) := by rw [closed_ball_eq_Icc, volume_Icc, ← sub_add, add_sub_cancel', two_mul] @[simp] lemma volume_emetric_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [metric.emetric_ball_top, volume_univ, two_mul, _root_.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_ball_nnreal, volume_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end @[simp] lemma volume_emetric_closed_ball (a : ℝ) (r : ℝ≥0∞) : volume (emetric.closed_ball a r) = 2 * r := begin rcases eq_or_ne r ∞ with rfl|hr, { rw [emetric.closed_ball_top, volume_univ, two_mul, _root_.top_add] }, { lift r to ℝ≥0 using hr, rw [metric.emetric_closed_ball_nnreal, volume_closed_ball, two_mul, ← nnreal.coe_add, ennreal.of_real_coe_nnreal, ennreal.coe_add, two_mul] } end instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) := ⟨λ x, volume_singleton⟩ @[simp] lemma volume_interval {a b : ℝ} : volume (uIcc a b) = of_real (|b - a|) := by rw [←Icc_min_max, volume_Icc, max_sub_min_eq_abs] @[simp] lemma volume_Ioi {a : ℝ} : volume (Ioi a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo a (a + n)) : by simp ... ≤ volume (Ioi a) : measure_mono Ioo_subset_Ioi_self @[simp] lemma volume_Ici {a : ℝ} : volume (Ici a) = ∞ := by simp [← measure_congr Ioi_ae_eq_Ici] @[simp] lemma volume_Iio {a : ℝ} : volume (Iio a) = ∞ := top_unique $ le_of_tendsto' ennreal.tendsto_nat_nhds_top $ λ n, calc (n : ℝ≥0∞) = volume (Ioo (a - n) a) : by simp ... ≤ volume (Iio a) : measure_mono Ioo_subset_Iio_self @[simp] lemma volume_Iic {a : ℝ} : volume (Iic a) = ∞ := by simp [← measure_congr Iio_ae_eq_Iic] instance locally_finite_volume : is_locally_finite_measure (volume : measure ℝ) := ⟨λ x, ⟨Ioo (x - 1) (x + 1), is_open.mem_nhds is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩ instance is_finite_measure_restrict_Icc (x y : ℝ) : is_finite_measure (volume.restrict (Icc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ico (x y : ℝ) : is_finite_measure (volume.restrict (Ico x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioc (x y : ℝ) : is_finite_measure (volume.restrict (Ioc x y)) := ⟨by simp⟩ instance is_finite_measure_restrict_Ioo (x y : ℝ) : is_finite_measure (volume.restrict (Ioo x y)) := ⟨by simp⟩ lemma volume_le_diam (s : set ℝ) : volume s ≤ emetric.diam s := begin by_cases hs : metric.bounded s, { rw [real.ediam_eq hs, ← volume_Icc], exact volume.mono (real.subset_Icc_Inf_Sup_of_bounded hs) }, { rw metric.ediam_of_unbounded hs, exact le_top } end lemma _root_.filter.eventually.volume_pos_of_nhds_real {p : ℝ → Prop} {a : ℝ} (h : ∀ᶠ x in 𝓝 a, p x) : (0 : ℝ≥0∞) < volume {x | p x} := begin rcases h.exists_Ioo_subset with ⟨l, u, hx, hs⟩, refine lt_of_lt_of_le _ (measure_mono hs), simpa [-mem_Ioo] using hx.1.trans hx.2 end /-! ### Volume of a box in `ℝⁿ` -/ lemma volume_Icc_pi {a b : ι → ℝ} : volume (Icc a b) = ∏ i, ennreal.of_real (b i - a i) := begin rw [← pi_univ_Icc, volume_pi_pi], simp only [real.volume_Icc] end @[simp] lemma volume_Icc_pi_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (Icc a b)).to_real = ∏ i, (b i - a i) := by simp only [volume_Icc_pi, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioo {a b : ι → ℝ} : volume (pi univ (λ i, Ioo (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioo_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioo_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioo (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioo, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ioc {a b : ι → ℝ} : volume (pi univ (λ i, Ioc (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ioc_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ioc_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ioc (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ioc, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] lemma volume_pi_Ico {a b : ι → ℝ} : volume (pi univ (λ i, Ico (a i) (b i))) = ∏ i, ennreal.of_real (b i - a i) := (measure_congr measure.univ_pi_Ico_ae_eq_Icc).trans volume_Icc_pi @[simp] lemma volume_pi_Ico_to_real {a b : ι → ℝ} (h : a ≤ b) : (volume (pi univ (λ i, Ico (a i) (b i)))).to_real = ∏ i, (b i - a i) := by simp only [volume_pi_Ico, ennreal.to_real_prod, ennreal.to_real_of_real (sub_nonneg.2 (h _))] @[simp] lemma volume_pi_ball (a : ι → ℝ) {r : ℝ} (hr : 0 < r) : volume (metric.ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_ball a hr, volume_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr.le) _).symm end @[simp] lemma volume_pi_closed_ball (a : ι → ℝ) {r : ℝ} (hr : 0 ≤ r) : volume (metric.closed_ball a r) = ennreal.of_real ((2 * r) ^ fintype.card ι) := begin simp only [volume_pi_closed_ball a hr, volume_closed_ball, finset.prod_const], exact (ennreal.of_real_pow (mul_nonneg zero_le_two hr) _).symm end lemma volume_pi_le_prod_diam (s : set (ι → ℝ)) : volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) := calc volume s ≤ volume (pi univ (λ i, closure (function.eval i '' s))) : volume.mono $ subset.trans (subset_pi_eval_image univ s) $ pi_mono $ λ i hi, subset_closure ... = ∏ i, volume (closure $ function.eval i '' s) : volume_pi_pi _ ... ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : finset.prod_le_prod' $ λ i hi, (volume_le_diam _).trans_eq (emetric.diam_closure _) lemma volume_pi_le_diam_pow (s : set (ι → ℝ)) : volume s ≤ emetric.diam s ^ fintype.card ι := calc volume s ≤ ∏ i : ι, emetric.diam (function.eval i '' s) : volume_pi_le_prod_diam s ... ≤ ∏ i : ι, (1 : ℝ≥0) * emetric.diam s : finset.prod_le_prod' $ λ i hi, (lipschitz_with.eval i).ediam_image_le s ... = emetric.diam s ^ fintype.card ι : by simp only [ennreal.coe_one, one_mul, finset.prod_const, fintype.card] /-! ### Images of the Lebesgue measure under multiplication in ℝ -/ lemma smul_map_volume_mul_left {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map ((*) a) volume = volume := begin refine (real.measure_ext_Ioo_rat $ λ p q, _).symm, cases lt_or_gt_of_ne h with h h, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, neg_sub_neg, neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, smul_eq_mul, mul_div_cancel' _ (ne_of_lt h)] }, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h), measure.map_apply (measurable_const_mul a) measurable_set_Ioo, preimage_const_mul_Ioo _ _ h, abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h), smul_eq_mul] } end lemma map_volume_mul_left {a : ℝ} (h : a ≠ 0) : measure.map ((*) a) volume = ennreal.of_real (|a⁻¹|) • volume := by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one, one_smul] } @[simp] lemma volume_preimage_mul_left {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume (((*) a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume (((*) a) ⁻¹' s) = measure.map ((*) a) volume s : ((homeomorph.mul_left₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_left h, refl } lemma smul_map_volume_mul_right {a : ℝ} (h : a ≠ 0) : ennreal.of_real (|a|) • measure.map (* a) volume = volume := by simpa only [mul_comm] using real.smul_map_volume_mul_left h lemma map_volume_mul_right {a : ℝ} (h : a ≠ 0) : measure.map (* a) volume = ennreal.of_real (|a⁻¹|) • volume := by simpa only [mul_comm] using real.map_volume_mul_left h @[simp] lemma volume_preimage_mul_right {a : ℝ} (h : a ≠ 0) (s : set ℝ) : volume ((* a) ⁻¹' s) = ennreal.of_real (abs a⁻¹) * volume s := calc volume ((* a) ⁻¹' s) = measure.map (* a) volume s : ((homeomorph.mul_right₀ a h).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs a⁻¹) * volume s : by { rw map_volume_mul_right h, refl } /-! ### Images of the Lebesgue measure under translation/linear maps in ℝⁿ -/ open matrix /-- A diagonal matrix rescales Lebesgue according to its determinant. This is a special case of `real.map_matrix_volume_pi_eq_smul_volume_pi`, that one should use instead (and whose proof uses this particular case). -/ lemma smul_map_diagonal_volume_pi [decidable_eq ι] {D : ι → ℝ} (h : det (diagonal D) ≠ 0) : ennreal.of_real (abs (det (diagonal D))) • measure.map ((diagonal D).to_lin') volume = volume := begin refine (measure.pi_eq (λ s hs, _)).symm, simp only [det_diagonal, measure.coe_smul, algebra.id.smul_eq_mul, pi.smul_apply], rw [measure.map_apply _ (measurable_set.univ_pi hs)], swap, { exact continuous.measurable (linear_map.continuous_on_pi _) }, have : (matrix.to_lin' (diagonal D)) ⁻¹' (set.pi set.univ (λ (i : ι), s i)) = set.pi set.univ (λ (i : ι), ((*) (D i)) ⁻¹' (s i)), { ext f, simp only [linear_map.coe_proj, algebra.id.smul_eq_mul, linear_map.smul_apply, mem_univ_pi, mem_preimage, linear_map.pi_apply, diagonal_to_lin'] }, have B : ∀ i, of_real (abs (D i)) * volume (has_mul.mul (D i) ⁻¹' s i) = volume (s i), { assume i, have A : D i ≠ 0, { simp only [det_diagonal, ne.def] at h, exact finset.prod_ne_zero_iff.1 h i (finset.mem_univ i) }, rw [volume_preimage_mul_left A, ← mul_assoc, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_inv_cancel A, abs_one, ennreal.of_real_one, one_mul] }, rw [this, volume_pi_pi, finset.abs_prod, ennreal.of_real_prod_of_nonneg (λ i hi, abs_nonneg (D i)), ← finset.prod_mul_distrib], simp only [B] end /-- A transvection preserves Lebesgue measure. -/ lemma volume_preserving_transvection_struct [decidable_eq ι] (t : transvection_struct ι ℝ) : measure_preserving (t.to_matrix.to_lin') := begin /- We separate the coordinate along which there is a shearing from the other ones, and apply Fubini. Along this coordinate (and when all the other coordinates are fixed), it acts like a translation, and therefore preserves Lebesgue. -/ let p : ι → Prop := λ i, i ≠ t.i, let α : Type* := {x // p x}, let β : Type* := {x // ¬ (p x)}, let g : (α → ℝ) → (β → ℝ) → (β → ℝ) := λ a b, (λ x, t.c * a ⟨t.j, t.hij.symm⟩) + b, let F : (α → ℝ) × (β → ℝ) → (α → ℝ) × (β → ℝ) := λ p, (id p.1, g p.1 p.2), let e : (ι → ℝ) ≃ᵐ (α → ℝ) × (β → ℝ) := measurable_equiv.pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p, have : (t.to_matrix.to_lin' : (ι → ℝ) → (ι → ℝ)) = e.symm ∘ F ∘ e, { cases t, ext f k, simp only [linear_equiv.map_smul, dite_eq_ite, linear_map.id_coe, p, ite_not, algebra.id.smul_eq_mul, one_mul, dot_product, std_basis_matrix, measurable_equiv.pi_equiv_pi_subtype_prod_symm_apply, id.def, transvection, pi.add_apply, zero_mul, linear_map.smul_apply, function.comp_app, measurable_equiv.pi_equiv_pi_subtype_prod_apply, matrix.transvection_struct.to_matrix_mk, matrix.mul_vec, linear_equiv.map_add, ite_mul, e, matrix.to_lin'_apply, pi.smul_apply, subtype.coe_mk, g, linear_map.add_apply, finset.sum_congr, matrix.to_lin'_one], by_cases h : t_i = k, { simp only [h, true_and, finset.mem_univ, if_true, eq_self_iff_true, finset.sum_ite_eq, one_apply, boole_mul, add_comm], }, { simp only [h, ne.symm h, add_zero, if_false, finset.sum_const_zero, false_and, mul_zero] } }, rw this, have A : measure_preserving e, { convert volume_preserving_pi_equiv_pi_subtype_prod (λ i : ι, ℝ) p }, have B : measure_preserving F, { have g_meas : measurable (function.uncurry g), { have : measurable (λ (c : (α → ℝ)), c ⟨t.j, t.hij.symm⟩) := measurable_pi_apply ⟨t.j, t.hij.symm⟩, refine (measurable_pi_lambda _ (λ i, measurable.const_mul _ _)).add measurable_snd, exact this.comp measurable_fst }, exact (measure_preserving.id _).skew_product g_meas (eventually_of_forall (λ a, map_add_left_eq_self _ _)) }, exact ((A.symm e).comp B).comp A, end /-- Any invertible matrix rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_matrix_volume_pi_eq_smul_volume_pi [decidable_eq ι] {M : matrix ι ι ℝ} (hM : det M ≠ 0) : measure.map M.to_lin' volume = ennreal.of_real (abs (det M)⁻¹) • volume := begin -- This follows from the cases we have already proved, of diagonal matrices and transvections, -- as these matrices generate all invertible matrices. apply diagonal_transvection_induction_of_det_ne_zero _ M hM (λ D hD, _) (λ t, _) (λ A B hA hB IHA IHB, _), { conv_rhs { rw [← smul_map_diagonal_volume_pi hD] }, rw [smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel hD, abs_one, ennreal.of_real_one, one_smul] }, { simp only [matrix.transvection_struct.det, ennreal.of_real_one, (volume_preserving_transvection_struct _).map_eq, one_smul, _root_.inv_one, abs_one] }, { rw [to_lin'_mul, det_mul, linear_map.coe_comp, ← measure.map_map, IHB, measure.map_smul, IHA, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, mul_comm, mul_inv], { apply continuous.measurable, apply linear_map.continuous_on_pi }, { apply continuous.measurable, apply linear_map.continuous_on_pi } } end /-- Any invertible linear map rescales Lebesgue measure through the absolute value of its determinant. -/ lemma map_linear_map_volume_pi_eq_smul_volume_pi {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0) : measure.map f volume = ennreal.of_real (abs (f.det)⁻¹) • volume := begin -- this is deduced from the matrix case classical, let M := f.to_matrix', have A : f.det = det M, by simp only [linear_map.det_to_matrix'], have B : f = M.to_lin', by simp only [to_lin'_to_matrix'], rw [A, B], apply map_matrix_volume_pi_eq_smul_volume_pi, rwa A at hf end end real section region_between variable {α : Type*} /-- The region between two real-valued functions on an arbitrary set. -/ def region_between (f g : α → ℝ) (s : set α) : set (α × ℝ) := {p : α × ℝ | p.1 ∈ s ∧ p.2 ∈ Ioo (f p.1) (g p.1)} lemma region_between_subset (f g : α → ℝ) (s : set α) : region_between f g s ⊆ s ×ˢ univ := by simpa only [prod_univ, region_between, set.preimage, set_of_subset_set_of] using λ a, and.left variables [measurable_space α] {μ : measure α} {f g : α → ℝ} {s : set α} /-- The region between two measurable functions on a measurable set is measurable. -/ lemma measurable_set_region_between (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set (region_between f g s) := begin dsimp only [region_between, Ioo, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graph of the upper function. -/ lemma measurable_set_region_between_oc (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Ioc (f p.fst) (g p.fst)} := begin dsimp only [region_between, Ioc, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_lt (hf.comp measurable_fst) measurable_snd).inter (measurable_set_le measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graph of the lower function. -/ lemma measurable_set_region_between_co (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Ico (f p.fst) (g p.fst)} := begin dsimp only [region_between, Ico, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_le (hf.comp measurable_fst) measurable_snd).inter (measurable_set_lt measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The region between two measurable functions on a measurable set is measurable; a version for the region together with the graphs of both functions. -/ lemma measurable_set_region_between_cc (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : measurable_set {p : α × ℝ | p.fst ∈ s ∧ p.snd ∈ Icc (f p.fst) (g p.fst)} := begin dsimp only [region_between, Icc, mem_set_of_eq, set_of_and], refine measurable_set.inter _ ((measurable_set_le (hf.comp measurable_fst) measurable_snd).inter (measurable_set_le measurable_snd (hg.comp measurable_fst))), exact measurable_fst hs, end /-- The graph of a measurable function is a measurable set. -/ lemma measurable_set_graph (hf : measurable f) : measurable_set {p : α × ℝ | p.snd = f p.fst} := by simpa using measurable_set_region_between_cc hf hf measurable_set.univ theorem volume_region_between_eq_lintegral' (hf : measurable f) (hg : measurable g) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin classical, rw measure.prod_apply, { have h : (λ x, volume {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)}) = s.indicator (λ x, ennreal.of_real (g x - f x)), { funext x, rw indicator_apply, split_ifs, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = Ioo (f x) (g x) := by simp [h, Ioo], simp only [hx, real.volume_Ioo, sub_zero] }, { have hx : {a | x ∈ s ∧ a ∈ Ioo (f x) (g x)} = ∅ := by simp [h], simp only [hx, measure_empty] } }, dsimp only [region_between, preimage_set_of_eq], rw [h, lintegral_indicator]; simp only [hs, pi.sub_apply] }, { exact measurable_set_region_between hf hg hs }, end /-- The volume of the region between two almost everywhere measurable functions on a measurable set can be represented as a Lebesgue integral. -/ theorem volume_region_between_eq_lintegral [sigma_finite μ] (hf : ae_measurable f (μ.restrict s)) (hg : ae_measurable g (μ.restrict s)) (hs : measurable_set s) : μ.prod volume (region_between f g s) = ∫⁻ y in s, ennreal.of_real ((g - f) y) ∂μ := begin have h₁ : (λ y, ennreal.of_real ((g - f) y)) =ᵐ[μ.restrict s] λ y, ennreal.of_real ((ae_measurable.mk g hg - ae_measurable.mk f hf) y) := (hg.ae_eq_mk.sub hf.ae_eq_mk).fun_comp _, have h₂ : (μ.restrict s).prod volume (region_between f g s) = (μ.restrict s).prod volume (region_between (ae_measurable.mk f hf) (ae_measurable.mk g hg) s), { apply measure_congr, apply eventually_eq.rfl.inter, exact ((quasi_measure_preserving_fst.ae_eq_comp hf.ae_eq_mk).comp₂ _ eventually_eq.rfl).inter (eventually_eq.rfl.comp₂ _ $ quasi_measure_preserving_fst.ae_eq_comp hg.ae_eq_mk) }, rw [lintegral_congr_ae h₁, ← volume_region_between_eq_lintegral' hf.measurable_mk hg.measurable_mk hs], convert h₂ using 1, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset f g s)).symm, }, { rw measure.restrict_prod_eq_prod_univ, exact (measure.restrict_eq_self _ (region_between_subset (ae_measurable.mk f hf) (ae_measurable.mk g hg) s)).symm }, end end region_between /-- Consider a real set `s`. If a property is true almost everywhere in `s ∩ (a, b)` for all `a, b ∈ s`, then it is true almost everywhere in `s`. Formulated with `μ.restrict`. See also `ae_of_mem_of_ae_of_mem_inter_Ioo`. -/ lemma ae_restrict_of_ae_restrict_inter_Ioo {μ : measure ℝ} [has_no_atoms μ] {s : set ℝ} {p : ℝ → Prop} (h : ∀ a b, a ∈ s → b ∈ s → a < b → ∀ᵐ x ∂(μ.restrict (s ∩ Ioo a b)), p x) : ∀ᵐ x ∂(μ.restrict s), p x := begin /- By second-countability, we cover `s` by countably many intervals `(a, b)` (except maybe for two endpoints, which don't matter since `μ` does not have any atom). -/ let T : s × s → set ℝ := λ p, Ioo p.1 p.2, let u := ⋃ (i : ↥s × ↥s), T i, have hfinite : (s \ u).finite := s.finite_diff_Union_Ioo', obtain ⟨A, A_count, hA⟩ : ∃ (A : set (↥s × ↥s)), A.countable ∧ (⋃ (i ∈ A), T i) = ⋃ (i : ↥s × ↥s), T i := is_open_Union_countable _ (λ p, is_open_Ioo), have : s ⊆ (s \ u) ∪ (⋃ p ∈ A, s ∩ T p), { assume x hx, by_cases h'x : x ∈ ⋃ (i : ↥s × ↥s), T i, { rw ← hA at h'x, obtain ⟨p, pA, xp⟩ : ∃ (p : ↥s × ↥s), p ∈ A ∧ x ∈ T p, by simpa only [mem_Union, exists_prop, set_coe.exists, exists_and_distrib_right] using h'x, right, exact mem_bUnion pA ⟨hx, xp⟩ }, { exact or.inl ⟨hx, h'x⟩ } }, apply ae_restrict_of_ae_restrict_of_subset this, rw [ae_restrict_union_iff, ae_restrict_bUnion_iff _ A_count], split, { have : μ.restrict (s \ u) = 0, by simp only [restrict_eq_zero, hfinite.measure_zero], simp only [this, ae_zero] }, { rintros ⟨⟨a, as⟩, ⟨b, bs⟩⟩ -, dsimp [T], rcases le_or_lt b a with hba|hab, { simp only [Ioo_eq_empty_of_le hba, inter_empty, restrict_empty, ae_zero] }, { exact h a b as bs hab } } end /-- Consider a real set `s`. If a property is true almost everywhere in `s ∩ (a, b)` for all `a, b ∈ s`, then it is true almost everywhere in `s`. Formulated with bare membership. See also `ae_restrict_of_ae_restrict_inter_Ioo`. -/ lemma ae_of_mem_of_ae_of_mem_inter_Ioo {μ : measure ℝ} [has_no_atoms μ] {s : set ℝ} {p : ℝ → Prop} (h : ∀ a b, a ∈ s → b ∈ s → a < b → ∀ᵐ x ∂μ, x ∈ s ∩ Ioo a b → p x) : ∀ᵐ x ∂μ, x ∈ s → p x := begin /- By second-countability, we cover `s` by countably many intervals `(a, b)` (except maybe for two endpoints, which don't matter since `μ` does not have any atom). -/ let T : s × s → set ℝ := λ p, Ioo p.1 p.2, let u := ⋃ (i : ↥s × ↥s), T i, have hfinite : (s \ u).finite := s.finite_diff_Union_Ioo', obtain ⟨A, A_count, hA⟩ : ∃ (A : set (↥s × ↥s)), A.countable ∧ (⋃ (i ∈ A), T i) = ⋃ (i : ↥s × ↥s), T i := is_open_Union_countable _ (λ p, is_open_Ioo), have M : ∀ᵐ x ∂μ, x ∉ s \ u, from hfinite.countable.ae_not_mem _, have M' : ∀ᵐ x ∂μ, ∀ (i : ↥s × ↥s) (H : i ∈ A), x ∈ s ∩ T i → p x, { rw ae_ball_iff A_count, rintros ⟨⟨a, as⟩, ⟨b, bs⟩⟩ -, change ∀ᵐ (x : ℝ) ∂μ, x ∈ s ∩ Ioo a b → p x, rcases le_or_lt b a with hba|hab, { simp only [Ioo_eq_empty_of_le hba, inter_empty, is_empty.forall_iff, eventually_true, mem_empty_iff_false], }, { exact h a b as bs hab } }, filter_upwards [M, M'] with x hx h'x, assume xs, by_cases Hx : x ∈ ⋃ (i : ↥s × ↥s), T i, { rw ← hA at Hx, obtain ⟨p, pA, xp⟩ : ∃ (p : ↥s × ↥s), p ∈ A ∧ x ∈ T p, by simpa only [mem_Union, exists_prop, set_coe.exists, exists_and_distrib_right] using Hx, apply h'x p pA ⟨xs, xp⟩ }, { exact false.elim (hx ⟨xs, Hx⟩) } end
af848644592b093ab1a3ececc9e7d1bf39f2793e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/issues5.lean
40af3d8e51ea0ea824018e18f2b31b92df3f4855
[ "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
538
lean
import Init.Data.HashMap def f (a : HashMap Nat Nat) : HashMap Nat Nat := a def t (as : List Nat) := let xs := {}; /- We can't elaborate r.insert at this point because we don't know the type of `r`. Our plan is to suspend it by creating a metavariable, and resume later when we have more information. -/ let ys := as.foldl (fun r a => r.insert a) xs; /- After elaborating `f xs`, we learn that `xs` has type `HashMap Nat Nat`. Then, we have enough information for resuming the elaboration of `r.insert a` -/ let zs := f xs; ys
403d293ddff6d08a1c4a34cad9370c912a025de4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/int/cast.lean
412152f5ae7a5c03ab4378c9c6f9c86a7c8d6515
[ "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
11,038
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.basic import data.nat.cast import tactic.pi_instances import data.sum.basic /-! # Cast of integers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the integers into an additive group with a one (`int.cast`). ## Main declarations * `cast_add_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. -/ open nat variables {F ι α β : Type*} namespace int /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast @[simp, norm_cast] theorem cast_mul [non_assoc_ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n := λ m, int.induction_on' m 0 (by simp) (λ k _ ih n, by simp [add_mul, ih]) (λ k _ ih n, by simp [sub_mul, ih]) @[simp, norm_cast] theorem cast_ite [add_group_with_one α] (P : Prop) [decidable P] (m n : ℤ) : ((ite P m n : ℤ) : α) = ite P m n := apply_ite _ _ _ _ /-- `coe : ℤ → α` as an `add_monoid_hom`. -/ def cast_add_hom (α : Type*) [add_group_with_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩ @[simp] lemma coe_cast_add_hom [add_group_with_one α] : ⇑(cast_add_hom α) = coe := rfl /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [non_assoc_ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [non_assoc_ring α] : ⇑(cast_ring_hom α) = coe := rfl lemma cast_commute [non_assoc_ring α] : ∀ (m : ℤ) (x : α), commute ↑m x | (n : ℕ) x := by simpa using n.cast_commute x | -[1+ n] x := by simpa only [cast_neg_succ_of_nat, commute.neg_left_iff, commute.neg_right_iff] using (n + 1).cast_commute (-x) lemma cast_comm [non_assoc_ring α] (m : ℤ) (x : α) : (m : α) * x = x * m := (cast_commute m x).eq lemma commute_cast [non_assoc_ring α] (x : α) (m : ℤ) : commute x m := (m.cast_commute x).symm theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) := begin intros m n h, rw ← sub_nonneg at h, lift n - m to ℕ using h with k, rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat], exact k.cast_nonneg end @[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one, by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le @[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) := strict_mono_of_le_iff_le $ λ m n, cast_le.symm @[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} : (m : α) < n ↔ m < n := cast_strict_mono.lt_iff_lt @[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] section linear_ordered_ring variables [linear_ordered_ring α] {a b : ℤ} (n : ℤ) @[simp, norm_cast] theorem cast_min : (↑(min a b) : α) = min a b := monotone.map_min cast_mono @[simp, norm_cast] theorem cast_max : (↑(max a b) : α) = max a b := monotone.map_max cast_mono @[simp, norm_cast] theorem cast_abs : ((|a| : ℤ) : α) = |a| := by simp [abs_eq_max_neg] lemma cast_one_le_of_pos (h : 0 < a) : (1 : α) ≤ a := by exact_mod_cast int.add_one_le_of_lt h lemma cast_le_neg_one_of_neg (h : a < 0) : (a : α) ≤ -1 := begin rw [← int.cast_one, ← int.cast_neg, cast_le], exact int.le_sub_one_of_lt h, end lemma nneg_mul_add_sq_of_abs_le_one {x : α} (hx : |x| ≤ 1) : (0 : α) ≤ n * x + n * n := begin have hnx : 0 < n → 0 ≤ x + n := λ hn, by { convert add_le_add (neg_le_of_abs_le hx) (cast_one_le_of_pos hn), rw add_left_neg, }, have hnx' : n < 0 → x + n ≤ 0 := λ hn, by { convert add_le_add (le_of_abs_le hx) (cast_le_neg_one_of_neg hn), rw add_right_neg, }, rw [← mul_add, mul_nonneg_iff], rcases lt_trichotomy n 0 with h | rfl | h, { exact or.inr ⟨by exact_mod_cast h.le, hnx' h⟩, }, { simp [le_total 0 x], }, { exact or.inl ⟨by exact_mod_cast h.le, hnx h⟩, }, end lemma cast_nat_abs : (n.nat_abs : α) = |n| := begin cases n, { simp, }, { simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast], }, end end linear_ordered_ring lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) : (m : α) ∣ (n : α) := ring_hom.map_dvd (int.cast_ring_hom α) h end cast end int namespace prod variables [add_group_with_one α] [add_group_with_one β] instance : add_group_with_one (α × β) := { int_cast := λ n, (n, n), int_cast_of_nat := λ _, by simp; refl, int_cast_neg_succ_of_nat := λ _, by simp; refl, .. prod.add_monoid_with_one, .. prod.add_group } @[simp] lemma fst_int_cast (n : ℤ) : (n : α × β).fst = n := rfl @[simp] lemma snd_int_cast (n : ℤ) : (n : α × β).snd = n := rfl end prod open int namespace add_monoid_hom variables {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g := have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat' _ _ h1, have ∀ n : ℕ, f n = g n := ext_iff.1 this, ext $ λ n, int.cases_on n this $ λ n, eq_on_neg _ _ (this $ n + 1) variables [add_group_with_one A] theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A := ext_int $ by simp [h1] end add_monoid_hom lemma eq_int_cast' [add_group_with_one α] [add_monoid_hom_class F ℤ α] (f : F) (h₁ : f 1 = 1) : ∀ n : ℤ, f n = n := add_monoid_hom.ext_iff.1 $ (f : ℤ →+ α).eq_int_cast_hom h₁ @[simp] lemma int.cast_add_hom_int : int.cast_add_hom ℤ = add_monoid_hom.id ℤ := ((add_monoid_hom.id ℤ).eq_int_cast_hom rfl).symm namespace monoid_hom variables {M : Type*} [monoid M] open multiplicative @[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g := monoid_hom.ext $ add_monoid_hom.ext_iff.mp $ @add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1 /-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : ℤ →* M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) : f = g := begin ext (x | x), { exact (monoid_hom.congr_fun h_nat x : _), }, { rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul], congr' 1, exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), } end end monoid_hom namespace monoid_with_zero_hom variables {M : Type*} [monoid_with_zero M] /-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/ @[ext] lemma ext_int {f g : ℤ →*₀ M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom = g.comp int.of_nat_hom.to_monoid_with_zero_hom) : f = g := to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _) end monoid_with_zero_hom /-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/ lemma ext_int' [monoid_with_zero α] [monoid_with_zero_hom_class F ℤ α] {f g : F} (h_neg_one : f (-1) = g (-1)) (h_pos : ∀ n : ℕ, 0 < n → f n = g n) : f = g := fun_like.ext _ _ $ λ n, by { have := fun_like.congr_fun (@monoid_with_zero_hom.ext_int _ _ (f : ℤ →*₀ α) (g : ℤ →*₀ α) h_neg_one $ monoid_with_zero_hom.ext_nat h_pos) n, exact this } section non_assoc_ring variables [non_assoc_ring α] [non_assoc_ring β] @[simp] lemma eq_int_cast [ring_hom_class F ℤ α] (f : F) (n : ℤ) : f n = n := eq_int_cast' f (map_one _) n @[simp] lemma map_int_cast [ring_hom_class F α β] (f : F) (n : ℤ) : f n = n := eq_int_cast ((f : α →+* β).comp (int.cast_ring_hom α)) n namespace ring_hom lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext $ eq_int_cast f lemma ext_int {R : Type*} [non_assoc_semiring R] (f g : ℤ →+* R) : f = g := coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm instance int.subsingleton_ring_hom {R : Type*} [non_assoc_semiring R] : subsingleton (ℤ →+* R) := ⟨ring_hom.ext_int⟩ end ring_hom end non_assoc_ring @[simp, norm_cast] lemma int.cast_id (n : ℤ) : ↑n = n := (eq_int_cast (ring_hom.id ℤ) _).symm @[simp] lemma int.cast_ring_hom_int : int.cast_ring_hom ℤ = ring_hom.id ℤ := (ring_hom.id ℤ).eq_int_cast'.symm namespace pi variables {π : ι → Type*} [Π i, has_int_cast (π i)] instance : has_int_cast (Π i, π i) := by refine_struct { .. }; tactic.pi_instance_derive_field lemma int_apply (n : ℤ) (i : ι) : (n : Π i, π i) i = n := rfl @[simp] lemma coe_int (n : ℤ) : (n : Π i, π i) = λ _, n := rfl end pi lemma sum.elim_int_cast_int_cast {α β γ : Type*} [has_int_cast γ] (n : ℤ) : sum.elim (n : α → γ) (n : β → γ) = n := @sum.elim_lam_const_lam_const α β γ n namespace pi variables {π : ι → Type*} [Π i, add_group_with_one (π i)] instance : add_group_with_one (Π i, π i) := by refine_struct { .. }; tactic.pi_instance_derive_field end pi namespace mul_opposite variables [add_group_with_one α] @[simp, norm_cast] lemma op_int_cast (z : ℤ) : op (z : α) = z := rfl @[simp, norm_cast] lemma unop_int_cast (n : ℤ) : unop (n : αᵐᵒᵖ) = n := rfl end mul_opposite /-! ### Order dual -/ open order_dual instance [h : has_int_cast α] : has_int_cast αᵒᵈ := h instance [h : add_group_with_one α] : add_group_with_one αᵒᵈ := h instance [h : add_comm_group_with_one α] : add_comm_group_with_one αᵒᵈ := h @[simp] lemma to_dual_int_cast [has_int_cast α] (n : ℤ) : to_dual (n : α) = n := rfl @[simp] lemma of_dual_int_cast [has_int_cast α] (n : ℤ) : (of_dual n : α) = n := rfl /-! ### Lexicographic order -/ instance [h : has_int_cast α] : has_int_cast (lex α) := h instance [h : add_group_with_one α] : add_group_with_one (lex α) := h instance [h : add_comm_group_with_one α] : add_comm_group_with_one (lex α) := h @[simp] lemma to_lex_int_cast [has_int_cast α] (n : ℤ) : to_lex (n : α) = n := rfl @[simp] lemma of_lex_int_cast [has_int_cast α] (n : ℤ) : (of_lex n : α) = n := rfl
e9c3b92c5399e13b08397730046d5a4e9dbf335b
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Parser/Module.lean
bb045607adf6e207fefbb09f6192115464879978
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,740
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Message import Lean.Parser.Command namespace Lean namespace Parser namespace Module def «prelude» := parser! "prelude" def «import» := parser! "import " >> optional "runtime" >> ident def header := parser! optional («prelude» >> ppLine) >> many («import» >> ppLine) >> ppLine /-- Parser for a Lean module. We never actually run this parser but instead use the imperative definitions below that return the same syntax tree structure, but add error recovery. Still, it is helpful to have a `Parser` definition for it in order to auto-generate helpers such as the pretty printer. -/ @[runBuiltinParserAttributeHooks] def module := parser! header >> many (commandParser >> ppLine >> ppLine) def updateTokens (c : ParserContext) : ParserContext := { c with tokens := match addParserTokens c.tokens header.info with | Except.ok tables => tables | Except.error _ => unreachable! } end Module structure ModuleParserState where pos : String.Pos := 0 recovering : Bool := false deriving Inhabited private def mkErrorMessage (c : ParserContext) (pos : String.Pos) (errorMsg : String) : Message := let pos := c.fileMap.toPosition pos { fileName := c.fileName, pos := pos, data := errorMsg } def parseHeader (inputCtx : InputContext) : IO (Syntax × ModuleParserState × MessageLog) := do let dummyEnv ← mkEmptyEnvironment let ctx := mkParserContext inputCtx { env := dummyEnv, options := {} } let ctx := Module.updateTokens ctx let s := mkParserState ctx.input let s := whitespace ctx s let s := Module.header.fn ctx s let stx := s.stxStack.back match s.errorMsg with | some errorMsg => let msg := mkErrorMessage ctx s.pos (toString errorMsg) pure (stx, { pos := s.pos, recovering := true }, { : MessageLog }.add msg) | none => pure (stx, { pos := s.pos }, {}) private def mkEOI (pos : String.Pos) : Syntax := let atom := mkAtom { pos := pos, trailing := "".toSubstring, leading := "".toSubstring } "" Syntax.node `Lean.Parser.Module.eoi #[atom] def isEOI (s : Syntax) : Bool := s.isOfKind `Lean.Parser.Module.eoi def isExitCommand (s : Syntax) : Bool := s.isOfKind `Lean.Parser.Command.exit private def consumeInput (c : ParserContext) (pos : String.Pos) : String.Pos := let s : ParserState := { cache := initCacheForInput c.input, pos := pos } let s := tokenFn c s match s.errorMsg with | some _ => pos + 1 | none => s.pos def topLevelCommandParserFn : ParserFn := orelseFnCore commandParser.fn (andthenFn (lookaheadFn termParser.fn) (errorFn "expected command, but found term; this error may be due to parsing precedence levels, consider parenthesizing the term")) false /- do not merge errors -/ partial def parseCommand (inputCtx : InputContext) (pmctx : ParserModuleContext) (s : ModuleParserState) (messages : MessageLog) : Syntax × ModuleParserState × MessageLog := let rec parse (s : ModuleParserState) (messages : MessageLog) := let { pos := pos, recovering := recovering } := s if inputCtx.input.atEnd pos then (mkEOI pos, s, messages) else let c := mkParserContext inputCtx pmctx let s := { cache := initCacheForInput c.input, pos := pos : ParserState } let s := whitespace c s let s := topLevelCommandParserFn c s let stx := s.stxStack.back match s.errorMsg with | none => (stx, { pos := s.pos }, messages) | some errorMsg => -- advance at least one token to prevent infinite loops let pos := if s.pos == pos then consumeInput c s.pos else s.pos if recovering then parse { pos := pos, recovering := true } messages else let msg := mkErrorMessage c s.pos (toString errorMsg) let messages := messages.add msg -- We should replace the following line with commented one if we want to elaborate commands containing Syntax errors. -- This is useful for implementing features such as autocompletion. -- Right now, it is disabled since `match_syntax` fails on "partial" `Syntax` objects. parse { pos := pos, recovering := true } messages -- (stx, { pos := pos, recovering := true }, messages) parse s messages -- only useful for testing since most Lean files cannot be parsed without elaboration partial def testParseModuleAux (env : Environment) (inputCtx : InputContext) (s : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) : IO (Array Syntax) := let rec parse (state : ModuleParserState) (msgs : MessageLog) (stxs : Array Syntax) := match parseCommand inputCtx { env := env, options := {} } state msgs with | (stx, state, msgs) => if isEOI stx then if msgs.isEmpty then pure stxs else do msgs.forM fun msg => msg.toString >>= IO.println throw (IO.userError "failed to parse file") else parse state msgs (stxs.push stx) parse s msgs stxs def testParseModule (env : Environment) (fname contents : String) : IO Syntax := do let fname ← IO.realPath fname let inputCtx := mkInputContext contents fname let (header, state, messages) ← parseHeader inputCtx let cmds ← testParseModuleAux env inputCtx state messages #[] let stx := Syntax.node `Lean.Parser.Module.module #[header, mkListNode cmds] pure stx.updateLeading def testParseFile (env : Environment) (fname : String) : IO Syntax := do let contents ← IO.FS.readFile fname testParseModule env fname contents end Parser end Lean
481a93e4ebd1d59b5c19e161f41d4f187d6d10f0
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/inner_product_space/adjoint.lean
a080577e7ce11e32a52884766a704fe59b953e11
[ "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
18,787
lean
/- Copyright (c) 2021 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis, Heather Macbeth -/ import analysis.inner_product_space.dual import analysis.inner_product_space.pi_L2 /-! # Adjoint of operators on Hilbert spaces Given an operator `A : E →L[𝕜] F`, where `E` and `F` are Hilbert spaces, its adjoint `adjoint A : F →L[𝕜] E` is the unique operator such that `⟪x, A y⟫ = ⟪adjoint A x, y⟫` for all `x` and `y`. We then use this to put a C⋆-algebra structure on `E →L[𝕜] E` with the adjoint as the star operation. This construction is used to define an adjoint for linear maps (i.e. not continuous) between finite dimensional spaces. ## Main definitions * `continuous_linear_map.adjoint : (E →L[𝕜] F) ≃ₗᵢ⋆[𝕜] (F →L[𝕜] E)`: the adjoint of a continuous linear map, bundled as a conjugate-linear isometric equivalence. * `linear_map.adjoint : (E →ₗ[𝕜] F) ≃ₗ⋆[𝕜] (F →ₗ[𝕜] E)`: the adjoint of a linear map between finite-dimensional spaces, this time only as a conjugate-linear equivalence, since there is no norm defined on these maps. ## Implementation notes * The continuous conjugate-linear version `adjoint_aux` is only an intermediate definition and is not meant to be used outside this file. ## Tags adjoint -/ noncomputable theory open is_R_or_C open_locale complex_conjugate variables {𝕜 E F G : Type*} [is_R_or_C 𝕜] variables [inner_product_space 𝕜 E] [inner_product_space 𝕜 F] [inner_product_space 𝕜 G] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y namespace inner_product_space /-! ### Self-adjoint operators -/ /-- A (not necessarily bounded) operator on an inner product space is self-adjoint, if for all `x`, `y`, we have `⟪T x, y⟫ = ⟪x, T y⟫`. -/ def is_self_adjoint (T : E →ₗ[𝕜] E) : Prop := ∀ x y, ⟪T x, y⟫ = ⟪x, T y⟫ section real variables {E' : Type*} [inner_product_space ℝ E'] -- Todo: Generalize this to `is_R_or_C`. /-- An operator `T` on a `ℝ`-inner product space is self-adjoint if and only if it is `bilin_form.is_self_adjoint` with respect to the bilinear form given by the inner product. -/ lemma is_self_adjoint_iff_bilin_form (T : E' →ₗ[ℝ] E') : is_self_adjoint T ↔ bilin_form_of_real_inner.is_self_adjoint T := by simp [is_self_adjoint, bilin_form.is_self_adjoint, bilin_form.is_adjoint_pair] end real lemma is_self_adjoint.conj_inner_sym {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) (x y : E) : conj ⟪T x, y⟫ = ⟪T y, x⟫ := by rw [hT x y, inner_conj_sym] @[simp] lemma is_self_adjoint.apply_clm {T : E →L[𝕜] E} (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) (x y : E) : ⟪T x, y⟫ = ⟪x, T y⟫ := hT x y /-- The **Hellinger--Toeplitz theorem**: if a symmetric operator is defined everywhere, then it is automatically continuous. -/ lemma is_self_adjoint.continuous [complete_space E] {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) : continuous T := begin -- We prove it by using the closed graph theorem refine T.continuous_of_seq_closed_graph (λ u x y hu hTu, _), rw [←sub_eq_zero, ←inner_self_eq_zero], have hlhs : ∀ k : ℕ, ⟪T (u k) - T x, y - T x⟫ = ⟪u k - x, T (y - T x)⟫ := by { intro k, rw [←T.map_sub, hT] }, refine tendsto_nhds_unique ((hTu.sub_const _).inner tendsto_const_nhds) _, simp_rw hlhs, rw ←@inner_zero_left 𝕜 E _ _ (T (y - T x)), refine filter.tendsto.inner _ tendsto_const_nhds, rw ←sub_self x, exact hu.sub_const _, end /-- The **Hellinger--Toeplitz theorem**: Construct a self-adjoint operator from an everywhere defined symmetric operator.-/ def is_self_adjoint.clm [complete_space E] {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) : E →L[𝕜] E := ⟨T, hT.continuous⟩ lemma is_self_adjoint.clm_apply [complete_space E] {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) {x : E} : hT.clm x = T x := rfl /-- For a self-adjoint operator `T`, the function `λ x, ⟪T x, x⟫` is real-valued. -/ @[simp] lemma is_self_adjoint.coe_re_apply_inner_self_apply {T : E →L[𝕜] E} (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) (x : E) : (T.re_apply_inner_self x : 𝕜) = ⟪T x, x⟫ := begin suffices : ∃ r : ℝ, ⟪T x, x⟫ = r, { obtain ⟨r, hr⟩ := this, simp [hr, T.re_apply_inner_self_apply] }, rw ← eq_conj_iff_real, exact hT.conj_inner_sym x x end /-- If a self-adjoint operator preserves a submodule, its restriction to that submodule is self-adjoint. -/ lemma is_self_adjoint.restrict_invariant {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) {V : submodule 𝕜 E} (hV : ∀ v ∈ V, T v ∈ V) : is_self_adjoint (T.restrict hV) := λ v w, hT v w section complex variables {V : Type*} [inner_product_space ℂ V] /-- A linear operator on a complex inner product space is self-adjoint precisely when `⟪T v, v⟫_ℂ` is real for all v.-/ lemma is_self_adjoint_iff_inner_map_self_real (T : V →ₗ[ℂ] V): is_self_adjoint T ↔ ∀ (v : V), conj ⟪T v, v⟫_ℂ = ⟪T v, v⟫_ℂ := begin split, { intros hT v, apply is_self_adjoint.conj_inner_sym hT }, { intros h x y, nth_rewrite 1 ← inner_conj_sym, nth_rewrite 1 inner_map_polarization, simp only [star_ring_end_apply, star_div', star_sub, star_add, star_mul], simp only [← star_ring_end_apply], rw [h (x + y), h (x - y), h (x + complex.I • y), h (x - complex.I • y)], simp only [complex.conj_I], rw inner_map_polarization', norm_num, ring }, end end complex end inner_product_space /-! ### Adjoint operator -/ open inner_product_space namespace continuous_linear_map variables [complete_space E] [complete_space G] /-- The adjoint, as a continuous conjugate-linear map. This is only meant as an auxiliary definition for the main definition `adjoint`, where this is bundled as a conjugate-linear isometric equivalence. -/ def adjoint_aux : (E →L[𝕜] F) →L⋆[𝕜] (F →L[𝕜] E) := (continuous_linear_map.compSL _ _ _ _ _ ((to_dual 𝕜 E).symm : normed_space.dual 𝕜 E →L⋆[𝕜] E)).comp (to_sesq_form : (E →L[𝕜] F) →L[𝕜] F →L⋆[𝕜] normed_space.dual 𝕜 E) @[simp] lemma adjoint_aux_apply (A : E →L[𝕜] F) (x : F) : adjoint_aux A x = ((to_dual 𝕜 E).symm : (normed_space.dual 𝕜 E) → E) ((to_sesq_form A) x) := rfl lemma adjoint_aux_inner_left (A : E →L[𝕜] F) (x : E) (y : F) : ⟪adjoint_aux A y, x⟫ = ⟪y, A x⟫ := by { simp only [adjoint_aux_apply, to_dual_symm_apply, to_sesq_form_apply_coe, coe_comp', innerSL_apply_coe]} lemma adjoint_aux_inner_right (A : E →L[𝕜] F) (x : E) (y : F) : ⟪x, adjoint_aux A y⟫ = ⟪A x, y⟫ := by rw [←inner_conj_sym, adjoint_aux_inner_left, inner_conj_sym] variables [complete_space F] lemma adjoint_aux_adjoint_aux (A : E →L[𝕜] F) : adjoint_aux (adjoint_aux A) = A := begin ext v, refine ext_inner_left 𝕜 (λ w, _), rw [adjoint_aux_inner_right, adjoint_aux_inner_left], end @[simp] lemma adjoint_aux_norm (A : E →L[𝕜] F) : ∥adjoint_aux A∥ = ∥A∥ := begin refine le_antisymm _ _, { refine continuous_linear_map.op_norm_le_bound _ (norm_nonneg _) (λ x, _), rw [adjoint_aux_apply, linear_isometry_equiv.norm_map], exact to_sesq_form_apply_norm_le }, { nth_rewrite_lhs 0 [←adjoint_aux_adjoint_aux A], refine continuous_linear_map.op_norm_le_bound _ (norm_nonneg _) (λ x, _), rw [adjoint_aux_apply, linear_isometry_equiv.norm_map], exact to_sesq_form_apply_norm_le } end /-- The adjoint of a bounded operator from Hilbert space E to Hilbert space F. -/ def adjoint : (E →L[𝕜] F) ≃ₗᵢ⋆[𝕜] (F →L[𝕜] E) := linear_isometry_equiv.of_surjective { norm_map' := adjoint_aux_norm, ..adjoint_aux } (λ A, ⟨adjoint_aux A, adjoint_aux_adjoint_aux A⟩) localized "postfix `†`:1000 := continuous_linear_map.adjoint" in inner_product /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_left (A : E →L[𝕜] F) (x : E) (y : F) : ⟪A† y, x⟫ = ⟪y, A x⟫ := adjoint_aux_inner_left A x y /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_right (A : E →L[𝕜] F) (x : E) (y : F) : ⟪x, A† y⟫ = ⟪A x, y⟫ := adjoint_aux_inner_right A x y /-- The adjoint is involutive -/ @[simp] lemma adjoint_adjoint (A : E →L[𝕜] F) : A†† = A := adjoint_aux_adjoint_aux A /-- The adjoint of the composition of two operators is the composition of the two adjoints in reverse order. -/ @[simp] lemma adjoint_comp (A : F →L[𝕜] G) (B : E →L[𝕜] F) : (A ∘L B)† = B† ∘L A† := begin ext v, refine ext_inner_left 𝕜 (λ w, _), simp only [adjoint_inner_right, continuous_linear_map.coe_comp', function.comp_app], end lemma apply_norm_sq_eq_inner_adjoint_left (A : E →L[𝕜] E) (x : E) : ∥A x∥^2 = re ⟪(A† * A) x, x⟫ := have h : ⟪(A† * A) x, x⟫ = ⟪A x, A x⟫ := by { rw [←adjoint_inner_left], refl }, by rw [h, ←inner_self_eq_norm_sq _] lemma apply_norm_eq_sqrt_inner_adjoint_left (A : E →L[𝕜] E) (x : E) : ∥A x∥ = real.sqrt (re ⟪(A† * A) x, x⟫) := by rw [←apply_norm_sq_eq_inner_adjoint_left, real.sqrt_sq (norm_nonneg _)] lemma apply_norm_sq_eq_inner_adjoint_right (A : E →L[𝕜] E) (x : E) : ∥A x∥^2 = re ⟪x, (A† * A) x⟫ := have h : ⟪x, (A† * A) x⟫ = ⟪A x, A x⟫ := by { rw [←adjoint_inner_right], refl }, by rw [h, ←inner_self_eq_norm_sq _] lemma apply_norm_eq_sqrt_inner_adjoint_right (A : E →L[𝕜] E) (x : E) : ∥A x∥ = real.sqrt (re ⟪x, (A† * A) x⟫) := by rw [←apply_norm_sq_eq_inner_adjoint_right, real.sqrt_sq (norm_nonneg _)] /-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫` for all `x` and `y`. -/ lemma eq_adjoint_iff (A : E →L[𝕜] F) (B : F →L[𝕜] E) : A = B† ↔ (∀ x y, ⟪A x, y⟫ = ⟪x, B y⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, ext x, exact ext_inner_right 𝕜 (λ y, by simp only [adjoint_inner_left, h x y]) end /-- `E →L[𝕜] E` is a star algebra with the adjoint as the star operation. -/ instance : has_star (E →L[𝕜] E) := ⟨adjoint⟩ instance : has_involutive_star (E →L[𝕜] E) := ⟨adjoint_adjoint⟩ instance : star_semigroup (E →L[𝕜] E) := ⟨adjoint_comp⟩ instance : star_ring (E →L[𝕜] E) := ⟨linear_isometry_equiv.map_add adjoint⟩ instance : star_module 𝕜 (E →L[𝕜] E) := ⟨linear_isometry_equiv.map_smulₛₗ adjoint⟩ lemma star_eq_adjoint (A : E →L[𝕜] E) : star A = A† := rfl instance : cstar_ring (E →L[𝕜] E) := ⟨begin intros A, rw [star_eq_adjoint], refine le_antisymm _ _, { calc ∥A† * A∥ ≤ ∥A†∥ * ∥A∥ : op_norm_comp_le _ _ ... = ∥A∥ * ∥A∥ : by rw [linear_isometry_equiv.norm_map] }, { rw [←sq, ←real.sqrt_le_sqrt_iff (norm_nonneg _), real.sqrt_sq (norm_nonneg _)], refine op_norm_le_bound _ (real.sqrt_nonneg _) (λ x, _), have := calc re ⟪(A† * A) x, x⟫ ≤ ∥(A† * A) x∥ * ∥x∥ : re_inner_le_norm _ _ ... ≤ ∥A† * A∥ * ∥x∥ * ∥x∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _), calc ∥A x∥ = real.sqrt (re ⟪(A† * A) x, x⟫) : by rw [apply_norm_eq_sqrt_inner_adjoint_left] ... ≤ real.sqrt (∥A† * A∥ * ∥x∥ * ∥x∥) : real.sqrt_le_sqrt this ... = real.sqrt (∥A† * A∥) * ∥x∥ : by rw [mul_assoc, real.sqrt_mul (norm_nonneg _), real.sqrt_mul_self (norm_nonneg _)] } end⟩ section real variables {E' : Type*} {F' : Type*} [inner_product_space ℝ E'] [inner_product_space ℝ F'] variables [complete_space E'] [complete_space F'] -- Todo: Generalize this to `is_R_or_C`. lemma is_adjoint_pair_inner (A : E' →L[ℝ] F') : linear_map.is_adjoint_pair (sesq_form_of_inner : E' →ₗ[ℝ] E' →ₗ[ℝ] ℝ) (sesq_form_of_inner : F' →ₗ[ℝ] F' →ₗ[ℝ] ℝ) A (A†) := λ x y, by simp only [sesq_form_of_inner_apply_apply, adjoint_inner_left, to_linear_map_eq_coe, coe_coe] end real end continuous_linear_map namespace linear_map variables [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] [finite_dimensional 𝕜 G] local attribute [instance, priority 20] finite_dimensional.complete /-- The adjoint of an operator from the finite-dimensional inner product space E to the finite- dimensional inner product space F. -/ def adjoint : (E →ₗ[𝕜] F) ≃ₗ⋆[𝕜] (F →ₗ[𝕜] E) := (linear_map.to_continuous_linear_map.trans continuous_linear_map.adjoint.to_linear_equiv).trans linear_map.to_continuous_linear_map.symm lemma adjoint_to_continuous_linear_map (A : E →ₗ[𝕜] F) : A.adjoint.to_continuous_linear_map = A.to_continuous_linear_map.adjoint := rfl lemma adjoint_eq_to_clm_adjoint (A : E →ₗ[𝕜] F) : A.adjoint = A.to_continuous_linear_map.adjoint := rfl /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_left (A : E →ₗ[𝕜] F) (x : E) (y : F) : ⟪adjoint A y, x⟫ = ⟪y, A x⟫ := begin rw [←coe_to_continuous_linear_map A, adjoint_eq_to_clm_adjoint], exact continuous_linear_map.adjoint_inner_left _ x y, end /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_right (A : E →ₗ[𝕜] F) (x : E) (y : F) : ⟪x, adjoint A y⟫ = ⟪A x, y⟫ := begin rw [←coe_to_continuous_linear_map A, adjoint_eq_to_clm_adjoint], exact continuous_linear_map.adjoint_inner_right _ x y, end /-- The adjoint is involutive -/ @[simp] lemma adjoint_adjoint (A : E →ₗ[𝕜] F) : A.adjoint.adjoint = A := begin ext v, refine ext_inner_left 𝕜 (λ w, _), rw [adjoint_inner_right, adjoint_inner_left], end /-- The adjoint of the composition of two operators is the composition of the two adjoints in reverse order. -/ @[simp] lemma adjoint_comp (A : F →ₗ[𝕜] G) (B : E →ₗ[𝕜] F) : (A ∘ₗ B).adjoint = B.adjoint ∘ₗ A.adjoint := begin ext v, refine ext_inner_left 𝕜 (λ w, _), simp only [adjoint_inner_right, linear_map.coe_comp, function.comp_app], end /-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫` for all `x` and `y`. -/ lemma eq_adjoint_iff (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ x y, ⟪A x, y⟫ = ⟪x, B y⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, ext x, exact ext_inner_right 𝕜 (λ y, by simp only [adjoint_inner_left, h x y]) end /-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫` for all basis vectors `x` and `y`. -/ lemma eq_adjoint_iff_basis {ι₁ : Type*} {ι₂ : Type*} (b₁ : basis ι₁ 𝕜 E) (b₂ : basis ι₂ 𝕜 F) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ (i₁ : ι₁) (i₂ : ι₂), ⟪A (b₁ i₁), b₂ i₂⟫ = ⟪b₁ i₁, B (b₂ i₂)⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, refine basis.ext b₁ (λ i₁, _), exact ext_inner_right_basis b₂ (λ i₂, by simp only [adjoint_inner_left, h i₁ i₂]), end lemma eq_adjoint_iff_basis_left {ι : Type*} (b : basis ι 𝕜 E) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ i y, ⟪A (b i), y⟫ = ⟪b i, B y⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, basis.ext b (λ i, _)⟩, exact ext_inner_right 𝕜 (λ y, by simp only [h i, adjoint_inner_left]), end lemma eq_adjoint_iff_basis_right {ι : Type*} (b : basis ι 𝕜 F) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ i x, ⟪A x, b i⟫ = ⟪x, B (b i)⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, ext x, refine ext_inner_right_basis b (λ i, by simp only [h i, adjoint_inner_left]), end lemma is_self_adjoint_iff_eq_adjoint (A : E →ₗ[𝕜] E) : is_self_adjoint A ↔ A = A.adjoint := by rw [is_self_adjoint, ← linear_map.eq_adjoint_iff] /-- `E →ₗ[𝕜] E` is a star algebra with the adjoint as the star operation. -/ instance : has_star (E →ₗ[𝕜] E) := ⟨adjoint⟩ instance : has_involutive_star (E →ₗ[𝕜] E) := ⟨adjoint_adjoint⟩ instance : star_semigroup (E →ₗ[𝕜] E) := ⟨adjoint_comp⟩ instance : star_ring (E →ₗ[𝕜] E) := ⟨linear_equiv.map_add adjoint⟩ instance : star_module 𝕜 (E →ₗ[𝕜] E) := ⟨linear_equiv.map_smulₛₗ adjoint⟩ lemma star_eq_adjoint (A : E →ₗ[𝕜] E) : star A = A.adjoint := rfl section real variables {E' : Type*} {F' : Type*} [inner_product_space ℝ E'] [inner_product_space ℝ F'] variables [finite_dimensional ℝ E'] [finite_dimensional ℝ F'] -- Todo: Generalize this to `is_R_or_C`. lemma is_adjoint_pair_inner (A : E' →ₗ[ℝ] F') : is_adjoint_pair (sesq_form_of_inner : E' →ₗ[ℝ] E' →ₗ[ℝ] ℝ) (sesq_form_of_inner : F' →ₗ[ℝ] F' →ₗ[ℝ] ℝ) A A.adjoint := λ x y, by simp only [sesq_form_of_inner_apply_apply, adjoint_inner_left] end real /-- The Gram operator T†T is self-adjoint. -/ lemma is_self_adjoint_adjoint_mul_self (T : E →ₗ[𝕜] E) : is_self_adjoint (T.adjoint * T) := λ x y, by simp only [linear_map.mul_apply, linear_map.adjoint_inner_left, linear_map.adjoint_inner_right] /-- The Gram operator T†T is a positive operator. -/ lemma re_inner_adjoint_mul_self_nonneg (T : E →ₗ[𝕜] E) (x : E) : 0 ≤ re ⟪ x, (T.adjoint * T) x ⟫ := by {simp only [linear_map.mul_apply, linear_map.adjoint_inner_right, inner_self_eq_norm_sq_to_K], norm_cast, exact sq_nonneg _} @[simp] lemma im_inner_adjoint_mul_self_eq_zero (T : E →ₗ[𝕜] E) (x : E) : im ⟪ x, linear_map.adjoint T (T x) ⟫ = 0 := by {simp only [linear_map.mul_apply, linear_map.adjoint_inner_right, inner_self_eq_norm_sq_to_K], norm_cast} end linear_map namespace matrix variables {m n : Type*} [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] open_locale complex_conjugate /-- The adjoint of the linear map associated to a matrix is the linear map associated to the conjugate transpose of that matrix. -/ lemma conj_transpose_eq_adjoint (A : matrix m n 𝕜) : to_lin' A.conj_transpose = @linear_map.adjoint _ (euclidean_space 𝕜 n) (euclidean_space 𝕜 m) _ _ _ _ _ (to_lin' A) := begin rw @linear_map.eq_adjoint_iff _ (euclidean_space 𝕜 m) (euclidean_space 𝕜 n), intros x y, convert dot_product_assoc (conj ∘ (id x : m → 𝕜)) y A using 1, simp [dot_product, mul_vec, ring_hom.map_sum, ← star_ring_end_apply, mul_comm], end end matrix
7b6da589bef46d1865545132dbac650431a52a38
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/data/nat/sub.lean
459f422cce2672512c221e4659f024c71b1bbacf
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,658
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad Module: data.nat.sub Subtraction on the natural numbers, as well as min, max, and distance. -/ import .order import tools.fake_simplifier open eq.ops open fake_simplifier namespace nat /- subtraction -/ theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl theorem zero_sub (n : ℕ) : 0 - n = 0 := nat.induction_on n !sub_zero (take k : nat, assume IH : 0 - k = 0, calc 0 - succ k = pred (0 - k) : sub_succ ... = pred 0 : IH ... = 0 : pred_zero) theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m theorem sub_self (n : ℕ) : n - n = 0 := nat.induction_on n !sub_zero (take k IH, !succ_sub_succ ⬝ IH) theorem add_sub_add_right (n k m : ℕ) : (n + k) - (m + k) = n - m := nat.induction_on k (calc (n + 0) - (m + 0) = n - (m + 0) : {!add_zero} ... = n - m : {!add_zero}) (take l : nat, assume IH : (n + l) - (m + l) = n - m, calc (n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {!add_succ} ... = succ (n + l) - succ (m + l) : {!add_succ} ... = (n + l) - (m + l) : !succ_sub_succ ... = n - m : IH) theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := !add.comm ▸ !add.comm ▸ !add_sub_add_right theorem add_sub_cancel (n m : ℕ) : n + m - m = n := nat.induction_on m (!add_zero⁻¹ ▸ !sub_zero) (take k : ℕ, assume IH : n + k - k = n, calc n + succ k - succ k = succ (n + k) - succ k : add_succ ... = n + k - k : succ_sub_succ ... = n : IH) theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := !add.comm ▸ !add_sub_cancel theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k) := nat.induction_on k (calc n - m - 0 = n - m : sub_zero ... = n - (m + 0) : add_zero) (take l : nat, assume IH : n - m - l = n - (m + l), calc n - m - succ l = pred (n - m - l) : !sub_succ ... = pred (n - (m + l)) : IH ... = n - succ (m + l) : sub_succ ... = n - (m + succ l) : {!add_succ⁻¹}) theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := calc succ n - m - succ k = succ n - (m + succ k) : sub_sub ... = succ n - succ (m + k) : add_succ ... = n - (m + k) : succ_sub_succ ... = n - m - k : sub_sub theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := calc n - (n + m) = n - n - m : sub_sub ... = 0 - m : sub_self ... = 0 : zero_sub theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := calc m - n - k = m - (n + k) : !sub_sub ... = m - (k + n) : {!add.comm} ... = m - k - n : !sub_sub⁻¹ theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl /- interaction with multiplication -/ theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m := nat.induction_on n (calc pred 0 * m = 0 * m : pred_zero ... = 0 : zero_mul ... = 0 - m : zero_sub ... = 0 * m - m : zero_mul) (take k : nat, assume IH : pred k * m = k * m - m, calc pred (succ k) * m = k * m : pred_succ ... = k * m + m - m : add_sub_cancel ... = succ k * m - m : succ_mul) theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := calc n * pred m = pred m * n : mul.comm ... = m * n - n : mul_pred_left ... = n * m - n : mul.comm theorem mul_sub_right_distrib (n m k : ℕ) : (n - m) * k = n * k - m * k := nat.induction_on m (calc (n - 0) * k = n * k : sub_zero ... = n * k - 0 : sub_zero ... = n * k - 0 * k : zero_mul) (take l : nat, assume IH : (n - l) * k = n * k - l * k, calc (n - succ l) * k = pred (n - l) * k : sub_succ ... = (n - l) * k - k : mul_pred_left ... = n * k - l * k - k : IH ... = n * k - (l * k + k) : sub_sub ... = n * k - (succ l * k) : succ_mul) theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := calc n * (m - k) = (m - k) * n : !mul.comm ... = m * n - k * n : !mul_sub_right_distrib ... = n * m - k * n : {!mul.comm} ... = n * m - n * k : {!mul.comm} /- interaction with inequalities -/ theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n) := sub_induction n m (take k, assume H : 0 ≤ k, rfl) (take k, assume H : succ k ≤ 0, absurd H !not_succ_le_zero) (take k l, assume IH : k ≤ l → succ l - k = succ (l - k), take H : succ k ≤ succ l, calc succ (succ l) - succ k = succ l - k : succ_sub_succ ... = succ (l - k) : IH (le_of_succ_le_succ H) ... = succ (succ l - succ k) : succ_sub_succ) theorem sub_eq_zero_of_le {n m : ℕ} (H : n ≤ m) : n - m = 0 := obtain (k : ℕ) (Hk : n + k = m), from le.elim H, Hk ▸ !sub_self_add theorem add_sub_of_le {n m : ℕ} : n ≤ m → n + (m - n) = m := sub_induction n m (take k, assume H : 0 ≤ k, calc 0 + (k - 0) = k - 0 : zero_add ... = k : sub_zero) (take k, assume H : succ k ≤ 0, absurd H !not_succ_le_zero) (take k l, assume IH : k ≤ l → k + (l - k) = l, take H : succ k ≤ succ l, calc succ k + (succ l - succ k) = succ k + (l - k) : succ_sub_succ ... = succ (k + (l - k)) : add.succ_left ... = succ l : IH (le_of_succ_le_succ H)) theorem add_sub_of_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := calc n + (m - n) = n + 0 : sub_eq_zero_of_le H ... = n : add_zero theorem sub_add_cancel {n m : ℕ} : n ≥ m → n - m + m = n := !add.comm ▸ !add_sub_of_le theorem sub_add_of_le {n m : ℕ} : n ≤ m → n - m + m = m := !add.comm ▸ add_sub_of_ge theorem sub.cases {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k) : P (n - m) := or.elim !le.total (assume H3 : n ≤ m, (sub_eq_zero_of_le H3)⁻¹ ▸ (H1 H3)) (assume H3 : m ≤ n, H2 (n - m) (add_sub_of_le H3)) theorem exists_sub_eq_of_le {n m : ℕ} (H : n ≤ m) : ∃k, m - k = n := obtain (k : ℕ) (Hk : n + k = m), from le.elim H, exists.intro k (calc m - k = n + k - k : Hk⁻¹ ... = n : add_sub_cancel) theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := have l1 : k ≤ m → n + m - k = n + (m - k), from sub_induction k m (take m : ℕ, assume H : 0 ≤ m, calc n + m - 0 = n + m : sub_zero ... = n + (m - 0) : sub_zero) (take k : ℕ, assume H : succ k ≤ 0, absurd H !not_succ_le_zero) (take k m, assume IH : k ≤ m → n + m - k = n + (m - k), take H : succ k ≤ succ m, calc n + succ m - succ k = succ (n + m) - succ k : add_succ ... = n + m - k : succ_sub_succ ... = n + (m - k) : IH (le_of_succ_le_succ H) ... = n + (succ m - succ k) : succ_sub_succ), l1 H theorem le_of_sub_eq_zero {n m : ℕ} : n - m = 0 → n ≤ m := sub.cases (assume H1 : n ≤ m, assume H2 : 0 = 0, H1) (take k : ℕ, assume H1 : m + k = n, assume H2 : k = 0, have H3 : n = m, from !add_zero ▸ H2 ▸ H1⁻¹, H3 ▸ !le.refl) theorem sub_sub.cases {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0) (H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n) := or.elim !le.total (assume H3 : n ≤ m, (sub_eq_zero_of_le H3)⁻¹ ▸ (H2 (m - n) (add_sub_of_le H3)⁻¹)) (assume H3 : m ≤ n, (sub_eq_zero_of_le H3)⁻¹ ▸ (H1 (n - m) (add_sub_of_le H3)⁻¹)) theorem sub_eq_of_add_eq {n m k : ℕ} (H : n + m = k) : k - n = m := have H2 : k - n + n = m + n, from calc k - n + n = k : sub_add_cancel (le.intro H) ... = n + m : H⁻¹ ... = m + n : !add.comm, add.cancel_right H2 theorem sub_le_sub_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n - k ≤ m - k := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, or.elim !le.total (assume H2 : n ≤ k, (sub_eq_zero_of_le H2)⁻¹ ▸ !zero_le) (assume H2 : k ≤ n, have H3 : n - k + l = m - k, from calc n - k + l = l + (n - k) : add.comm ... = l + n - k : add_sub_assoc H2 l ... = n + l - k : add.comm ... = m - k : Hl, le.intro H3) theorem sub_le_sub_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k - m ≤ k - n := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, sub.cases (assume H2 : k ≤ m, !zero_le) (take m' : ℕ, assume Hm : m + m' = k, have H3 : n ≤ k, from le.trans H (le.intro Hm), have H4 : m' + l + n = k - n + n, from calc m' + l + n = n + (m' + l) : add.comm ... = n + (l + m') : add.comm ... = n + l + m' : add.assoc ... = m + m' : Hl ... = k : Hm ... = k - n + n : sub_add_cancel H3, le.intro (add.cancel_right H4)) theorem sub_pos_of_lt {m n : ℕ} (H : m < n) : n - m > 0 := have H1 : n = n - m + m, from (sub_add_cancel (le_of_lt H))⁻¹, have H2 : 0 + m < n - m + m, from (zero_add m)⁻¹ ▸ H1 ▸ H, !lt_of_add_lt_add_right H2 theorem lt_of_sub_pos {m n : ℕ} (H : n - m > 0) : m < n := lt_of_not_le (take H1 : m ≥ n, have H2 : n - m = 0, from sub_eq_zero_of_le H1, !lt.irrefl (H2 ▸ H)) theorem lt_of_sub_lt_sub_right {n m k : ℕ} (H : n - k < m - k) : n < m := lt_of_not_le (assume H1 : m ≤ n, have H2 : m - k ≤ n - k, from sub_le_sub_right H1 _, not_le_of_lt H H2) theorem lt_of_sub_lt_sub_left {n m k : ℕ} (H : n - m < n - k) : k < m := lt_of_not_le (assume H1 : m ≤ k, have H2 : n - k ≤ n - m, from sub_le_sub_left H1 _, not_le_of_lt H H2) theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := sub.cases (assume H : n ≤ m, !zero_add⁻¹ ▸ sub_le_sub_right H k) (take mn : ℕ, assume Hmn : m + mn = n, sub.cases (assume H : m ≤ k, have H2 : n - k ≤ n - m, from sub_le_sub_left H n, have H3 : n - k ≤ mn, from sub_eq_of_add_eq Hmn ▸ H2, show n - k ≤ mn + 0, from !add_zero⁻¹ ▸ H3) (take km : ℕ, assume Hkm : k + km = m, have H : k + (mn + km) = n, from calc k + (mn + km) = k + (km + mn): add.comm ... = k + km + mn : add.assoc ... = m + mn : Hkm ... = n : Hmn, have H2 : n - k = mn + km, from sub_eq_of_add_eq H, H2 ▸ !le.refl)) theorem sub_lt_self {m n : ℕ} (H1 : m > 0) (H2 : n > 0) : m - n < m := calc m - n = succ (pred m) - n : succ_pred_of_pos H1 ... = succ (pred m) - succ (pred n) : succ_pred_of_pos H2 ... = pred m - pred n : succ_sub_succ ... ≤ pred m : sub_le ... < succ (pred m) : lt_succ_self ... = m : succ_pred_of_pos H1 theorem le_sub_of_add_le {m n k : ℕ} (H : m + k ≤ n) : m ≤ n - k := calc m = m + k - k : add_sub_cancel ... ≤ n - k : sub_le_sub_right H k theorem lt_sub_of_add_lt {m n k : ℕ} (H : m + k < n) (H2 : k ≤ n) : m < n - k := lt_of_succ_le (le_sub_of_add_le (calc succ m + k = succ (m + k) : succ_add_eq_succ_add ... ≤ n : succ_le_of_lt H)) /- distance -/ definition dist [reducible] (n m : ℕ) := (n - m) + (m - n) theorem dist.comm (n m : ℕ) : dist n m = dist m n := !add.comm theorem dist_self (n : ℕ) : dist n n = 0 := calc (n - n) + (n - n) = 0 + (n - n) : sub_self ... = 0 + 0 : sub_self ... = 0 : rfl theorem eq_of_dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m := have H2 : n - m = 0, from eq_zero_of_add_eq_zero_right H, have H3 : n ≤ m, from le_of_sub_eq_zero H2, have H4 : m - n = 0, from eq_zero_of_add_eq_zero_left H, have H5 : m ≤ n, from le_of_sub_eq_zero H4, le.antisymm H3 H5 theorem dist_eq_sub_of_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n := calc dist n m = 0 + (m - n) : {sub_eq_zero_of_le H} ... = m - n : zero_add theorem dist_eq_sub_of_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m := !dist.comm ▸ dist_eq_sub_of_le H theorem dist_zero_right (n : ℕ) : dist n 0 = n := dist_eq_sub_of_ge !zero_le ⬝ !sub_zero theorem dist_zero_left (n : ℕ) : dist 0 n = n := dist_eq_sub_of_le !zero_le ⬝ !sub_zero theorem dist.intro {n m k : ℕ} (H : n + m = k) : dist k n = m := calc dist k n = k - n : dist_eq_sub_of_ge (le.intro H) ... = m : sub_eq_of_add_eq H theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : add_sub_add_right ... = (n - m) + (m - n) : add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := !add.comm ▸ !add.comm ▸ !dist_add_add_right theorem dist_add_eq_of_ge {n m : ℕ} (H : n ≥ m) : dist n m + m = n := calc dist n m + m = n - m + m : {dist_eq_sub_of_ge H} ... = n : sub_add_cancel H theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : dist_add_add_right ... = dist (k + l) (k + m) : H ... = dist l m : dist_add_add_left theorem dist_sub_eq_dist_add_left {n m : ℕ} (H : n ≥ m) (k : ℕ) : dist (n - m) k = dist n (k + m) := have H2 : n - m + (k + m) = k + n, from calc n - m + (k + m) = n - m + (m + k) : add.comm ... = n - m + m + k : add.assoc ... = n + k : sub_add_cancel H ... = k + n : add.comm, dist_eq_intro H2 theorem dist_sub_eq_dist_add_right {k m : ℕ} (H : k ≥ m) (n : ℕ) : dist n (k - m) = dist (n + m) k := (dist_sub_eq_dist_add_left H n ▸ !dist.comm) ▸ !dist.comm theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have H : (n - m) + (m - k) + ((k - m) + (m - n)) = (n - m) + (m - n) + ((m - k) + (k - m)), by simp, H ▸ add_le_add !sub_lt_sub_add_sub !sub_lt_sub_add_sub theorem dist_add_add_le_add_dist_dist (n m k l : ℕ) : dist (n + m) (k + l) ≤ dist n k + dist m l := have H : dist (n + m) (k + m) + dist (k + m) (k + l) = dist n k + dist m l, from !dist_add_add_left ▸ !dist_add_add_right ▸ rfl, H ▸ !dist.triangle_inequality theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := have H : ∀n m, dist n m = n - m + (m - n), from take n m, rfl, by simp theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := have H : ∀n m, dist n m = n - m + (m - n), from take n m, rfl, by simp theorem dist_mul_dist (n m k l : ℕ) : dist n m * dist k l = dist (n * k + m * l) (n * l + m * k) := have aux : ∀k l, k ≥ l → dist n m * dist k l = dist (n * k + m * l) (n * l + m * k), from take k l : ℕ, assume H : k ≥ l, have H2 : m * k ≥ m * l, from mul_le_mul_left H m, have H3 : n * l + m * k ≥ m * l, from le.trans H2 !le_add_left, calc dist n m * dist k l = dist n m * (k - l) : dist_eq_sub_of_ge H ... = dist (n * (k - l)) (m * (k - l)) : dist_mul_right ... = dist (n * k - n * l) (m * k - m * l) : by simp ... = dist (n * k) (m * k - m * l + n * l) : dist_sub_eq_dist_add_left (mul_le_mul_left H n) ... = dist (n * k) (n * l + (m * k - m * l)) : add.comm ... = dist (n * k) (n * l + m * k - m * l) : add_sub_assoc H2 (n * l) ... = dist (n * k + m * l) (n * l + m * k) : dist_sub_eq_dist_add_right H3 _, or.elim !le.total (assume H : k ≤ l, !dist.comm ▸ !dist.comm ▸ aux l k H) (assume H : l ≤ k, aux k l H) end nat
64df7947baab939aea75d0bec5b11cb308be0bfa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/density.lean
c2bf0bcb2b140ce47c362fca7476367cd46e347a
[ "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
19,281
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.radon_nikodym import measure_theory.measure.haar.of_basis /-! # Probability density function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the probability density function of random variables, by which we mean measurable functions taking values in a Borel space. In particular, a measurable function `f` is said to the probability density function of a random variable `X` if for all measurable sets `S`, `ℙ(X ∈ S) = ∫ x in S, f x dx`. Probability density functions are one way of describing the distribution of a random variable, and are useful for calculating probabilities and finding moments (although the latter is better achieved with moment generating functions). This file also defines the continuous uniform distribution and proves some properties about random variables with this distribution. ## Main definitions * `measure_theory.has_pdf` : A random variable `X : Ω → E` is said to `has_pdf` with respect to the measure `ℙ` on `Ω` and `μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. * `measure_theory.pdf` : If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. * `measure_theory.pdf.uniform` : A random variable `X` is said to follow the uniform distribution if it has a constant probability density function with a compact, non-null support. ## Main results * `measure_theory.pdf.integral_fun_mul_eq_integral` : Law of the unconscious statistician, i.e. if a random variable `X : Ω → E` has pdf `f`, then `𝔼(g(X)) = ∫ x, g x * f x dx` for all measurable `g : E → ℝ`. * `measure_theory.pdf.integral_mul_eq_integral` : A real-valued random variable `X` with pdf `f` has expectation `∫ x, x * f x dx`. * `measure_theory.pdf.uniform.integral_eq` : If `X` follows the uniform distribution with its pdf having support `s`, then `X` has expectation `(λ s)⁻¹ * ∫ x in s, x dx` where `λ` is the Lebesgue measure. ## TODOs Ultimately, we would also like to define characteristic functions to describe distributions as it exists for all random variables. However, to define this, we will need Fourier transforms which we currently do not have. -/ noncomputable theory open_locale classical measure_theory nnreal ennreal namespace measure_theory open topological_space measure_theory.measure variables {Ω E : Type*} [measurable_space E] /-- A random variable `X : Ω → E` is said to `has_pdf` with respect to the measure `ℙ` on `Ω` and `μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/ class has_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) : Prop := (pdf' : measurable X ∧ ∃ (f : E → ℝ≥0∞), measurable f ∧ map X ℙ = μ.with_density f) @[measurability] lemma has_pdf.measurable {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] : measurable X := hX.pdf'.1 /-- If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/ def pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) := if hX : has_pdf X ℙ μ then classical.some hX.pdf'.2 else 0 lemma pdf_undef {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E} (h : ¬ has_pdf X ℙ μ) : pdf X ℙ μ = 0 := by simp only [pdf, dif_neg h] lemma has_pdf_of_pdf_ne_zero {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E} (h : pdf X ℙ μ ≠ 0) : has_pdf X ℙ μ := begin by_contra hpdf, rw [pdf, dif_neg hpdf] at h, exact hpdf (false.rec (has_pdf X ℙ μ) (h rfl)) end lemma pdf_eq_zero_of_not_measurable {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} {X : Ω → E} (hX : ¬ measurable X) : pdf X ℙ μ = 0 := pdf_undef (λ hpdf, hX hpdf.pdf'.1) lemma measurable_of_pdf_ne_zero {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} (X : Ω → E) (h : pdf X ℙ μ ≠ 0) : measurable X := by { by_contra hX, exact h (pdf_eq_zero_of_not_measurable hX) } @[measurability] lemma measurable_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) : measurable (pdf X ℙ μ) := begin by_cases hX : has_pdf X ℙ μ, { rw [pdf, dif_pos hX], exact (classical.some_spec hX.pdf'.2).1 }, { rw [pdf, dif_neg hX], exact measurable_zero } end lemma map_eq_with_density_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] : measure.map X ℙ = μ.with_density (pdf X ℙ μ) := begin rw [pdf, dif_pos hX], exact (classical.some_spec hX.pdf'.2).2 end lemma map_eq_set_lintegral_pdf {m : measurable_space Ω} (X : Ω → E) (ℙ : measure Ω) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] {s : set E} (hs : measurable_set s) : measure.map X ℙ s = ∫⁻ x in s, pdf X ℙ μ x ∂μ := by rw [← with_density_apply _ hs, map_eq_with_density_pdf X ℙ μ] namespace pdf variables {m : measurable_space Ω} {ℙ : measure Ω} {μ : measure E} lemma lintegral_eq_measure_univ {X : Ω → E} [has_pdf X ℙ μ] : ∫⁻ x, pdf X ℙ μ x ∂μ = ℙ set.univ := begin rw [← set_lintegral_univ, ← map_eq_set_lintegral_pdf X ℙ μ measurable_set.univ, measure.map_apply (has_pdf.measurable X ℙ μ) measurable_set.univ, set.preimage_univ], end lemma ae_lt_top [is_finite_measure ℙ] {μ : measure E} {X : Ω → E} : ∀ᵐ x ∂μ, pdf X ℙ μ x < ∞ := begin by_cases hpdf : has_pdf X ℙ μ, { haveI := hpdf, refine ae_lt_top (measurable_pdf X ℙ μ) _, rw lintegral_eq_measure_univ, exact (measure_lt_top _ _).ne }, { rw [pdf, dif_neg hpdf], exact filter.eventually_of_forall (λ x, with_top.zero_lt_top) } end lemma of_real_to_real_ae_eq [is_finite_measure ℙ] {X : Ω → E} : (λ x, ennreal.of_real (pdf X ℙ μ x).to_real) =ᵐ[μ] pdf X ℙ μ := of_real_to_real_ae_eq ae_lt_top lemma integrable_iff_integrable_mul_pdf [is_finite_measure ℙ] {X : Ω → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) : integrable (λ x, f (X x)) ℙ ↔ integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ := begin rw [← integrable_map_measure hf.ae_strongly_measurable (has_pdf.measurable X ℙ μ).ae_measurable, map_eq_with_density_pdf X ℙ μ, integrable_with_density_iff (measurable_pdf _ _ _) ae_lt_top], apply_instance end /-- **The Law of the Unconscious Statistician**: Given a random variable `X` and a measurable function `f`, `f ∘ X` is a random variable with expectation `∫ x, f x * pdf X ∂μ` where `μ` is a measure on the codomain of `X`. -/ lemma integral_fun_mul_eq_integral [is_finite_measure ℙ] {X : Ω → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) : ∫ x, f x * (pdf X ℙ μ x).to_real ∂μ = ∫ x, f (X x) ∂ℙ := begin by_cases hpdf : integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ, { rw [← integral_map (has_pdf.measurable X ℙ μ).ae_measurable hf.ae_strongly_measurable, map_eq_with_density_pdf X ℙ μ, integral_eq_lintegral_pos_part_sub_lintegral_neg_part hpdf, integral_eq_lintegral_pos_part_sub_lintegral_neg_part, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.neg.ennreal_of_real, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.ennreal_of_real], { congr' 2, { have : ∀ x, ennreal.of_real (f x * (pdf X ℙ μ x).to_real) = ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (f x), { intro x, rw [mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] }, simp_rw [this], exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) }, { have : ∀ x, ennreal.of_real (- (f x * (pdf X ℙ μ x).to_real)) = ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (-f x), { intro x, rw [neg_mul_eq_neg_mul, mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] }, simp_rw [this], exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) } }, { refine ⟨hf.ae_strongly_measurable, _⟩, rw [has_finite_integral, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf _ _ _) hf.nnnorm.coe_nnreal_ennreal], have : (λ x, (pdf X ℙ μ * λ x, ↑‖f x‖₊) x) =ᵐ[μ] (λ x, ‖f x * (pdf X ℙ μ x).to_real‖₊), { simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul], rw [smul_eq_mul, mul_comm], refine filter.eventually_eq.mul (ae_eq_refl _) (ae_eq_trans of_real_to_real_ae_eq.symm _), convert ae_eq_refl _, ext1 x, exact real.ennnorm_eq_of_real ennreal.to_real_nonneg }, rw lintegral_congr_ae this, exact hpdf.2 } }, { rw [integral_undef hpdf, integral_undef], rwa ← integrable_iff_integrable_mul_pdf hf at hpdf, all_goals { apply_instance } } end lemma map_absolutely_continuous {X : Ω → E} [has_pdf X ℙ μ] : map X ℙ ≪ μ := by { rw map_eq_with_density_pdf X ℙ μ, exact with_density_absolutely_continuous _ _, } /-- A random variable that `has_pdf` is quasi-measure preserving. -/ lemma to_quasi_measure_preserving {X : Ω → E} [has_pdf X ℙ μ] : quasi_measure_preserving X ℙ μ := { measurable := has_pdf.measurable X ℙ μ, absolutely_continuous := map_absolutely_continuous, } lemma have_lebesgue_decomposition_of_has_pdf {X : Ω → E} [hX' : has_pdf X ℙ μ] : (map X ℙ).have_lebesgue_decomposition μ := ⟨⟨⟨0, pdf X ℙ μ⟩, by simp only [zero_add, measurable_pdf X ℙ μ, true_and, mutually_singular.zero_left, map_eq_with_density_pdf X ℙ μ] ⟩⟩ lemma has_pdf_iff {X : Ω → E} : has_pdf X ℙ μ ↔ measurable X ∧ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ := begin split, { intro hX', exactI ⟨hX'.pdf'.1, have_lebesgue_decomposition_of_has_pdf, map_absolutely_continuous⟩ }, { rintros ⟨hX, h_decomp, h⟩, haveI := h_decomp, refine ⟨⟨hX, (measure.map X ℙ).rn_deriv μ, measurable_rn_deriv _ _, _⟩⟩, rwa with_density_rn_deriv_eq } end lemma has_pdf_iff_of_measurable {X : Ω → E} (hX : measurable X) : has_pdf X ℙ μ ↔ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ := by { rw has_pdf_iff, simp only [hX, true_and], } section variables {F : Type*} [measurable_space F] {ν : measure F} /-- A random variable that `has_pdf` transformed under a `quasi_measure_preserving` map also `has_pdf` if `(map g (map X ℙ)).have_lebesgue_decomposition μ`. `quasi_measure_preserving_has_pdf'` is more useful in the case we are working with a probability measure and a real-valued random variable. -/ lemma quasi_measure_preserving_has_pdf {X : Ω → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) (hmap : (map g (map X ℙ)).have_lebesgue_decomposition ν) : has_pdf (g ∘ X) ℙ ν := begin rw [has_pdf_iff, ← map_map hg.measurable (has_pdf.measurable X ℙ μ)], refine ⟨hg.measurable.comp (has_pdf.measurable X ℙ μ), hmap, _⟩, rw [map_eq_with_density_pdf X ℙ μ], refine absolutely_continuous.mk (λ s hsm hs, _), rw [map_apply hg.measurable hsm, with_density_apply _ (hg.measurable hsm)], have := hg.absolutely_continuous hs, rw map_apply hg.measurable hsm at this, exact set_lintegral_measure_zero _ _ this, end lemma quasi_measure_preserving_has_pdf' [is_finite_measure ℙ] [sigma_finite ν] {X : Ω → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) : has_pdf (g ∘ X) ℙ ν := quasi_measure_preserving_has_pdf hg infer_instance end section real variables [is_finite_measure ℙ] {X : Ω → ℝ} /-- A real-valued random variable `X` `has_pdf X ℙ λ` (where `λ` is the Lebesgue measure) if and only if the push-forward measure of `ℙ` along `X` is absolutely continuous with respect to `λ`. -/ lemma real.has_pdf_iff_of_measurable (hX : measurable X) : has_pdf X ℙ ↔ map X ℙ ≪ volume := begin rw [has_pdf_iff_of_measurable hX, and_iff_right_iff_imp], exact λ h, infer_instance, end lemma real.has_pdf_iff : has_pdf X ℙ ↔ measurable X ∧ map X ℙ ≪ volume := begin by_cases hX : measurable X, { rw [real.has_pdf_iff_of_measurable hX, iff_and_self], exact λ h, hX, apply_instance }, { exact ⟨λ h, false.elim (hX h.pdf'.1), λ h, false.elim (hX h.1)⟩, } end /-- If `X` is a real-valued random variable that has pdf `f`, then the expectation of `X` equals `∫ x, x * f x ∂λ` where `λ` is the Lebesgue measure. -/ lemma integral_mul_eq_integral [has_pdf X ℙ] : ∫ x, x * (pdf X ℙ volume x).to_real = ∫ x, X x ∂ℙ := integral_fun_mul_eq_integral measurable_id lemma has_finite_integral_mul {f : ℝ → ℝ} {g : ℝ → ℝ≥0∞} (hg : pdf X ℙ =ᵐ[volume] g) (hgi : ∫⁻ x, ‖f x‖₊ * g x ≠ ∞) : has_finite_integral (λ x, f x * (pdf X ℙ volume x).to_real) := begin rw has_finite_integral, have : (λ x, ↑‖f x‖₊ * g x) =ᵐ[volume] (λ x, ‖f x * (pdf X ℙ volume x).to_real‖₊), { refine ae_eq_trans (filter.eventually_eq.mul (ae_eq_refl (λ x, ‖f x‖₊)) (ae_eq_trans hg.symm of_real_to_real_ae_eq.symm)) _, simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul, smul_eq_mul], refine filter.eventually_eq.mul (ae_eq_refl _) _, convert ae_eq_refl _, ext1 x, exact real.ennnorm_eq_of_real ennreal.to_real_nonneg }, rwa [lt_top_iff_ne_top, ← lintegral_congr_ae this], end end real section /-! **Uniform Distribution** -/ /-- A random variable `X` has uniform distribution if it has a probability density function `f` with support `s` such that `f = (μ s)⁻¹ 1ₛ` a.e. where `1ₛ` is the indicator function for `s`. -/ def is_uniform {m : measurable_space Ω} (X : Ω → E) (support : set E) (ℙ : measure Ω) (μ : measure E . volume_tac) := pdf X ℙ μ =ᵐ[μ] support.indicator ((μ support)⁻¹ • 1) namespace is_uniform lemma has_pdf {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hu : is_uniform X s ℙ μ) : has_pdf X ℙ μ := has_pdf_of_pdf_ne_zero begin intro hpdf, rw [is_uniform, hpdf] at hu, suffices : μ (s ∩ function.support ((μ s)⁻¹ • 1)) = 0, { have heq : function.support ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) = set.univ, { ext x, rw [function.mem_support], simp [hnt] }, rw [heq, set.inter_univ] at this, exact hns this }, exact set.indicator_ae_eq_zero.1 hu.symm, end lemma pdf_to_real_ae_eq {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hX : is_uniform X s ℙ μ) : (λ x, (pdf X ℙ μ x).to_real) =ᵐ[μ] (λ x, (s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x).to_real) := filter.eventually_eq.fun_comp hX ennreal.to_real lemma measure_preimage {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : measurable_set s) (hu : is_uniform X s ℙ μ) {A : set E} (hA : measurable_set A) : ℙ (X ⁻¹' A) = μ (s ∩ A) / μ s := begin haveI := hu.has_pdf hns hnt, rw [←measure.map_apply (has_pdf.measurable X ℙ μ) hA, map_eq_set_lintegral_pdf X ℙ μ hA, lintegral_congr_ae hu.restrict], simp only [hms, hA, lintegral_indicator, pi.smul_apply, pi.one_apply, algebra.id.smul_eq_mul, mul_one, lintegral_const, restrict_apply', set.univ_inter], rw ennreal.div_eq_inv_mul, end lemma is_probability_measure {m : measurable_space Ω} {X : Ω → E} {ℙ : measure Ω} {μ : measure E} {s : set E} (hns : μ s ≠ 0) (hnt : μ s ≠ ∞) (hms : measurable_set s) (hu : is_uniform X s ℙ μ) : is_probability_measure ℙ := ⟨begin have : X ⁻¹' set.univ = set.univ, { simp only [set.preimage_univ] }, rw [←this, hu.measure_preimage hns hnt hms measurable_set.univ, set.inter_univ, ennreal.div_self hns hnt], end⟩ variables {X : Ω → ℝ} {s : set ℝ} (hms : measurable_set s) (hns : volume s ≠ 0) include hms hns lemma mul_pdf_integrable [is_finite_measure ℙ] (hcs : is_compact s) (huX : is_uniform X s ℙ) : integrable (λ x : ℝ, x * (pdf X ℙ volume x).to_real) := begin by_cases hsupp : volume s = ∞, { have : pdf X ℙ =ᵐ[volume] 0, { refine ae_eq_trans huX _, simp [hsupp] }, refine integrable.congr (integrable_zero _ _ _) _, rw [(by simp : (λ x, 0 : ℝ → ℝ) = (λ x, x * (0 : ℝ≥0∞).to_real))], refine filter.eventually_eq.mul (ae_eq_refl _) (filter.eventually_eq.fun_comp this.symm ennreal.to_real) }, refine ⟨ae_strongly_measurable_id.mul (measurable_pdf X ℙ).ae_measurable.ennreal_to_real.ae_strongly_measurable, _⟩, refine has_finite_integral_mul huX _, set ind := (volume s)⁻¹ • (1 : ℝ → ℝ≥0∞) with hind, have : ∀ x, ↑‖x‖₊ * s.indicator ind x = s.indicator (λ x, ‖x‖₊ * ind x) x := λ x, (s.indicator_mul_right (λ x, ↑‖x‖₊) ind).symm, simp only [this, lintegral_indicator _ hms, hind, mul_one, algebra.id.smul_eq_mul, pi.one_apply, pi.smul_apply], rw lintegral_mul_const _ measurable_nnnorm.coe_nnreal_ennreal, { refine (ennreal.mul_lt_top (set_lintegral_lt_top_of_is_compact hsupp hcs continuous_nnnorm).ne (ennreal.inv_lt_top.2 (pos_iff_ne_zero.mpr hns)).ne).ne }, { apply_instance } end /-- A real uniform random variable `X` with support `s` has expectation `(λ s)⁻¹ * ∫ x in s, x ∂λ` where `λ` is the Lebesgue measure. -/ lemma integral_eq (hnt : volume s ≠ ∞) (huX : is_uniform X s ℙ) : ∫ x, X x ∂ℙ = (volume s)⁻¹.to_real * ∫ x in s, x := begin haveI := has_pdf hns hnt huX, haveI := huX.is_probability_measure hns hnt hms, rw ← integral_mul_eq_integral, rw integral_congr_ae (filter.eventually_eq.mul (ae_eq_refl _) (pdf_to_real_ae_eq huX)), have : ∀ x, x * (s.indicator ((volume s)⁻¹ • (1 : ℝ → ℝ≥0∞)) x).to_real = x * (s.indicator ((volume s)⁻¹.to_real • (1 : ℝ → ℝ)) x), { refine λ x, congr_arg ((*) x) _, by_cases hx : x ∈ s, { simp [set.indicator_of_mem hx] }, { simp [set.indicator_of_not_mem hx] }}, simp_rw [this, ← s.indicator_mul_right (λ x, x), integral_indicator hms], change ∫ x in s, x * ((volume s)⁻¹.to_real • 1) ∂(volume) = _, rw [integral_mul_right, mul_comm, algebra.id.smul_eq_mul, mul_one], end . end is_uniform end end pdf end measure_theory
d5c7377f0fd0cc1aed08bb8702639196b82eb8c1
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/matrix/nonsingular_inverse.lean
c84571d57cdd149cc1912aeb2e694c13c930d761
[ "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
23,147
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baanen, Lu-Ming Zhang -/ import algebra.regular.smul import linear_algebra.matrix.adjugate import linear_algebra.matrix.polynomial /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. We show that dividing the adjugate by `det A` (if possible), giving a matrix `A⁻¹` (`nonsing_inv`), will result in a multiplicative inverse to `A`. Note that there are at least three different inverses in mathlib: * `A⁻¹` (`has_inv.inv`): alone, this satisfies no properties, although it is usually used in conjunction with `group` or `group_with_zero`. On matrices, this is defined to be zero when no inverse exists. * `⅟A` (`inv_of`): this is only available in the presence of `[invertible A]`, which guarantees an inverse exists. * `ring.inverse A`: this is defined on any `monoid_with_zero`, and just like `⁻¹` on matrices, is defined to be zero when no inverse exists. We start by working with `invertible`, and show the main results: * `matrix.invertible_of_det_invertible` * `matrix.det_invertible_of_invertible` * `matrix.is_unit_iff_is_unit_det` * `matrix.mul_eq_one_comm` After this we define `matrix.has_inv` and show it matches `⅟A` and `ring.inverse A`. The rest of the results in the file are then about `A⁻¹` ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace matrix universes u u' v variables {m : Type u} {n : Type u'} {α : Type v} open_locale matrix big_operators open equiv equiv.perm finset /-! ### Matrices are `invertible` iff their determinants are -/ section invertible variables [fintype n] [decidable_eq n] [comm_ring α] /-- A copy of `inv_of_mul_self` using `⬝` not `*`. -/ protected lemma inv_of_mul_self (A : matrix n n α) [invertible A] : ⅟A ⬝ A = 1 := inv_of_mul_self A /-- A copy of `mul_inv_of_self` using `⬝` not `*`. -/ protected lemma mul_inv_of_self (A : matrix n n α) [invertible A] : A ⬝ ⅟A = 1 := mul_inv_of_self A /-- A copy of `inv_of_mul_self_assoc` using `⬝` not `*`. -/ protected lemma inv_of_mul_self_assoc (A : matrix n n α) (B : matrix n m α) [invertible A] : ⅟A ⬝ (A ⬝ B) = B := by rw [←matrix.mul_assoc, matrix.inv_of_mul_self, matrix.one_mul] /-- A copy of `mul_inv_of_self_assoc` using `⬝` not `*`. -/ protected lemma mul_inv_of_self_assoc (A : matrix n n α) (B : matrix n m α) [invertible A] : A ⬝ (⅟A ⬝ B) = B := by rw [←matrix.mul_assoc, matrix.mul_inv_of_self, matrix.one_mul] /-- A copy of `mul_inv_of_mul_self_cancel` using `⬝` not `*`. -/ protected lemma mul_inv_of_mul_self_cancel (A : matrix m n α) (B : matrix n n α) [invertible B] : A ⬝ ⅟B ⬝ B = A := by rw [matrix.mul_assoc, matrix.inv_of_mul_self, matrix.mul_one] /-- A copy of `mul_mul_inv_of_self_cancel` using `⬝` not `*`. -/ protected lemma mul_mul_inv_of_self_cancel (A : matrix m n α) (B : matrix n n α) [invertible B] : A ⬝ B ⬝ ⅟B = A := by rw [matrix.mul_assoc, matrix.mul_inv_of_self, matrix.mul_one] variables (A : matrix n n α) (B : matrix n n α) /-- If `A.det` has a constructive inverse, produce one for `A`. -/ def invertible_of_det_invertible [invertible A.det] : invertible A := { inv_of := ⅟A.det • A.adjugate, mul_inv_of_self := by rw [mul_smul_comm, matrix.mul_eq_mul, mul_adjugate, smul_smul, inv_of_mul_self, one_smul], inv_of_mul_self := by rw [smul_mul_assoc, matrix.mul_eq_mul, adjugate_mul, smul_smul, inv_of_mul_self, one_smul] } lemma inv_of_eq [invertible A.det] [invertible A] : ⅟A = ⅟A.det • A.adjugate := by { letI := invertible_of_det_invertible A, convert (rfl : ⅟A = _) } /-- `A.det` is invertible if `A` has a left inverse. -/ def det_invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [mul_comm, ← det_mul, h, det_one], inv_of_mul_self := by rw [← det_mul, h, det_one] } /-- `A.det` is invertible if `A` has a right inverse. -/ def det_invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [← det_mul, h, det_one], inv_of_mul_self := by rw [mul_comm, ← det_mul, h, det_one] } /-- If `A` has a constructive inverse, produce one for `A.det`. -/ def det_invertible_of_invertible [invertible A] : invertible A.det := det_invertible_of_left_inverse A (⅟A) (inv_of_mul_self _) lemma det_inv_of [invertible A] [invertible A.det] : (⅟A).det = ⅟A.det := by { letI := det_invertible_of_invertible A, convert (rfl : _ = ⅟A.det) } /-- Together `matrix.det_invertible_of_invertible` and `matrix.invertible_of_det_invertible` form an equivalence, although both sides of the equiv are subsingleton anyway. -/ @[simps] def invertible_equiv_det_invertible : invertible A ≃ invertible A.det := { to_fun := @det_invertible_of_invertible _ _ _ _ _ A, inv_fun := @invertible_of_det_invertible _ _ _ _ _ A, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } variables {A B} lemma mul_eq_one_comm : A ⬝ B = 1 ↔ B ⬝ A = 1 := suffices ∀ A B, A ⬝ B = 1 → B ⬝ A = 1, from ⟨this A B, this B A⟩, assume A B h, begin letI : invertible B.det := det_invertible_of_left_inverse _ _ h, letI : invertible B := invertible_of_det_invertible B, calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ ⅟B) : by rw [matrix.mul_inv_of_self, matrix.mul_one] ... = B ⬝ ((A ⬝ B) ⬝ ⅟B) : by simp only [matrix.mul_assoc] ... = B ⬝ ⅟B : by rw [h, matrix.one_mul] ... = 1 : matrix.mul_inv_of_self B, end variables (A B) /-- We can construct an instance of invertible A if A has a left inverse. -/ def invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A := ⟨B, h, mul_eq_one_comm.mp h⟩ /-- We can construct an instance of invertible A if A has a right inverse. -/ def invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A := ⟨B, mul_eq_one_comm.mp h, h⟩ /-- Given a proof that `A.det` has a constructive inverse, lift `A` to `(matrix n n α)ˣ`-/ def unit_of_det_invertible [invertible A.det] : (matrix n n α)ˣ := @unit_of_invertible _ _ A (invertible_of_det_invertible A) /-- When lowered to a prop, `matrix.invertible_equiv_det_invertible` forms an `iff`. -/ lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det := by simp only [← nonempty_invertible_iff_is_unit, (invertible_equiv_det_invertible A).nonempty_congr] /-! #### Variants of the statements above with `is_unit`-/ lemma is_unit_det_of_invertible [invertible A] : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_invertible A) variables {A B} lemma is_unit_det_of_left_inverse (h : B ⬝ A = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_left_inverse _ _ h) lemma is_unit_det_of_right_inverse (h : A ⬝ B = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_right_inverse _ _ h) lemma det_ne_zero_of_left_inverse [nontrivial α] (h : B ⬝ A = 1) : A.det ≠ 0 := (is_unit_det_of_left_inverse h).ne_zero lemma det_ne_zero_of_right_inverse [nontrivial α] (h : A ⬝ B = 1) : A.det ≠ 0 := (is_unit_det_of_right_inverse h).ne_zero end invertible variables [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] [comm_ring α] variables (A : matrix n n α) (B : matrix n n α) lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det := by { rw det_transpose, exact h, } /-! ### A noncomputable `has_inv` instance -/ /-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/ noncomputable instance : has_inv (matrix n n α) := ⟨λ A, ring.inverse A.det • A.adjugate⟩ lemma inv_def (A : matrix n n α) : A⁻¹ = ring.inverse A.det • A.adjugate := rfl lemma nonsing_inv_apply_not_is_unit (h : ¬ is_unit A.det) : A⁻¹ = 0 := by rw [inv_def, ring.inverse_non_unit _ h, zero_smul] lemma nonsing_inv_apply (h : is_unit A.det) : A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate := by rw [inv_def, ←ring.inverse_unit h.unit, is_unit.unit_spec] /-- The nonsingular inverse is the same as `inv_of` when `A` is invertible. -/ @[simp] lemma inv_of_eq_nonsing_inv [invertible A] : ⅟A = A⁻¹ := begin letI := det_invertible_of_invertible A, rw [inv_def, ring.inverse_invertible, inv_of_eq], end /-- Coercing the result of `units.has_inv` is the same as coercing first and applying the nonsingular inverse. -/ @[simp, norm_cast] lemma coe_units_inv (A : (matrix n n α)ˣ) : ↑(A⁻¹) = (A⁻¹ : matrix n n α) := begin letI := A.invertible, rw [←inv_of_eq_nonsing_inv, inv_of_units], end /-- The nonsingular inverse is the same as the general `ring.inverse`. -/ lemma nonsing_inv_eq_ring_inverse : A⁻¹ = ring.inverse A := begin by_cases h_det : is_unit A.det, { casesI (A.is_unit_iff_is_unit_det.mpr h_det).nonempty_invertible, rw [←inv_of_eq_nonsing_inv, ring.inverse_invertible], }, { have h := mt A.is_unit_iff_is_unit_det.mp h_det, rw [ring.inverse_non_unit _ h, nonsing_inv_apply_not_is_unit A h_det], }, end lemma transpose_nonsing_inv : (A⁻¹)ᵀ = (Aᵀ)⁻¹ := by rw [inv_def, inv_def, transpose_smul, det_transpose, adjugate_transpose] lemma conj_transpose_nonsing_inv [star_ring α] : (A⁻¹)ᴴ = (Aᴴ)⁻¹ := by rw [inv_def, inv_def, conj_transpose_smul, det_conj_transpose, adjugate_conj_transpose, ring.inverse_star] /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 := begin casesI (A.is_unit_iff_is_unit_det.mpr h).nonempty_invertible, rw [←inv_of_eq_nonsing_inv, matrix.mul_inv_of_self], end /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 := begin casesI (A.is_unit_iff_is_unit_det.mpr h).nonempty_invertible, rw [←inv_of_eq_nonsing_inv, matrix.inv_of_mul_self], end @[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 := mul_nonsing_inv A (is_unit_det_of_invertible A) @[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 := nonsing_inv_mul A (is_unit_det_of_invertible A) lemma nonsing_inv_cancel_or_zero : (A⁻¹ ⬝ A = 1 ∧ A ⬝ A⁻¹ = 1) ∨ A⁻¹ = 0 := begin by_cases h : is_unit A.det, { exact or.inl ⟨nonsing_inv_mul _ h, mul_nonsing_inv _ h⟩ }, { exact or.inr (nonsing_inv_apply_not_is_unit _ h) } end lemma det_nonsing_inv_mul_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 := by rw [←det_mul, A.nonsing_inv_mul h, det_one] @[simp] lemma det_nonsing_inv : A⁻¹.det = ring.inverse A.det := begin by_cases h : is_unit A.det, { casesI h.nonempty_invertible, letI := invertible_of_det_invertible A, rw [ring.inverse_invertible, ←inv_of_eq_nonsing_inv, det_inv_of] }, casesI is_empty_or_nonempty n, { rw [det_is_empty, det_is_empty, ring.inverse_one] }, { rw [ring.inverse_non_unit _ h, nonsing_inv_apply_not_is_unit _ h, det_zero ‹_›] }, end lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det := is_unit_of_mul_eq_one _ _ (A.det_nonsing_inv_mul_det h) @[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A := calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul ... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h ... = A : by { rw [matrix.mul_assoc, (A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h), matrix.mul_one], } lemma is_unit_nonsing_inv_det_iff {A : matrix n n α} : is_unit A⁻¹.det ↔ is_unit A.det := by rw [matrix.det_nonsing_inv, is_unit_ring_inverse] /- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/ /-- A version of `matrix.invertible_of_det_invertible` with the inverse defeq to `A⁻¹` that is therefore noncomputable. -/ noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A := ⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩ /-- A version of `matrix.units_of_det_invertible` with the inverse defeq to `A⁻¹` that is therefore noncomputable. -/ noncomputable def nonsing_inv_unit (h : is_unit A.det) : (matrix n n α)ˣ := @unit_of_invertible _ _ _ (invertible_of_is_unit_det A h) lemma unit_of_det_invertible_eq_nonsing_inv_unit [invertible A.det] : unit_of_det_invertible A = nonsing_inv_unit A (is_unit_of_invertible _) := by { ext, refl } variables {A} {B} /-- If matrix A is left invertible, then its inverse equals its left inverse. -/ lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B := begin letI := invertible_of_left_inverse _ _ h, exact inv_of_eq_nonsing_inv A ▸ inv_of_eq_left_inv h, end /-- If matrix A is right invertible, then its inverse equals its right inverse. -/ lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B := inv_eq_left_inv (mul_eq_one_comm.2 h) section inv_eq_inv variables {C : matrix n n α} /-- The left inverse of matrix A is unique when existing. -/ lemma left_inv_eq_left_inv (h : B ⬝ A = 1) (g : C ⬝ A = 1) : B = C := by rw [←inv_eq_left_inv h, ←inv_eq_left_inv g] /-- The right inverse of matrix A is unique when existing. -/ lemma right_inv_eq_right_inv (h : A ⬝ B = 1) (g : A ⬝ C = 1) : B = C := by rw [←inv_eq_right_inv h, ←inv_eq_right_inv g] /-- The right inverse of matrix A equals the left inverse of A when they exist. -/ lemma right_inv_eq_left_inv (h : A ⬝ B = 1) (g : C ⬝ A = 1) : B = C := by rw [←inv_eq_right_inv h, ←inv_eq_left_inv g] lemma inv_inj (h : A⁻¹ = B⁻¹) (h' : is_unit A.det) : A = B := begin refine left_inv_eq_left_inv (mul_nonsing_inv _ h') _, rw h, refine mul_nonsing_inv _ _, rwa [←is_unit_nonsing_inv_det_iff, ←h, is_unit_nonsing_inv_det_iff] end end inv_eq_inv variable (A) @[simp] lemma inv_zero : (0 : matrix n n α)⁻¹ = 0 := begin casesI (subsingleton_or_nontrivial α) with ht ht, { simp }, cases (fintype.card n).zero_le.eq_or_lt with hc hc, { rw [eq_comm, fintype.card_eq_zero_iff] at hc, haveI := hc, ext i, exact (is_empty.false i).elim }, { have hn : nonempty n := fintype.card_pos_iff.mp hc, refine nonsing_inv_apply_not_is_unit _ _, simp [hn] }, end @[simp] lemma inv_one : (1 : matrix n n α)⁻¹ = 1 := inv_eq_left_inv (by simp) lemma inv_smul (k : α) [invertible k] (h : is_unit A.det) : (k • A)⁻¹ = ⅟k • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_smul' (k : αˣ) (h : is_unit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_adjugate (A : matrix n n α) (h : is_unit A.det) : (adjugate A)⁻¹ = h.unit⁻¹ • A := begin refine inv_eq_left_inv _, rw [smul_mul, mul_adjugate, units.smul_def, smul_smul, h.coe_inv_mul, one_smul] end /-- `diagonal v` is invertible if `v` is -/ def diagonal_invertible {α} [non_assoc_semiring α] (v : n → α) [invertible v] : invertible (diagonal v) := invertible.map (diagonal_ring_hom n α) v lemma inv_of_diagonal_eq {α} [semiring α] (v : n → α) [invertible v] [invertible (diagonal v)] : ⅟(diagonal v) = diagonal (⅟v) := by { letI := diagonal_invertible v, convert (rfl : ⅟(diagonal v) = _) } /-- `v` is invertible if `diagonal v` is -/ def invertible_of_diagonal_invertible (v : n → α) [invertible (diagonal v)] : invertible v := { inv_of := diag (⅟(diagonal v)), inv_of_mul_self := funext $ λ i, begin letI : invertible (diagonal v).det := det_invertible_of_invertible _, rw [inv_of_eq, diag_smul, adjugate_diagonal, diag_diagonal], dsimp, rw [mul_assoc, prod_erase_mul _ _ (finset.mem_univ _), ←det_diagonal], exact mul_inv_of_self _, end, mul_inv_of_self := funext $ λ i, begin letI : invertible (diagonal v).det := det_invertible_of_invertible _, rw [inv_of_eq, diag_smul, adjugate_diagonal, diag_diagonal], dsimp, rw [mul_left_comm, mul_prod_erase _ _ (finset.mem_univ _), ←det_diagonal], exact mul_inv_of_self _, end } /-- Together `matrix.diagonal_invertible` and `matrix.invertible_of_diagonal_invertible` form an equivalence, although both sides of the equiv are subsingleton anyway. -/ @[simps] def diagonal_invertible_equiv_invertible (v : n → α) : invertible (diagonal v) ≃ invertible v := { to_fun := @invertible_of_diagonal_invertible _ _ _ _ _ _, inv_fun := @diagonal_invertible _ _ _ _ _ _, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- When lowered to a prop, `matrix.diagonal_invertible_equiv_invertible` forms an `iff`. -/ @[simp] lemma is_unit_diagonal {v : n → α} : is_unit (diagonal v) ↔ is_unit v := by simp only [← nonempty_invertible_iff_is_unit, (diagonal_invertible_equiv_invertible v).nonempty_congr] lemma inv_diagonal (v : n → α) : (diagonal v)⁻¹ = diagonal (ring.inverse v) := begin rw nonsing_inv_eq_ring_inverse, by_cases h : is_unit v, { have := is_unit_diagonal.mpr h, casesI this.nonempty_invertible, casesI h.nonempty_invertible, rw [ring.inverse_invertible, ring.inverse_invertible, inv_of_diagonal_eq], }, { have := is_unit_diagonal.not.mpr h, rw [ring.inverse_non_unit _ h, pi.zero_def, diagonal_zero, ring.inverse_non_unit _ this] } end @[simp] lemma inv_inv_inv (A : matrix n n α) : A⁻¹⁻¹⁻¹ = A⁻¹ := begin by_cases h : is_unit A.det, { rw [nonsing_inv_nonsing_inv _ h] }, { simp [nonsing_inv_apply_not_is_unit _ h] } end lemma mul_inv_rev (A B : matrix n n α) : (A ⬝ B)⁻¹ = B⁻¹ ⬝ A⁻¹ := begin simp only [inv_def], rw [matrix.smul_mul, matrix.mul_smul, smul_smul, det_mul, adjugate_mul_distrib, ring.mul_inverse_rev], end /-- A version of `list.prod_inv_reverse` for `matrix.has_inv`. -/ lemma list_prod_inv_reverse : ∀ l : list (matrix n n α), l.prod⁻¹ = (l.reverse.map has_inv.inv).prod | [] := by rw [list.reverse_nil, list.map_nil, list.prod_nil, inv_one] | (A :: Xs) := by rw [list.reverse_cons', list.map_concat, list.prod_concat, list.prod_cons, matrix.mul_eq_mul, matrix.mul_eq_mul, mul_inv_rev, list_prod_inv_reverse] /-- One form of **Cramer's rule**. See `matrix.mul_vec_cramer` for a stronger form. -/ @[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.mul_vec b = cramer A b := begin rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc, smul_smul, h.mul_coe_inv, one_smul] end /-- One form of **Cramer's rule**. See `matrix.mul_vec_cramer` for a stronger form. -/ @[simp] lemma det_smul_inv_vec_mul_eq_cramer_transpose (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.vec_mul b = cramer Aᵀ b := by rw [← (A⁻¹).transpose_transpose, vec_mul_transpose, transpose_nonsing_inv, ← det_transpose, Aᵀ.det_smul_inv_mul_vec_eq_cramer _ (is_unit_det_transpose A h)] /-! ### More results about determinants -/ /-- A variant of `matrix.det_units_conj`. -/ lemma det_conj {M : matrix m m α} (h : is_unit M) (N : matrix m m α) : det (M ⬝ N ⬝ M⁻¹) = det N := by rw [←h.unit_spec, ←coe_units_inv, det_units_conj] /-- A variant of `matrix.det_units_conj'`. -/ lemma det_conj' {M : matrix m m α} (h : is_unit M) (N : matrix m m α) : det (M⁻¹ ⬝ N ⬝ M) = det N := by rw [←h.unit_spec, ←coe_units_inv, det_units_conj'] /-- Determinant of a 2×2 block matrix, expanded around an invertible top left element in terms of the Schur complement. -/ lemma det_from_blocks₁₁ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) [invertible A] : (matrix.from_blocks A B C D).det = det A * det (D - C ⬝ (⅟A) ⬝ B) := begin have : from_blocks A B C D = from_blocks 1 0 (C ⬝ ⅟A) 1 ⬝ from_blocks A 0 0 (D - C ⬝ (⅟A) ⬝ B) ⬝ from_blocks 1 (⅟A ⬝ B) 0 1, { simp only [from_blocks_multiply, matrix.mul_zero, matrix.zero_mul, add_zero, zero_add, matrix.one_mul, matrix.mul_one, matrix.inv_of_mul_self, matrix.mul_inv_of_self_assoc, matrix.mul_inv_of_mul_self_cancel, matrix.mul_assoc, add_sub_cancel'_right] }, rw [this, det_mul, det_mul, det_from_blocks_zero₂₁, det_from_blocks_zero₂₁, det_from_blocks_zero₁₂, det_one, det_one, one_mul, one_mul, mul_one], end @[simp] lemma det_from_blocks_one₁₁ (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) : (matrix.from_blocks 1 B C D).det = det (D - C ⬝ B) := begin haveI : invertible (1 : matrix m m α) := invertible_one, rw [det_from_blocks₁₁, inv_of_one, matrix.mul_one, det_one, one_mul], end /-- Determinant of a 2×2 block matrix, expanded around an invertible bottom right element in terms of the Schur complement. -/ lemma det_from_blocks₂₂ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) (D : matrix n n α) [invertible D] : (matrix.from_blocks A B C D).det = det D * det (A - B ⬝ (⅟D) ⬝ C) := begin have : from_blocks A B C D = (from_blocks D C B A).minor (sum_comm _ _) (sum_comm _ _), { ext i j, cases i; cases j; refl }, rw [this, det_minor_equiv_self, det_from_blocks₁₁], end @[simp] lemma det_from_blocks_one₂₂ (A : matrix m m α) (B : matrix m n α) (C : matrix n m α) : (matrix.from_blocks A B C 1).det = det (A - B ⬝ C) := begin haveI : invertible (1 : matrix n n α) := invertible_one, rw [det_from_blocks₂₂, inv_of_one, matrix.mul_one, det_one, one_mul], end /-- The **Weinstein–Aronszajn identity**. Note the `1` on the LHS is of shape m×m, while the `1` on the RHS is of shape n×n. -/ lemma det_one_add_mul_comm (A : matrix m n α) (B : matrix n m α) : det (1 + A ⬝ B) = det (1 + B ⬝ A) := calc det (1 + A ⬝ B) = det (from_blocks 1 (-A) B 1) : by rw [det_from_blocks_one₂₂, matrix.neg_mul, sub_neg_eq_add] ... = det (1 + B ⬝ A) : by rw [det_from_blocks_one₁₁, matrix.mul_neg, sub_neg_eq_add] /-- Alternate statement of the **Weinstein–Aronszajn identity** -/ lemma det_mul_add_one_comm (A : matrix m n α) (B : matrix n m α) : det (A ⬝ B + 1) = det (B ⬝ A + 1) := by rw [add_comm, det_one_add_mul_comm, add_comm] lemma det_one_sub_mul_comm (A : matrix m n α) (B : matrix n m α) : det (1 - A ⬝ B) = det (1 - B ⬝ A) := by rw [sub_eq_add_neg, ←matrix.neg_mul, det_one_add_mul_comm, matrix.mul_neg, ←sub_eq_add_neg] /-- A special case of the **Matrix determinant lemma** for when `A = I`. TODO: show this more generally. -/ lemma det_one_add_col_mul_row (u v : m → α) : det (1 + col u ⬝ row v) = 1 + v ⬝ᵥ u := by rw [det_one_add_mul_comm, det_unique, pi.add_apply, pi.add_apply, matrix.one_apply_eq, matrix.row_mul_col_apply] end matrix
873ee9a502247b8c373793ccc59ccc4f66f31914
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/closed/ideal.lean
031a35b28df17bd5ea0ad8e5d1ee0db7562c40f2
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
11,750
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.constructions.finite_products_of_binary_products import category_theory.monad.limits import category_theory.adjunction.fully_faithful import category_theory.adjunction.reflective import category_theory.closed.cartesian import category_theory.subterminal /-! # Exponential ideals An exponential ideal of a cartesian closed category `C` is a subcategory `D ⊆ C` such that for any `B : D` and `A : C`, the exponential `A ⟹ B` is in `D`: resembling ring theoretic ideals. We define the notion here for inclusion functors `i : D ⥤ C` rather than explicit subcategories to preserve the principle of equivalence. We additionally show that if `C` is cartesian closed and `i : D ⥤ C` is a reflective functor, the following are equivalent. * The left adjoint to `i` preserves binary (equivalently, finite) products. * `i` is an exponential ideal. -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open limits category section ideal variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] {i : D ⥤ C} variables (i) [has_finite_products C] [cartesian_closed C] /-- The subcategory `D` of `C` expressed as an inclusion functor is an *exponential ideal* if `B ∈ D` implies `A ⟹ B ∈ D` for all `A`. -/ class exponential_ideal : Prop := (exp_closed : ∀ {B}, B ∈ i.ess_image → ∀ A, (A ⟹ B) ∈ i.ess_image) /-- To show `i` is an exponential ideal it suffices to show that `A ⟹ iB` is "in" `D` for any `A` in `C` and `B` in `D`. -/ lemma exponential_ideal.mk' (h : ∀ (B : D) (A : C), (A ⟹ i.obj B) ∈ i.ess_image) : exponential_ideal i := ⟨λ B hB A, begin rcases hB with ⟨B', ⟨iB'⟩⟩, exact functor.ess_image.of_iso ((exp A).map_iso iB') (h B' A), end⟩ /-- The entire category viewed as a subcategory is an exponential ideal. -/ instance : exponential_ideal (𝟭 C) := exponential_ideal.mk' _ (λ B A, ⟨_, ⟨iso.refl _⟩⟩) /-- The subcategory of subterminal objects is an exponential ideal. -/ instance : exponential_ideal (subterminal_inclusion C) := begin apply exponential_ideal.mk', intros B A, refine ⟨⟨A ⟹ B.1, λ Z g h, _⟩, ⟨iso.refl _⟩⟩, exact uncurry_injective (B.2 (cartesian_closed.uncurry g) (cartesian_closed.uncurry h)) end /-- If `D` is a reflective subcategory, the property of being an exponential ideal is equivalent to the presence of a natural isomorphism `i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A`, that is: `(A ⟹ iB) ≅ i L (A ⟹ iB)`, naturally in `B`. The converse is given in `exponential_ideal.mk_of_iso`. -/ def exponential_ideal_reflective (A : C) [reflective i] [exponential_ideal i] : i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A := begin symmetry, apply nat_iso.of_components _ _, { intro X, haveI := (exponential_ideal.exp_closed (i.obj_mem_ess_image X) A).unit_is_iso, apply as_iso ((adjunction.of_right_adjoint i).unit.app (A ⟹ i.obj X)) }, { simp } end /-- Given a natural isomorphism `i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A`, we can show `i` is an exponential ideal. -/ lemma exponential_ideal.mk_of_iso [reflective i] (h : Π (A : C), i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A) : exponential_ideal i := begin apply exponential_ideal.mk', intros B A, exact ⟨_, ⟨(h A).app B⟩⟩, end end ideal section variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] variables (i : D ⥤ C) lemma reflective_products [has_finite_products C] [reflective i] : has_finite_products D := ⟨λ J 𝒥₁ 𝒥₂, by exactI has_limits_of_shape_of_reflective i⟩ local attribute [instance, priority 10] reflective_products variables [has_finite_products C] [reflective i] [cartesian_closed C] /-- If the reflector preserves binary products, the subcategory is an exponential ideal. This is the converse of `preserves_binary_products_of_exponential_ideal`. -/ @[priority 10] instance exponential_ideal_of_preserves_binary_products [preserves_limits_of_shape (discrete walking_pair) (left_adjoint i)] : exponential_ideal i := begin let ir := adjunction.of_right_adjoint i, let L : C ⥤ D := left_adjoint i, let η : 𝟭 C ⟶ L ⋙ i := ir.unit, let ε : i ⋙ L ⟶ 𝟭 D := ir.counit, apply exponential_ideal.mk', intros B A, let q : i.obj (L.obj (A ⟹ i.obj B)) ⟶ A ⟹ i.obj B, apply cartesian_closed.curry (ir.hom_equiv _ _ _), apply _ ≫ (ir.hom_equiv _ _).symm ((ev A).app (i.obj B)), refine prod_comparison L A _ ≫ limits.prod.map (𝟙 _) (ε.app _) ≫ inv (prod_comparison _ _ _), have : η.app (A ⟹ i.obj B) ≫ q = 𝟙 (A ⟹ i.obj B), { dsimp, rw [← curry_natural_left, curry_eq_iff, uncurry_id_eq_ev, ← ir.hom_equiv_naturality_left, ir.hom_equiv_apply_eq, assoc, assoc, prod_comparison_natural_assoc, L.map_id, ← prod.map_id_comp_assoc, ir.left_triangle_components, prod.map_id_id, id_comp], apply is_iso.hom_inv_id_assoc }, haveI : split_mono (η.app (A ⟹ i.obj B)) := ⟨_, this⟩, apply mem_ess_image_of_unit_split_mono, end variables [exponential_ideal i] /-- If `i` witnesses that `D` is a reflective subcategory and an exponential ideal, then `D` is itself cartesian closed. -/ def cartesian_closed_of_reflective : cartesian_closed D := { closed := λ B, { is_adj := { right := i ⋙ exp (i.obj B) ⋙ left_adjoint i, adj := begin apply adjunction.restrict_fully_faithful i i (exp.adjunction (i.obj B)), { symmetry, apply nat_iso.of_components _ _, { intro X, haveI := adjunction.right_adjoint_preserves_limits (adjunction.of_right_adjoint i), apply as_iso (prod_comparison i B X) }, { intros X Y f, dsimp, rw prod_comparison_natural, simp, } }, { apply (exponential_ideal_reflective i _).symm } end } } } -- It's annoying that I need to do this. local attribute [-instance] category_theory.preserves_limit_of_creates_limit_and_has_limit category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape /-- We construct a bijection between morphisms `L(A ⨯ B) ⟶ X` and morphisms `LA ⨯ LB ⟶ X`. This bijection has two key properties: * It is natural in `X`: See `bijection_natural`. * When `X = LA ⨯ LB`, then the backwards direction sends the identity morphism to the product comparison morphism: See `bijection_symm_apply_id`. Together these help show that `L` preserves binary products. This should be considered *internal implementation* towards `preserves_binary_products_of_exponential_ideal`. -/ noncomputable def bijection (A B : C) (X : D) : ((left_adjoint i).obj (A ⨯ B) ⟶ X) ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ X) := calc _ ≃ (A ⨯ B ⟶ i.obj X) : (adjunction.of_right_adjoint i).hom_equiv _ _ ... ≃ (B ⨯ A ⟶ i.obj X) : (limits.prod.braiding _ _).hom_congr (iso.refl _) ... ≃ (A ⟶ B ⟹ i.obj X) : (exp.adjunction _).hom_equiv _ _ ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B ⟹ i.obj X) : unit_comp_partial_bijective _ (exponential_ideal.exp_closed (i.obj_mem_ess_image _) _) ... ≃ (B ⨯ i.obj ((left_adjoint i).obj A) ⟶ i.obj X) : ((exp.adjunction _).hom_equiv _ _).symm ... ≃ (i.obj ((left_adjoint i).obj A) ⨯ B ⟶ i.obj X) : (limits.prod.braiding _ _).hom_congr (iso.refl _) ... ≃ (B ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj X) : (exp.adjunction _).hom_equiv _ _ ... ≃ (i.obj ((left_adjoint i).obj B) ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj X) : unit_comp_partial_bijective _ (exponential_ideal.exp_closed (i.obj_mem_ess_image _) _) ... ≃ (i.obj ((left_adjoint i).obj A) ⨯ i.obj ((left_adjoint i).obj B) ⟶ i.obj X) : ((exp.adjunction _).hom_equiv _ _).symm ... ≃ (i.obj ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B) ⟶ i.obj X) : begin apply iso.hom_congr _ (iso.refl _), haveI : preserves_limits i := (adjunction.of_right_adjoint i).right_adjoint_preserves_limits, exact (preserves_limit_pair.iso _ _ _).symm, end ... ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ X) : (equiv_of_fully_faithful _).symm lemma bijection_symm_apply_id (A B : C) : (bijection i A B _).symm (𝟙 _) = prod_comparison _ _ _ := begin dsimp [bijection], rw [comp_id, comp_id, comp_id, i.map_id, comp_id, unit_comp_partial_bijective_symm_apply, unit_comp_partial_bijective_symm_apply, uncurry_natural_left, uncurry_curry, uncurry_natural_left, uncurry_curry, prod.lift_map_assoc, comp_id, prod.lift_map_assoc, comp_id, prod.comp_lift_assoc, prod.lift_snd, prod.lift_fst_assoc, prod.lift_fst_comp_snd_comp, ←adjunction.eq_hom_equiv_apply, adjunction.hom_equiv_unit, iso.comp_inv_eq, assoc, preserves_limit_pair.iso_hom], apply prod.hom_ext, { rw [limits.prod.map_fst, assoc, assoc, prod_comparison_fst, ←i.map_comp, prod_comparison_fst], apply (adjunction.of_right_adjoint i).unit.naturality }, { rw [limits.prod.map_snd, assoc, assoc, prod_comparison_snd, ←i.map_comp, prod_comparison_snd], apply (adjunction.of_right_adjoint i).unit.naturality }, end lemma bijection_natural (A B : C) (X X' : D) (f : ((left_adjoint i).obj (A ⨯ B) ⟶ X)) (g : X ⟶ X') : bijection i _ _ _ (f ≫ g) = bijection i _ _ _ f ≫ g := begin dsimp [bijection], apply i.map_injective, rw [i.image_preimage, i.map_comp, i.image_preimage, comp_id, comp_id, comp_id, comp_id, comp_id, comp_id, adjunction.hom_equiv_naturality_right, ← assoc, curry_natural_right _ (i.map g), unit_comp_partial_bijective_natural, uncurry_natural_right, ← assoc, curry_natural_right, unit_comp_partial_bijective_natural, uncurry_natural_right, assoc], end /-- The bijection allows us to show that `prod_comparison L A B` is an isomorphism, where the inverse is the forward map of the identity morphism. -/ lemma prod_comparison_iso (A B : C) : is_iso (prod_comparison (left_adjoint i) A B) := ⟨⟨bijection i _ _ _ (𝟙 _), by rw [←(bijection i _ _ _).injective.eq_iff, bijection_natural, ← bijection_symm_apply_id, equiv.apply_symm_apply, id_comp], by rw [←bijection_natural, id_comp, ←bijection_symm_apply_id, equiv.apply_symm_apply]⟩⟩ local attribute [instance] prod_comparison_iso /-- If a reflective subcategory is an exponential ideal, then the reflector preserves binary products. This is the converse of `exponential_ideal_of_preserves_binary_products`. -/ noncomputable def preserves_binary_products_of_exponential_ideal : preserves_limits_of_shape (discrete walking_pair) (left_adjoint i) := { preserves_limit := λ K, begin apply limits.preserves_limit_of_iso_diagram _ (diagram_iso_pair K).symm, apply preserves_limit_pair.of_iso_prod_comparison, end } /-- If a reflective subcategory is an exponential ideal, then the reflector preserves finite products. -/ noncomputable def preserves_finite_products_of_exponential_ideal (J : Type*) [fintype J] : preserves_limits_of_shape (discrete J) (left_adjoint i) := begin letI := preserves_binary_products_of_exponential_ideal i, letI := left_adjoint_preserves_terminal_of_reflective i, apply preserves_finite_products_of_preserves_binary_and_terminal (left_adjoint i) J end end end category_theory
37880d6f40236064aa502b813d2be31810f10d4e
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/free_comm_ring.lean
3d93f61504920132cb82b0d35c23e98cc93e46f8
[ "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
14,411
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.equiv.functor import data.mv_polynomial.equiv import data.mv_polynomial.comm_ring import ring_theory.free_ring /-! # Free commutative rings The theory of the free commutative ring generated by a type `α`. It is isomorphic to the polynomial ring over ℤ with variables in `α` ## Main definitions * `free_comm_ring α` : the free commutative ring on a type α * `lift (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`. * `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by functoriality from f. ## Main results `free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor). In this file we have: * `of : α → free_comm_ring α` * `lift (f : α → R) : free_comm_ring α →+* R` * `map (f : α → β) : free_comm_ring α →+* free_comm_ring β` * `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` : `free_comm_ring α` is isomorphic to a polynomial ring. ## Implementation notes `free_comm_ring α` is implemented not using `mv_polynomial` but directly as the free abelian group on `multiset α`, the type of monomials in this free commutative ring. ## Tags free commutative ring, free ring -/ noncomputable theory open_locale classical universes u v variables (α : Type u) /-- `free_comm_ring α` is the free commutative ring on the type `α`. -/ @[derive [comm_ring, inhabited]] def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring variables {α} /-- The canonical map from `α` to the free commutative ring on `α`. -/ def of (x : α) : free_comm_ring α := free_abelian_group.of $ multiplicative.of_add ({x} : multiset α) lemma of_injective : function.injective (of : α → free_comm_ring α) := free_abelian_group.of_injective.comp (λ x y, (multiset.coe_eq_coe.trans list.singleton_perm_singleton).mp) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {R : Type v} [comm_ring R] (f : α → R) /-- A helper to implement `lift`. This is essentially `free_comm_monoid.lift`, but this does not currently exist. -/ private def lift_to_multiset : (α → R) ≃ (multiplicative (multiset α) →* R) := { to_fun := λ f, { to_fun := λ s, (s.to_add.map f).prod, map_mul' := λ x y, calc _ = multiset.prod ((multiset.map f x) + (multiset.map f y)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _, map_one' := rfl}, inv_fun := λ F x, F (multiplicative.of_add ({x} : multiset α)), left_inv := λ f, funext $ λ x, show (multiset.map f (x ::ₘ 0)).prod = _, by simp, right_inv := λ F, monoid_hom.ext $ λ x, let F' := F.to_additive'', x' := x.to_add in show (multiset.map (λ a, F' {a}) x').sum = F' x', begin rw [←multiset.map_map, ←add_monoid_hom.map_multiset_sum], exact F.congr_arg (multiset.sum_map_singleton x'), end } /-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : (α → R) ≃ (free_comm_ring α →+* R) := equiv.trans lift_to_multiset free_abelian_group.lift_monoid @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_comp_of (f : free_comm_ring α →+* R) : lift (f ∘ of) = f := ring_hom.ext $ λ x, free_comm_ring.induction_on x (by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one]) (lift_of _) (λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy]) (λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy]) @[ext] lemma hom_ext ⦃f g : free_comm_ring α →+* R⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := lift.symm.injective (funext h) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift $ of ∘ f @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ /-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported /-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined by sending all variables not in `s` to zero. -/ def restriction (s : set α) [decidable_pred s] : free_comm_ring α →+* free_comm_ring s := lift (λ p, if H : p ∈ s then of (⟨p, H⟩ : s) else 0) section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin haveI := classical.dec_pred s, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [ring_hom.map_one], norm_cast }, { use -1, rw [ring_hom.map_neg, ring_hom.map_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [ring_hom.map_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [ring_hom.map_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw ring_hom.map_one, refl }, { rw [ring_hom.map_neg, ring_hom.map_neg, ring_hom.map_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [ring_hom.map_mul, restriction_of, dif_pos hps, ring_hom.map_mul, map_of, ih] }, { intros x y ihx ihy, rw [ring_hom.map_add, ring_hom.map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) /-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring generated by `α`. -/ def to_free_comm_ring {α} : free_ring α →+* free_comm_ring α := free_ring.lift free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := (free_ring.lift _).map_neg _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := (free_ring.lift _).map_add _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := (free_ring.lift _).map_sub _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := (free_ring.lift _).map_mul _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact (free_ring.lift _).map_add _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact (free_ring.lift _).map_mul _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := funext $ λ x, free_abelian_group.lift.unique _ _ $ λ L, by { simp_rw [free_abelian_group.lift.of, (∘)], exact free_monoid.rec_on L rfl (λ hd tl ih, by { rw [(free_monoid.lift _).map_mul, free_monoid.lift_eval_of, ih], refl }) } -- FIXME This was in `deprecated.ring`, but only used here. -- It would be good to inline it into the next construction. /-- Interpret an equivalence `f : R ≃ S` as a ring equivalence `R ≃+* S`. -/ def of' {R S : Type*} [ring R] [ring S] (e : R ≃ S) [is_ring_hom e] : R ≃+* S := { .. e, .. monoid_hom.of e, .. add_monoid_hom.of e } /-- If α has size at most 1 then the natural map from the free ring on `α` to the free commutative ring on `α` is an isomorphism of rings. -/ def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by { rw [← (subsingleton_equiv_free_comm_ring α).symm_apply_apply (y * x), ((subsingleton_equiv_free_comm_ring α)).map_mul, mul_comm, ← ((subsingleton_equiv_free_comm_ring α)).map_mul, (subsingleton_equiv_free_comm_ring α).symm_apply_apply], }, .. free_ring.ring α } end free_ring /-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with variables in `α` -/ def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := ring_equiv.of_hom_inv (free_comm_ring.lift $ λ a, mv_polynomial.X a) (mv_polynomial.eval₂_hom (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of) (by { ext, simp }) (by ext; simp ) /-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/ def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) -- this messes with the next definition local attribute [-instance] algebra_int /-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := (free_comm_ring_equiv_mv_polynomial_int _).trans (mv_polynomial.punit_alg_equiv ℤ).to_ring_equiv open free_ring /-- The free ring on the empty type is isomorphic to `ℤ`. -/ def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int /-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
f603ed7bd43abf4682a5c62b1df2e119c8a2168e
57c233acf9386e610d99ed20ef139c5f97504ba3
/counterexamples/phillips.lean
48ecc429ae3073147fd75376c9f920ad2fd13ff2
[ "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
28,546
lean
/- Copyright (c) 2021 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.normed_space.hahn_banach import measure_theory.measure.lebesgue /-! # A counterexample on Pettis integrability There are several theories of integration for functions taking values in Banach spaces. Bochner integration, requiring approximation by simple functions, is the analogue of the one-dimensional theory. It is very well behaved, but only works for functions with second-countable range. For functions `f` taking values in a larger Banach space `B`, one can define the Dunford integral as follows. Assume that, for all continuous linear functional `φ`, the function `φ ∘ f` is measurable (we say that `f` is weakly measurable, or scalarly measurable) and integrable. Then `φ ↦ ∫ φ ∘ f` is continuous (by the closed graph theorem), and therefore defines an element of the bidual `B**`. This is the Dunford integral of `f`. This Dunford integral is not usable in practice as it does not belong to the right space. Let us say that a function is Pettis integrable if its Dunford integral belongs to the canonical image of `B` in `B**`. In this case, we define the Pettis integral as the Dunford integral inside `B`. This integral is very general, but not really usable to do analysis. This file illustrates this, by giving an example of a function with nice properties but which is *not* Pettis-integrable. This function: - is defined from `[0, 1]` to a complete Banach space; - is weakly measurable; - has norm everywhere bounded by `1` (in particular, its norm is integrable); - and yet it is not Pettis-integrable with respect to Lebesgue measure. This construction is due to [Ralph S. Phillips, *Integration in a convex linear topological space*][phillips1940], in Example 10.8. It requires the continuum hypothesis. The example is the following. Under the continuum hypothesis, one can find a subset of `ℝ²` which, along each vertical line, only misses a countable set of points, while it is countable along each horizontal line. This is due to Sierpinski, and formalized in `sierpinski_pathological_family`. (In fact, Sierpinski proves that the existence of such a set is equivalent to the continuum hypothesis). Let `B` be the set of all bounded functions on `ℝ` (we are really talking about everywhere defined functions here). Define `f : ℝ → B` by taking `f x` to be the characteristic function of the vertical slice at position `x` of Sierpinski's set. It is our counterexample. To show that it is weakly measurable, we should consider `φ ∘ f` where `φ` is an arbitrary continuous linear form on `B`. There is no reasonable classification of such linear forms (they can be very wild). But if one restricts such a linear form to characteristic functions, one gets a finitely additive signed "measure". Such a "measure" can be decomposed into a discrete part (supported on a countable set) and a continuous part (giving zero mass to countable sets). For all but countably many points, `f x` will not intersect the discrete support of `φ` thanks to the definition of the Sierpinski set. This implies that `φ ∘ f` is constant outside of a countable set, and equal to the total mass of the continuous part of `φ` there. In particular, it is measurable (and its integral is the total mass of the continuous part of `φ`). Assume that `f` has a Pettis integral `g`. For all continuous linear form `φ`, then `φ g` should be the total mass of the continuous part of `φ`. Taking for `φ` the evaluation at the point `x` (which has no continuous part), one gets `g x = 0`. Take then for `φ` the Lebesgue integral on `[0, 1]` (or rather an arbitrary extension of Lebesgue integration to all bounded functions, thanks to Hahn-Banach). Then `φ g` should be the total mass of the continuous part of `φ`, which is `1`. This contradicts the fact that `g = 0`, and concludes the proof that `f` has no Pettis integral. ## Implementation notes The space of all bounded functions is defined as the space of all bounded continuous functions on a discrete copy of the original type, as mathlib only contains the space of all bounded continuous functions (which is the useful one). -/ universe u variables {α : Type u} open set bounded_continuous_function measure_theory open cardinal (aleph) open_locale cardinal bounded_continuous_function noncomputable theory /-- A copy of a type, endowed with the discrete topology -/ def discrete_copy (α : Type u) : Type u := α instance : topological_space (discrete_copy α) := ⊥ instance : discrete_topology (discrete_copy α) := ⟨rfl⟩ instance [inhabited α] : inhabited (discrete_copy α) := ⟨show α, from default⟩ namespace phillips_1940 /-! ### Extending the integral Thanks to Hahn-Banach, one can define a (non-canonical) continuous linear functional on the space of all bounded functions, coinciding with the integral on the integrable ones. -/ /-- The subspace of integrable functions in the space of all bounded functions on a type. This is a technical device, used to apply Hahn-Banach theorem to construct an extension of the integral to all bounded functions. -/ def bounded_integrable_functions [measurable_space α] (μ : measure α) : subspace ℝ (discrete_copy α →ᵇ ℝ) := { carrier := {f | integrable f μ}, zero_mem' := integrable_zero _ _ _, add_mem' := λ f g hf hg, integrable.add hf hg, smul_mem' := λ c f hf, integrable.smul c hf } /-- The integral, as a continuous linear map on the subspace of integrable functions in the space of all bounded functions on a type. This is a technical device, that we will extend through Hahn-Banach. -/ def bounded_integrable_functions_integral_clm [measurable_space α] (μ : measure α) [is_finite_measure μ] : bounded_integrable_functions μ →L[ℝ] ℝ := linear_map.mk_continuous { to_fun := λ f, ∫ x, f x ∂μ, map_add' := λ f g, integral_add f.2 g.2, map_smul' := λ c f, integral_smul _ _ } (μ univ).to_real begin assume f, rw mul_comm, apply norm_integral_le_of_norm_le_const, apply filter.eventually_of_forall, assume x, exact bounded_continuous_function.norm_coe_le_norm f x, end /-- Given a measure, there exists a continuous linear form on the space of all bounded functions (not necessarily measurable) that coincides with the integral on bounded measurable functions. -/ lemma exists_linear_extension_to_bounded_functions [measurable_space α] (μ : measure α) [is_finite_measure μ] : ∃ φ : (discrete_copy α →ᵇ ℝ) →L[ℝ] ℝ, ∀ (f : discrete_copy α →ᵇ ℝ), integrable f μ → φ f = ∫ x, f x ∂μ := begin rcases exists_extension_norm_eq _ (bounded_integrable_functions_integral_clm μ) with ⟨φ, hφ⟩, exact ⟨φ, λ f hf, hφ.1 ⟨f, hf⟩⟩, end /-- An arbitrary extension of the integral to all bounded functions, as a continuous linear map. It is not at all canonical, and constructed using Hahn-Banach. -/ def _root_.measure_theory.measure.extension_to_bounded_functions [measurable_space α] (μ : measure α) [is_finite_measure μ] : (discrete_copy α →ᵇ ℝ) →L[ℝ] ℝ := (exists_linear_extension_to_bounded_functions μ).some lemma extension_to_bounded_functions_apply [measurable_space α] (μ : measure α) [is_finite_measure μ] (f : discrete_copy α →ᵇ ℝ) (hf : integrable f μ) : μ.extension_to_bounded_functions f = ∫ x, f x ∂μ := (exists_linear_extension_to_bounded_functions μ).some_spec f hf /-! ### Additive measures on the space of all sets We define bounded finitely additive signed measures on the space of all subsets of a type `α`, and show that such an object can be split into a discrete part and a continuous part. -/ /-- A bounded signed finitely additive measure defined on *all* subsets of a type. -/ structure bounded_additive_measure (α : Type u) := (to_fun : set α → ℝ) (additive' : ∀ s t, disjoint s t → to_fun (s ∪ t) = to_fun s + to_fun t) (exists_bound : ∃ (C : ℝ), ∀ s, |to_fun s| ≤ C) instance : inhabited (bounded_additive_measure α) := ⟨{ to_fun := λ s, 0, additive' := λ s t hst, by simp, exists_bound := ⟨0, λ s, by simp⟩ }⟩ instance : has_coe_to_fun (bounded_additive_measure α) (λ _, set α → ℝ) := ⟨λ f, f.to_fun⟩ namespace bounded_additive_measure /-- A constant bounding the mass of any set for `f`. -/ def C (f : bounded_additive_measure α) := f.exists_bound.some lemma additive (f : bounded_additive_measure α) (s t : set α) (h : disjoint s t) : f (s ∪ t) = f s + f t := f.additive' s t h lemma abs_le_bound (f : bounded_additive_measure α) (s : set α) : |f s| ≤ f.C := f.exists_bound.some_spec s lemma le_bound (f : bounded_additive_measure α) (s : set α) : f s ≤ f.C := le_trans (le_abs_self _) (f.abs_le_bound s) @[simp] lemma empty (f : bounded_additive_measure α) : f ∅ = 0 := begin have : (∅ : set α) = ∅ ∪ ∅, by simp only [empty_union], apply_fun f at this, rwa [f.additive _ _ (empty_disjoint _), self_eq_add_left] at this, end instance : has_neg (bounded_additive_measure α) := ⟨λ f, { to_fun := λ s, - f s, additive' := λ s t hst, by simp only [f.additive s t hst, add_comm, neg_add_rev], exists_bound := ⟨f.C, λ s, by simp [f.abs_le_bound]⟩ }⟩ @[simp] lemma neg_apply (f : bounded_additive_measure α) (s : set α) : (-f) s = - (f s) := rfl /-- Restricting a bounded additive measure to a subset still gives a bounded additive measure. -/ def restrict (f : bounded_additive_measure α) (t : set α) : bounded_additive_measure α := { to_fun := λ s, f (t ∩ s), additive' := λ s s' h, begin rw [← f.additive (t ∩ s) (t ∩ s'), inter_union_distrib_left], exact h.mono (inter_subset_right _ _) (inter_subset_right _ _), end, exists_bound := ⟨f.C, λ s, f.abs_le_bound _⟩ } @[simp] lemma restrict_apply (f : bounded_additive_measure α) (s t : set α) : f.restrict s t = f (s ∩ t) := rfl /-- There is a maximal countable set of positive measure, in the sense that any countable set not intersecting it has nonpositive measure. Auxiliary lemma to prove `exists_discrete_support`. -/ lemma exists_discrete_support_nonpos (f : bounded_additive_measure α) : ∃ (s : set α), countable s ∧ (∀ t, countable t → f (t \ s) ≤ 0) := begin /- The idea of the proof is to construct the desired set inductively, adding at each step a countable set with close to maximal measure among those points that have not already been chosen. Doing this countably many steps will be enough. Indeed, otherwise, a remaining set would have positive measure `ε`. This means that at each step the set we have added also had a large measure, say at least `ε / 2`. After `n` steps, the set we have constructed has therefore measure at least `n * ε / 2`. This is a contradiction since the measures have to remain uniformly bounded. We argue from the start by contradiction, as this means that our inductive construction will never be stuck, so we won't have to consider this case separately. -/ by_contra' h, -- We will formulate things in terms of the type of countable subsets of `α`, as this is more -- convenient to formalize the inductive construction. let A : set (set α) := {t | countable t}, let empty : A := ⟨∅, countable_empty⟩, haveI : nonempty A := ⟨empty⟩, -- given a countable set `s`, one can find a set `t` in its complement with measure close to -- maximal. have : ∀ (s : A), ∃ (t : A), (∀ (u : A), f (u \ s) ≤ 2 * f (t \ s)), { assume s, have B : bdd_above (range (λ (u : A), f (u \ s))), { refine ⟨f.C, λ x hx, _⟩, rcases hx with ⟨u, hu⟩, rw ← hu, exact f.le_bound _ }, let S := supr (λ (t : A), f (t \ s)), have S_pos : 0 < S, { rcases h s.1 s.2 with ⟨t, t_count, ht⟩, apply ht.trans_le, let t' : A := ⟨t, t_count⟩, change f (t' \ s) ≤ S, exact le_csupr B t' }, rcases exists_lt_of_lt_csupr (half_lt_self S_pos) with ⟨t, ht⟩, refine ⟨t, λ u, _⟩, calc f (u \ s) ≤ S : le_csupr B _ ... = 2 * (S / 2) : by ring ... ≤ 2 * f (t \ s) : mul_le_mul_of_nonneg_left ht.le (by norm_num) }, choose! F hF using this, -- iterate the above construction, by adding at each step a set with measure close to maximal in -- the complement of already chosen points. This is the set `s n` at step `n`. let G : A → A := λ u, ⟨u ∪ F u, u.2.union (F u).2⟩, let s : ℕ → A := λ n, G^[n] empty, -- We will get a contradiction from the fact that there is a countable set `u` with positive -- measure in the complement of `⋃ n, s n`. rcases h (⋃ n, s n) (countable_Union (λ n, (s n).2)) with ⟨t, t_count, ht⟩, let u : A := ⟨t \ ⋃ n, s n, t_count.mono (diff_subset _ _)⟩, set ε := f u with hε, have ε_pos : 0 < ε := ht, have I1 : ∀ n, ε / 2 ≤ f (s (n+1) \ s n), { assume n, rw [div_le_iff' (show (0 : ℝ) < 2, by norm_num), hε], convert hF (s n) u using 3, { dsimp [u], ext x, simp only [not_exists, mem_Union, mem_diff], tauto }, { simp only [s, function.iterate_succ', subtype.coe_mk, union_diff_left] } }, have I2 : ∀ (n : ℕ), (n : ℝ) * (ε / 2) ≤ f (s n), { assume n, induction n with n IH, { simp only [s, bounded_additive_measure.empty, id.def, nat.cast_zero, zero_mul, function.iterate_zero, subtype.coe_mk], }, { have : (s (n+1) : set α) = (s (n+1) \ s n) ∪ s n, by simp only [s, function.iterate_succ', union_comm, union_diff_self, subtype.coe_mk, union_diff_left], rw [nat.succ_eq_add_one, this, f.additive], swap, { rw disjoint.comm, apply disjoint_diff }, calc ((n + 1) : ℝ) * (ε / 2) = ε / 2 + n * (ε / 2) : by ring ... ≤ f ((s (n + 1)) \ (s n)) + f (s n) : add_le_add (I1 n) IH } }, rcases exists_nat_gt (f.C / (ε / 2)) with ⟨n, hn⟩, have : (n : ℝ) ≤ f.C / (ε / 2), by { rw le_div_iff (half_pos ε_pos), exact (I2 n).trans (f.le_bound _) }, exact lt_irrefl _ (this.trans_lt hn), end lemma exists_discrete_support (f : bounded_additive_measure α) : ∃ (s : set α), countable s ∧ (∀ t, countable t → f (t \ s) = 0) := begin rcases f.exists_discrete_support_nonpos with ⟨s₁, s₁_count, h₁⟩, rcases (-f).exists_discrete_support_nonpos with ⟨s₂, s₂_count, h₂⟩, refine ⟨s₁ ∪ s₂, s₁_count.union s₂_count, λ t ht, le_antisymm _ _⟩, { have : t \ (s₁ ∪ s₂) = (t \ (s₁ ∪ s₂)) \ s₁, by rw [diff_diff, union_comm, union_assoc, union_self], rw this, exact h₁ _ (ht.mono (diff_subset _ _)) }, { have : t \ (s₁ ∪ s₂) = (t \ (s₁ ∪ s₂)) \ s₂, by rw [diff_diff, union_assoc, union_self], rw this, simp only [neg_nonpos, neg_apply] at h₂, exact h₂ _ (ht.mono (diff_subset _ _)) }, end /-- A countable set outside of which the measure gives zero mass to countable sets. We are not claiming this set is unique, but we make an arbitrary choice of such a set. -/ def discrete_support (f : bounded_additive_measure α) : set α := (exists_discrete_support f).some lemma countable_discrete_support (f : bounded_additive_measure α) : countable f.discrete_support := (exists_discrete_support f).some_spec.1 lemma apply_countable (f : bounded_additive_measure α) (t : set α) (ht : countable t) : f (t \ f.discrete_support) = 0 := (exists_discrete_support f).some_spec.2 t ht /-- The discrete part of a bounded additive measure, obtained by restricting the measure to its countable support. -/ def discrete_part (f : bounded_additive_measure α) : bounded_additive_measure α := f.restrict f.discrete_support /-- The continuous part of a bounded additive measure, giving zero measure to every countable set. -/ def continuous_part (f : bounded_additive_measure α) : bounded_additive_measure α := f.restrict (univ \ f.discrete_support) lemma eq_add_parts (f : bounded_additive_measure α) (s : set α) : f s = f.discrete_part s + f.continuous_part s := begin simp only [discrete_part, continuous_part, restrict_apply], rw [← f.additive, ← inter_distrib_right], { simp only [union_univ, union_diff_self, univ_inter] }, { have : disjoint f.discrete_support (univ \ f.discrete_support) := disjoint_diff, exact this.mono (inter_subset_left _ _) (inter_subset_left _ _) } end lemma discrete_part_apply (f : bounded_additive_measure α) (s : set α) : f.discrete_part s = f (f.discrete_support ∩ s) := rfl lemma continuous_part_apply_eq_zero_of_countable (f : bounded_additive_measure α) (s : set α) (hs : countable s) : f.continuous_part s = 0 := begin simp [continuous_part], convert f.apply_countable s hs using 2, ext x, simp [and_comm] end lemma continuous_part_apply_diff (f : bounded_additive_measure α) (s t : set α) (hs : countable s) : f.continuous_part (t \ s) = f.continuous_part t := begin conv_rhs { rw ← diff_union_inter t s }, rw [additive, self_eq_add_right], { exact continuous_part_apply_eq_zero_of_countable _ _ (hs.mono (inter_subset_right _ _)) }, { exact disjoint.mono_right (inter_subset_right _ _) (disjoint.comm.1 disjoint_diff) }, end end bounded_additive_measure open bounded_additive_measure section /-! ### Relationship between continuous functionals and finitely additive measures. -/ lemma norm_indicator_le_one (s : set α) (x : α) : ∥(indicator s (1 : α → ℝ)) x∥ ≤ 1 := by { simp only [indicator, pi.one_apply], split_ifs; norm_num } /-- A functional in the dual space of bounded functions gives rise to a bounded additive measure, by applying the functional to the indicator functions. -/ def _root_.continuous_linear_map.to_bounded_additive_measure [topological_space α] [discrete_topology α] (f : (α →ᵇ ℝ) →L[ℝ] ℝ) : bounded_additive_measure α := { to_fun := λ s, f (of_normed_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)), additive' := λ s t hst, begin have : of_normed_group_discrete (indicator (s ∪ t) 1) 1 (norm_indicator_le_one (s ∪ t)) = of_normed_group_discrete (indicator s 1) 1 (norm_indicator_le_one s) + of_normed_group_discrete (indicator t 1) 1 (norm_indicator_le_one t), by { ext x, simp [indicator_union_of_disjoint hst], }, rw [this, f.map_add], end, exists_bound := ⟨∥f∥, λ s, begin have I : ∥of_normed_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)∥ ≤ 1, by apply norm_of_normed_group_le _ zero_le_one, apply le_trans (f.le_op_norm _), simpa using mul_le_mul_of_nonneg_left I (norm_nonneg f), end⟩ } @[simp] lemma continuous_part_eval_clm_eq_zero [topological_space α] [discrete_topology α] (s : set α) (x : α) : (eval_clm ℝ x).to_bounded_additive_measure.continuous_part s = 0 := let f := (eval_clm ℝ x).to_bounded_additive_measure in calc f.continuous_part s = f.continuous_part (s \ {x}) : (continuous_part_apply_diff _ _ _ (countable_singleton x)).symm ... = f ((univ \ f.discrete_support) ∩ (s \ {x})) : rfl ... = indicator ((univ \ f.discrete_support) ∩ (s \ {x})) 1 x : rfl ... = 0 : by simp lemma to_functions_to_measure [measurable_space α] (μ : measure α) [is_finite_measure μ] (s : set α) (hs : measurable_set s) : μ.extension_to_bounded_functions.to_bounded_additive_measure s = (μ s).to_real := begin change μ.extension_to_bounded_functions (of_normed_group_discrete (indicator s (λ x, 1)) 1 (norm_indicator_le_one s)) = (μ s).to_real, rw extension_to_bounded_functions_apply, { change ∫ x, s.indicator (λ y, (1 : ℝ)) x ∂μ = _, simp [integral_indicator hs] }, { change integrable (indicator s 1) μ, have : integrable (λ x, (1 : ℝ)) μ := integrable_const (1 : ℝ), apply this.mono' (measurable.indicator (@measurable_const _ _ _ _ (1 : ℝ)) hs).ae_measurable, apply filter.eventually_of_forall, exact norm_indicator_le_one _ } end lemma to_functions_to_measure_continuous_part [measurable_space α] [measurable_singleton_class α] (μ : measure α) [is_finite_measure μ] [has_no_atoms μ] (s : set α) (hs : measurable_set s) : μ.extension_to_bounded_functions.to_bounded_additive_measure.continuous_part s = (μ s).to_real := begin let f := μ.extension_to_bounded_functions.to_bounded_additive_measure, change f ((univ \ f.discrete_support) ∩ s) = (μ s).to_real, rw to_functions_to_measure, swap, { exact measurable_set.inter (measurable_set.univ.diff (countable.measurable_set f.countable_discrete_support)) hs }, congr' 1, rw [inter_comm, ← inter_diff_assoc, inter_univ], exact measure_diff_null (f.countable_discrete_support.measure_zero _) end end /-! ### A set in `ℝ²` large along verticals, small along horizontals We construct a subset of `ℝ²`, given as a family of sets, which is large along verticals (i.e., it only misses a countable set along each vertical) but small along horizontals (it is countable along horizontals). Such a set can not be measurable as it would contradict Fubini theorem. We need the continuum hypothesis to construct it. -/ theorem sierpinski_pathological_family (Hcont : #ℝ = aleph 1) : ∃ (f : ℝ → set ℝ), (∀ x, countable (univ \ f x)) ∧ (∀ y, countable {x | y ∈ f x}) := begin rcases cardinal.ord_eq ℝ with ⟨r, hr, H⟩, resetI, refine ⟨λ x, {y | r x y}, λ x, _, λ y, _⟩, { have : univ \ {y | r x y} = {y | r y x} ∪ {x}, { ext y, simp only [true_and, mem_univ, mem_set_of_eq, mem_insert_iff, union_singleton, mem_diff], rcases trichotomous_of r x y with h|rfl|h, { simp only [h, not_or_distrib, false_iff, not_true], split, { rintros rfl, exact irrefl_of r y h }, { exact asymm h } }, { simp only [true_or, eq_self_iff_true, iff_true], exact irrefl x }, { simp only [h, iff_true, or_true], exact asymm h } }, rw this, apply countable.union _ (countable_singleton _), rw [cardinal.countable_iff_lt_aleph_one, ← Hcont], exact cardinal.card_typein_lt r x H }, { rw [cardinal.countable_iff_lt_aleph_one, ← Hcont], exact cardinal.card_typein_lt r y H } end /-- A family of sets in `ℝ` which only miss countably many points, but such that any point is contained in only countably many of them. -/ def spf (Hcont : #ℝ = aleph 1) (x : ℝ) : set ℝ := (sierpinski_pathological_family Hcont).some x lemma countable_compl_spf (Hcont : #ℝ = aleph 1) (x : ℝ) : countable (univ \ spf Hcont x) := (sierpinski_pathological_family Hcont).some_spec.1 x lemma countable_spf_mem (Hcont : #ℝ = aleph 1) (y : ℝ) : countable {x | y ∈ spf Hcont x} := (sierpinski_pathological_family Hcont).some_spec.2 y /-! ### A counterexample for the Pettis integral We construct a function `f` from `[0,1]` to a complete Banach space `B`, which is weakly measurable (i.e., for any continuous linear form `φ` on `B` the function `φ ∘ f` is measurable), bounded in norm (i.e., for all `x`, one has `∥f x∥ ≤ 1`), and still `f` has no Pettis integral. This construction, due to Phillips, requires the continuum hypothesis. We will take for `B` the space of all bounded functions on `ℝ`, with the supremum norm (no measure here, we are really talking of everywhere defined functions). And `f x` will be the characteristic function of a set which is large (it has countable complement), as in the Sierpinski pathological family. -/ /-- A family of bounded functions `f_x` from `ℝ` (seen with the discrete topology) to `ℝ` (in fact taking values in `{0, 1}`), indexed by a real parameter `x`, corresponding to the characteristic functions of the different fibers of the Sierpinski pathological family -/ def f (Hcont : #ℝ = aleph 1) (x : ℝ) : (discrete_copy ℝ →ᵇ ℝ) := of_normed_group_discrete (indicator (spf Hcont x) 1) 1 (norm_indicator_le_one _) lemma apply_f_eq_continuous_part (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) (x : ℝ) (hx : φ.to_bounded_additive_measure.discrete_support ∩ spf Hcont x = ∅) : φ (f Hcont x) = φ.to_bounded_additive_measure.continuous_part univ := begin set ψ := φ.to_bounded_additive_measure with hψ, have : φ (f Hcont x) = ψ (spf Hcont x) := rfl, have U : univ = spf Hcont x ∪ (univ \ spf Hcont x), by simp only [union_univ, union_diff_self], rw [this, eq_add_parts, discrete_part_apply, hx, ψ.empty, zero_add, U, ψ.continuous_part.additive _ _ (disjoint_diff), ψ.continuous_part_apply_eq_zero_of_countable _ (countable_compl_spf Hcont x), add_zero], end lemma countable_ne (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : countable {x | φ.to_bounded_additive_measure.continuous_part univ ≠ φ (f Hcont x)} := begin have A : {x | φ.to_bounded_additive_measure.continuous_part univ ≠ φ (f Hcont x)} ⊆ {x | φ.to_bounded_additive_measure.discrete_support ∩ spf Hcont x ≠ ∅}, { assume x hx, contrapose! hx, simp only [not_not, mem_set_of_eq] at hx, simp [apply_f_eq_continuous_part Hcont φ x hx], }, have B : {x | φ.to_bounded_additive_measure.discrete_support ∩ spf Hcont x ≠ ∅} ⊆ ⋃ y ∈ φ.to_bounded_additive_measure.discrete_support, {x | y ∈ spf Hcont x}, { assume x hx, dsimp at hx, rw [← ne.def, ne_empty_iff_nonempty] at hx, simp only [exists_prop, mem_Union, mem_set_of_eq], exact hx }, apply countable.mono (subset.trans A B), exact countable.bUnion (countable_discrete_support _) (λ a ha, countable_spf_mem Hcont a), end lemma comp_ae_eq_const (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : ∀ᵐ x ∂(volume.restrict (Icc (0 : ℝ) 1)), φ.to_bounded_additive_measure.continuous_part univ = φ (f Hcont x) := begin apply ae_restrict_of_ae, refine measure_mono_null _ ((countable_ne Hcont φ).measure_zero _), assume x, simp only [imp_self, mem_set_of_eq, mem_compl_eq], end lemma integrable_comp (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : integrable_on (λ x, φ (f Hcont x)) (Icc 0 1) := begin have : integrable_on (λ x, φ.to_bounded_additive_measure.continuous_part univ) (Icc (0 : ℝ) 1) volume, by simp [integrable_on_const], apply integrable.congr this (comp_ae_eq_const Hcont φ), end lemma integral_comp (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : ∫ x in Icc 0 1, φ (f Hcont x) = φ.to_bounded_additive_measure.continuous_part univ := begin rw ← integral_congr_ae (comp_ae_eq_const Hcont φ), simp, end /-! The next few statements show that the function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` takes its values in a complete space, is scalarly measurable, is everywhere bounded by `1`, and still has no Pettis integral. -/ example : complete_space (discrete_copy ℝ →ᵇ ℝ) := by apply_instance /-- The function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` is scalarly measurable. -/ lemma measurable_comp (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : measurable (λ x, φ (f Hcont x)) := begin have : measurable (λ x, φ.to_bounded_additive_measure.continuous_part univ) := measurable_const, refine this.measurable_of_countable_ne _, exact countable_ne Hcont φ, end /-- The function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` is uniformly bounded by `1` in norm. -/ lemma norm_bound (Hcont : #ℝ = aleph 1) (x : ℝ) : ∥f Hcont x∥ ≤ 1 := norm_of_normed_group_le _ zero_le_one _ /-- The function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` has no Pettis integral. -/ theorem no_pettis_integral (Hcont : #ℝ = aleph 1) : ¬ ∃ (g : discrete_copy ℝ →ᵇ ℝ), ∀ (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ), ∫ x in Icc 0 1, φ (f Hcont x) = φ g := begin rintros ⟨g, h⟩, simp only [integral_comp] at h, have : g = 0, { ext x, have : g x = eval_clm ℝ x g := rfl, rw [this, ← h], simp }, simp only [this, continuous_linear_map.map_zero] at h, specialize h (volume.restrict (Icc (0 : ℝ) 1)).extension_to_bounded_functions, simp_rw [to_functions_to_measure_continuous_part _ _ measurable_set.univ] at h, simpa using h, end end phillips_1940
101fcbd66b9c284bd45a24312fb7898497d40bc6
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/normed_space/normed_group_hom.lean
449507db6a02a3d9797807714cc77336c451d15d
[ "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
21,141
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import analysis.normed_space.basic import topology.sequences import topology.metric_space.isometry /-! # Normed groups homomorphisms This file gathers definitions and elementary constructions about bounded group homomorphisms between normed (abelian) groups (abbreviated to "normed group homs"). The main lemmas relate the boundedness condition to continuity and Lipschitzness. The main construction is to endow the type of normed group homs between two given normed groups with a group structure and a norm, giving rise to a normed group structure. Some easy other constructions are related to subgroups of normed groups. Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory of `semi_normed_group_hom` and we specialize to `normed_group_hom` when needed. -/ noncomputable theory open_locale nnreal big_operators /-- A morphism of seminormed abelian groups is a bounded group homomorphism. -/ structure normed_group_hom (V W : Type*) [semi_normed_group V] [semi_normed_group W] := (to_fun : V → W) (map_add' : ∀ v₁ v₂, to_fun (v₁ + v₂) = to_fun v₁ + to_fun v₂) (bound' : ∃ C, ∀ v, ∥to_fun v∥ ≤ C * ∥v∥) namespace add_monoid_hom variables {V W : Type*} [semi_normed_group V] [semi_normed_group W] {f g : normed_group_hom V W} /-- Associate to a group homomorphism a bounded group homomorphism under a norm control condition. See `add_monoid_hom.mk_normed_group_hom'` for a version that uses `ℝ≥0` for the bound. -/ def mk_normed_group_hom (f : V →+ W) (C : ℝ) (h : ∀ v, ∥f v∥ ≤ C * ∥v∥) : normed_group_hom V W := { bound' := ⟨C, h⟩, ..f } /-- Associate to a group homomorphism a bounded group homomorphism under a norm control condition. See `add_monoid_hom.mk_normed_group_hom` for a version that uses `ℝ` for the bound. -/ def mk_normed_group_hom' (f : V →+ W) (C : ℝ≥0) (hC : ∀ x, nnnorm (f x) ≤ C * nnnorm x) : normed_group_hom V W := { bound' := ⟨C, hC⟩ .. f} end add_monoid_hom lemma exists_pos_bound_of_bound {V W : Type*} [semi_normed_group V] [semi_normed_group W] {f : V → W} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ namespace normed_group_hom variables {V V₁ V₂ V₃ : Type*} variables [semi_normed_group V] [semi_normed_group V₁] [semi_normed_group V₂] [semi_normed_group V₃] variables {f g : normed_group_hom V₁ V₂} instance : has_coe_to_fun (normed_group_hom V₁ V₂) := ⟨_, normed_group_hom.to_fun⟩ initialize_simps_projections normed_group_hom (to_fun → apply) lemma coe_inj (H : ⇑f = g) : f = g := by cases f; cases g; congr'; exact funext H lemma coe_injective : @function.injective (normed_group_hom V₁ V₂) (V₁ → V₂) coe_fn := by apply coe_inj lemma coe_inj_iff : f = g ↔ ⇑f = g := ⟨congr_arg _, coe_inj⟩ @[ext] lemma ext (H : ∀ x, f x = g x) : f = g := coe_inj $ funext H lemma ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by rintro rfl x; refl, ext⟩ variables (f g) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f) (h₁) (h₂) (h₃) : ⇑(⟨f, h₁, h₂, h₃⟩ : normed_group_hom V₁ V₂) = f := rfl @[simp] lemma coe_mk_normed_group_hom (f : V₁ →+ V₂) (C) (hC) : ⇑(f.mk_normed_group_hom C hC) = f := rfl @[simp] lemma coe_mk_normed_group_hom' (f : V₁ →+ V₂) (C) (hC) : ⇑(f.mk_normed_group_hom' C hC) = f := rfl /-- The group homomorphism underlying a bounded group homomorphism. -/ def to_add_monoid_hom (f : normed_group_hom V₁ V₂) : V₁ →+ V₂ := add_monoid_hom.mk' f f.map_add' @[simp] lemma coe_to_add_monoid_hom : ⇑f.to_add_monoid_hom = f := rfl lemma to_add_monoid_hom_injective : function.injective (@normed_group_hom.to_add_monoid_hom V₁ V₂ _ _) := λ f g h, coe_inj $ show ⇑f.to_add_monoid_hom = g, by { rw h, refl } @[simp] lemma mk_to_add_monoid_hom (f) (h₁) (h₂) : (⟨f, h₁, h₂⟩ : normed_group_hom V₁ V₂).to_add_monoid_hom = add_monoid_hom.mk' f h₁ := rfl @[simp] lemma map_zero : f 0 = 0 := f.to_add_monoid_hom.map_zero @[simp] lemma map_add (x y) : f (x + y) = f x + f y := f.to_add_monoid_hom.map_add _ _ @[simp] lemma map_sum {ι : Type*} (v : ι → V₁) (s : finset ι) : f (∑ i in s, v i) = ∑ i in s, f (v i) := f.to_add_monoid_hom.map_sum _ _ @[simp] lemma map_sub (x y) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub _ _ @[simp] lemma map_neg (x) : f (-x) = -(f x) := f.to_add_monoid_hom.map_neg _ /-- Predicate asserting a norm bound on a normed group hom. -/ def bound_by (f : normed_group_hom V₁ V₂) (C : ℝ≥0) : Prop := ∀ x, ∥f x∥ ≤ C * ∥x∥ lemma mk_normed_group_hom'_bound_by (f : V₁ →+ V₂) (C) (hC) : (f.mk_normed_group_hom' C hC).bound_by C := hC lemma bound : ∃ C, 0 < C ∧ f.bound_by C := begin obtain ⟨C, hC⟩ := f.bound', rcases exists_pos_bound_of_bound _ hC with ⟨C', C'pos, hC'⟩, exact ⟨⟨C', C'pos.le⟩, C'pos, hC'⟩, end lemma lipschitz_of_bound_by (C : ℝ≥0) (h : f.bound_by C) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem antilipschitz_of_bound_by {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) protected lemma uniform_continuous (f : normed_group_hom V₁ V₂) : uniform_continuous f := let ⟨C, C_pos, hC⟩ := f.bound in (lipschitz_of_bound_by f C hC).uniform_continuous @[continuity] protected lemma continuous (f : normed_group_hom V₁ V₂) : continuous f := f.uniform_continuous.continuous /-! ### The operator norm -/ /-- The operator norm of a seminormed group homomorphism is the inf of all its bounds. -/ def op_norm (f : normed_group_hom V₁ V₂) := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (normed_group_hom V₁ V₂) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : normed_group_hom V₁ V₂} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : normed_group_hom V₁ V₂} : bdd_below {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := real.lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm (x : V₁) : ∥f x∥ ≤ ∥f∥ * ∥x∥ := begin obtain ⟨C, Cpos, hC⟩ := f.bound, replace hC := hC x, by_cases h : ∥x∥ = 0, { rwa [h, mul_zero] at ⊢ hC }, have hlt : 0 < ∥x∥ := lt_of_le_of_ne (norm_nonneg x) (ne.symm h), exact (div_le_iff hlt).mp ((real.le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc })), end theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : V₁) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm (x : V₁) : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_of_nonneg_of_le_mul (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := real.Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : normed_group_hom V₁ V₂} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 /-- If a bounded group homomorphism map is constructed from a group homomorphism via the constructor `mk_normed_group_hom`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma mk_normed_group_hom_norm_le (f : V₁ →+ V₂) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_normed_group_hom C h∥ ≤ C := op_norm_le_bound _ hC h /-- If a bounded group homomorphism map is constructed from a group homomorphism via the constructor `mk_normed_group_hom`, then its norm is bounded by the bound given to the constructor or zero if this bound is negative. -/ lemma mk_normed_group_hom_norm_le' (f : V₁ →+ V₂) {C : ℝ} (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_normed_group_hom C h∥ ≤ max C 0 := op_norm_le_bound _ (le_max_right _ _) $ λ x, (h x).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg x) alias mk_normed_group_hom_norm_le ← add_monoid_hom.mk_normed_group_hom_norm_le alias mk_normed_group_hom_norm_le' ← add_monoid_hom.mk_normed_group_hom_norm_le' /-! ### Addition of normed group homs -/ /-- Addition of normed group homs. -/ instance : has_add (normed_group_hom V₁ V₂) := ⟨λ f g, (f.to_add_monoid_hom + g.to_add_monoid_hom).mk_normed_group_hom (∥f∥ + ∥g∥) $ λ v, calc ∥f v + g v∥ ≤ ∥f v∥ + ∥g v∥ : norm_add_le _ _ ... ≤ ∥f∥ * ∥v∥ + ∥g∥ * ∥v∥ : add_le_add (le_op_norm f v) (le_op_norm g v) ... = (∥f∥ + ∥g∥) * ∥v∥ : by rw add_mul⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := mk_normed_group_hom_norm_le _ (add_nonneg (op_norm_nonneg _) (op_norm_nonneg _)) _ /-- Terms containing `@has_add.add (has_coe_to_fun.F ...) pi.has_add` seem to cause leanchecker to [crash due to an out-of-memory condition](https://github.com/leanprover-community/lean/issues/543). As a workaround, we add a type annotation: `(f + g : V₁ → V₂)` -/ library_note "addition on function coercions" -- see Note [addition on function coercions] @[simp] lemma coe_add (f g : normed_group_hom V₁ V₂) : ⇑(f + g) = (f + g : V₁ → V₂) := rfl @[simp] lemma add_apply (f g : normed_group_hom V₁ V₂) (v : V₁) : (f + g : normed_group_hom V₁ V₂) v = f v + g v := rfl /-! ### The zero normed group hom -/ instance : has_zero (normed_group_hom V₁ V₂) := ⟨(0 : V₁ →+ V₂).mk_normed_group_hom 0 (by simp)⟩ instance : inhabited (normed_group_hom V₁ V₂) := ⟨0⟩ /-- The norm of the `0` operator is `0`. -/ theorem op_norm_zero : ∥(0 : normed_group_hom V₁ V₂)∥ = 0 := le_antisymm (real.Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul], exact norm_zero })⟩) (op_norm_nonneg _) /-- For normed groups, an operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff {V₁ V₂ : Type*} [normed_group V₁] [normed_group V₂] {f : normed_group_hom V₁ V₂} : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, by rw [hf, op_norm_zero] ) -- see Note [addition on function coercions] @[simp] lemma coe_zero : ⇑(0 : normed_group_hom V₁ V₂) = (0 : V₁ → V₂) := rfl @[simp] lemma zero_apply (v : V₁) : (0 : normed_group_hom V₁ V₂) v = 0 := rfl variables {f g} /-! ### The identity normed group hom -/ /-- The identity as a continuous normed group hom. -/ @[simps] def id : normed_group_hom V V := (add_monoid_hom.id V).mk_normed_group_hom 1 (by simp [le_refl]) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the norm of every element vanishes, where it is `0`. (Since we are working with seminorms this can happen even if the space is non-trivial.) It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥(id : normed_group_hom V V)∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If there is an element with norm different from `0`, then the norm of the identity equals `1`. (Since we are working with seminorms supposing that the space is non-trivial is not enough.) -/ lemma norm_id_of_nontrivial_seminorm (h : ∃ (x : V), ∥x∥ ≠ 0 ) : ∥(id : normed_group_hom V V)∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := h in have _ := (id : normed_group_hom V V).ratio_le_op_norm x, by rwa [id_apply, div_self hx] at this /-- If a normed space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id {V : Type*} [normed_group V] [nontrivial V] : ∥(id : normed_group_hom V V)∥ = 1 := begin refine norm_id_of_nontrivial_seminorm _, obtain ⟨x, hx⟩ := exists_ne (0 : V), exact ⟨x, ne_of_gt (norm_pos_iff.2 hx)⟩, end /-! ### The negation of a normed group hom -/ /-- Opposite of a normed group hom. -/ instance : has_neg (normed_group_hom V₁ V₂) := ⟨λ f, (-f.to_add_monoid_hom).mk_normed_group_hom (∥f∥) (λ v, by simp [le_op_norm f v])⟩ -- see Note [addition on function coercions] @[simp] lemma coe_neg (f : normed_group_hom V₁ V₂) : ⇑(-f) = (-f : V₁ → V₂) := rfl @[simp] lemma neg_apply (f : normed_group_hom V₁ V₂) (v : V₁) : (-f : normed_group_hom V₁ V₂) v = - (f v) := rfl lemma op_norm_neg (f : normed_group_hom V₁ V₂) : ∥-f∥ = ∥f∥ := by simp only [norm_def, coe_neg, norm_neg, pi.neg_apply] /-! ### Subtraction of normed group homs -/ /-- Subtraction of normed group homs. -/ instance : has_sub (normed_group_hom V₁ V₂) := ⟨λ f g, { bound' := begin simp only [add_monoid_hom.sub_apply, add_monoid_hom.to_fun_eq_coe, sub_eq_add_neg], exact (f + -g).bound' end, .. (f.to_add_monoid_hom - g.to_add_monoid_hom) }⟩ -- see Note [addition on function coercions] @[simp] lemma coe_sub (f g : normed_group_hom V₁ V₂) : ⇑(f - g) = (f - g : V₁ → V₂) := rfl @[simp] lemma sub_apply (f g : normed_group_hom V₁ V₂) (v : V₁) : (f - g : normed_group_hom V₁ V₂) v = f v - g v := rfl /-! ### Normed group structure on normed group homs -/ /-- Homs between two given normed groups form a commutative additive group. -/ instance : add_comm_group (normed_group_hom V₁ V₂) := coe_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- Normed group homomorphisms themselves form a seminormed group with respect to the operator norm. -/ instance to_semi_normed_group : semi_normed_group (normed_group_hom V₁ V₂) := semi_normed_group.of_core _ ⟨op_norm_zero, op_norm_add_le, op_norm_neg⟩ /-- Normed group homomorphisms themselves form a normed group with respect to the operator norm. -/ instance to_normed_group {V₁ V₂ : Type*} [normed_group V₁] [normed_group V₂] : normed_group (normed_group_hom V₁ V₂) := normed_group.of_core _ ⟨λ f, op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ /-- Coercion of a `normed_group_hom` is an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn` -/ @[simps] def coe_fn_add_hom : normed_group_hom V₁ V₂ →+ (V₁ → V₂) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add} @[simp] lemma coe_sum {ι : Type*} (s : finset ι) (f : ι → normed_group_hom V₁ V₂) : ⇑(∑ i in s, f i) = ∑ i in s, (f i) := (coe_fn_add_hom : _ →+ (V₁ → V₂)).map_sum f s lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → normed_group_hom V₁ V₂) (v : V₁) : (∑ i in s, f i) v = ∑ i in s, (f i v) := by simp only [coe_sum, finset.sum_apply] /-! ### Composition of normed group homs -/ /-- The composition of continuous normed group homs. -/ @[simps] protected def comp (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) : normed_group_hom V₁ V₃ := (g.to_add_monoid_hom.comp f.to_add_monoid_hom).mk_normed_group_hom (∥g∥ * ∥f∥) $ λ v, calc ∥g (f v)∥ ≤ ∥g∥ * ∥f v∥ : le_op_norm _ _ ... ≤ ∥g∥ * (∥f∥ * ∥v∥) : mul_le_mul_of_nonneg_left (le_op_norm _ _) (op_norm_nonneg _) ... = ∥g∥ * ∥f∥ * ∥v∥ : by rw mul_assoc lemma norm_comp_le (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) : ∥g.comp f∥ ≤ ∥g∥ * ∥f∥ := mk_normed_group_hom_norm_le _ (mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _)) _ /-- Composition of normed groups hom as an additive group morphism. -/ def comp_hom : (normed_group_hom V₂ V₃) →+ (normed_group_hom V₁ V₂) →+ (normed_group_hom V₁ V₃) := add_monoid_hom.mk' (λ g, add_monoid_hom.mk' (λ f, g.comp f) (by { intros, ext, exact g.map_add _ _ })) (by { intros, ext, simp only [comp_apply, pi.add_apply, function.comp_app, add_monoid_hom.add_apply, add_monoid_hom.coe_mk', coe_add] }) @[simp] lemma comp_zero (f : normed_group_hom V₂ V₃) : f.comp (0 : normed_group_hom V₁ V₂) = 0 := by { ext, exact f.map_zero } @[simp] lemma zero_comp (f : normed_group_hom V₁ V₂) : (0 : normed_group_hom V₂ V₃).comp f = 0 := by { ext, refl } end normed_group_hom namespace normed_group_hom variables {V W V₁ V₂ V₃ : Type*} variables [semi_normed_group V] [semi_normed_group W] [semi_normed_group V₁] [semi_normed_group V₂] [semi_normed_group V₃] /-- The inclusion of an `add_subgroup`, as bounded group homomorphism. -/ @[simps] def incl (s : add_subgroup V) : normed_group_hom s V := { to_fun := (coe : s → V), map_add' := λ v w, add_subgroup.coe_add _ _ _, bound' := ⟨1, λ v, by { rw [one_mul], refl }⟩ } /-!### Kernel -/ section kernels variables (f : normed_group_hom V₁ V₂) (g : normed_group_hom V₂ V₃) /-- The kernel of a bounded group homomorphism. Naturally endowed with a `semi_normed_group` instance. -/ def ker : add_subgroup V₁ := f.to_add_monoid_hom.ker lemma mem_ker (v : V₁) : v ∈ f.ker ↔ f v = 0 := by { erw f.to_add_monoid_hom.mem_ker, refl } /-- Given a normed group hom `f : V₁ → V₂` satisfying `g.comp f = 0` for some `g : V₂ → V₃`, the corestriction of `f` to the kernel of `g`. -/ @[simps] def ker.lift (h : g.comp f = 0) : normed_group_hom V₁ g.ker := { to_fun := λ v, ⟨f v, by { erw g.mem_ker, show (g.comp f) v = 0, rw h, refl }⟩, map_add' := λ v w, by { simp only [map_add], refl }, bound' := f.bound' } @[simp] lemma ker.incl_comp_lift (h : g.comp f = 0) : (incl g.ker).comp (ker.lift f g h) = f := by { ext, refl } end kernels /-! ### Range -/ section range variables (f : normed_group_hom V₁ V₂) (g : normed_group_hom V₂ V₃) /-- The image of a bounded group homomorphism. Naturally endowed with a `semi_normed_group` instance. -/ def range : add_subgroup V₂ := f.to_add_monoid_hom.range lemma mem_range (v : V₂) : v ∈ f.range ↔ ∃ w, f w = v := by { rw [range, add_monoid_hom.mem_range], refl } end range variables {f : normed_group_hom V W} /-- A `normed_group_hom` is *norm-nonincreasing* if `∥f v∥ ≤ ∥v∥` for all `v`. -/ def norm_noninc (f : normed_group_hom V W) : Prop := ∀ v, ∥f v∥ ≤ ∥v∥ namespace norm_noninc lemma bound_by_one (hf : f.norm_noninc) : f.bound_by 1 := λ v, by simpa only [one_mul, nnreal.coe_one] using hf v lemma id : (id : normed_group_hom V V).norm_noninc := λ v, le_rfl lemma comp {g : normed_group_hom V₂ V₃} {f : normed_group_hom V₁ V₂} (hg : g.norm_noninc) (hf : f.norm_noninc) : (g.comp f).norm_noninc := λ v, (hg (f v)).trans (hf v) end norm_noninc section isometry lemma isometry_iff_norm (f : normed_group_hom V W) : isometry f ↔ ∀ v, ∥f v∥ = ∥v∥ := add_monoid_hom.isometry_iff_norm f.to_add_monoid_hom lemma isometry_of_norm (f : normed_group_hom V W) (hf : ∀ v, ∥f v∥ = ∥v∥) : isometry f := f.isometry_iff_norm.mpr hf lemma norm_eq_of_isometry {f : normed_group_hom V W} (hf : isometry f) (v : V) : ∥f v∥ = ∥v∥ := f.isometry_iff_norm.mp hf v lemma isometry_id : @isometry V V _ _ (id : normed_group_hom V V) := isometry_id lemma isometry_comp {g : normed_group_hom V₂ V₃} {f : normed_group_hom V₁ V₂} (hg : isometry g) (hf : isometry f) : isometry (g.comp f) := hg.comp hf lemma norm_noninc_of_isometry (hf : isometry f) : f.norm_noninc := λ v, le_of_eq $ norm_eq_of_isometry hf v lemma bound_by_one_of_isometry (hf : isometry f) : f.bound_by 1 := (norm_noninc_of_isometry hf).bound_by_one end isometry end normed_group_hom
43df151f9d7885ffae0eebb4e5f3e32a65cdb33a
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/match_tac3.lean
efc05ea4d1f82821532c338867ec5975d4d91961
[ "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
230
lean
import data.nat open nat theorem tst (a b : nat) (H : a = 0) : a + b = b := begin revert H, match a with | zero := λ H, by rewrite zero_add | (n+1) := λ H, nat.no_confusion H end end reveal tst print definition tst
4ba7be6b4f906f5f79c4b68a915f61d0124c438d
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Mathlib/NormCast.lean
8a4b76ec88da9f9ffdf5b42f7c87e12a8cd269ed
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
1,639
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Basic import Mathport.Syntax.Translate.Tactic.Lean3 open Lean namespace Mathport.Translate.Tactic open Parser -- # tactic.norm_cast @[tr_user_attr norm_cast] def trNormCastAttr : Parse1 Syntax.Attr := parse1 (ident)? fun | some `elim => `(attr| norm_cast elim) | some `move => `(attr| norm_cast move) | some `squash => `(attr| norm_cast squash) | none => `(attr| norm_cast) | _ => warn! "unsupported (impossible)" @[tr_tactic push_cast] def trPushCast : TacM Syntax.Tactic := do let hs := (← trSimpArgs (← parse simpArgList)).asNonempty let loc ← trLoc (← parse location) `(tactic| push_cast $[[$hs,*]]? $[$loc:location]?) @[tr_tactic norm_cast] def trNormCast : TacM Syntax.Tactic := do `(tactic| norm_cast $(← trLoc (← parse location))?) @[tr_tactic rw_mod_cast] def trRwModCast : TacM Syntax.Tactic := do `(tactic| rw_mod_cast [$(← liftM $ (← parse rwRules).mapM trRwRule),*] $(← trLoc (← parse location))?) @[tr_tactic exact_mod_cast] def trExactModCast : TacM Syntax.Tactic := do `(tactic| exact_mod_cast $(← trExpr (← parse pExpr))) @[tr_tactic apply_mod_cast] def trApplyModCast : TacM Syntax.Tactic := do `(tactic| apply_mod_cast $(← trExpr (← parse pExpr))) @[tr_tactic assumption_mod_cast] def trAssumptionModCast : TacM Syntax.Tactic := do `(tactic| assumption_mod_cast) @[tr_conv norm_cast] def trNormCastConv : TacM Syntax.Conv := `(conv| norm_cast)
7c3883b27c01d8ecb33fd65d37847d1422f37ac6
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/non_exhaustive_error.lean
b95ed33a3959221069d0bb2a38e9b4267a314438
[ "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
88
lean
definition f : string → nat → bool | "hello world" 1 := tt | "bye" _ := tt
359ba5b9670615911102e6e42903c335fe00b7dd
274748215b6d042f0d9c9a505f9551fa8e0c5f38
/src/affine_algebraic_set/lattice.lean
210c22a5774f0b2cd4c36f635c6d9f2188c0e26c
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M4P33
878ecb515c77d20cc799ff1ebd78f1bf4fd65c12
1a179372db71ad6802d11eacbc1f02f327d55f8f
refs/heads/master
1,607,519,867,193
1,583,344,297,000
1,583,344,297,000
233,316,107
59
4
Apache-2.0
1,579,285,778,000
1,578,788,367,000
Lean
UTF-8
Lean
false
false
732
lean
/- The lattice structure on affine algebraic subsets of kⁿ Kevin Buzzard -/ import affine_algebraic_set.basic -- the basic theory of affine algebraic sets. import affine_algebraic_set.union /- # The lattice structure on `affine_algebraic_set k n`. Lean level: hard. Let k be a field and let n be a natural number. We put the structure of a semilattice_sup on the type of affine algebraic subsets of kⁿ. ## References Martin Orr's lecture notes at https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/ ## Tags algebraic geometry, algebraic variety -/ -- end of docstring; code starts here. -- affine algebraic sets are a semilattice_sup -- instance : semilattice_sup (affine_algebraic_set k n) := sorry
57b23424419c317c2b019f17dbfeb2c3a9c49859
bdb33f8b7ea65f7705fc342a178508e2722eb851
/tactic/default.lean
ff3917dfa3bfa77430433dbb2bd9c412c6ac25e1
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
53
lean
import tactic.interactive tactic.alias tactic.finish
735c821c67d32ee7b8efdf160eb7179efc09b99d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/omega/nat/preterm.lean
2343c6361adedb3f9e84ab29fdb796786ccb3a84
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,882
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Linear natural number arithmetic terms in pre-normalized form. -/ import tactic.omega.term open tactic namespace omega namespace nat /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `5` is reified to `cst 5`) and all other atomic terms are reified to `exp` (e.g., `5 * (list.length l)` is reified to `exp 5 \`(list.length l)`). `exp` accepts a coefficient of type `nat` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : nat → exprterm | exp : nat → expr → exprterm | add : exprterm → exprterm → exprterm | sub : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive decidable_eq, derive inhabited] inductive preterm : Type | cst : nat → preterm | var : nat → nat → preterm | add : preterm → preterm → preterm | sub : preterm → preterm → preterm localized "notation `&` k := omega.nat.preterm.cst k" in omega.nat localized "infix ` ** ` : 300 := omega.nat.preterm.var" in omega.nat localized "notation t ` +* ` s := omega.nat.preterm.add t s" in omega.nat localized "notation t ` -* ` s := omega.nat.preterm.sub t s" in omega.nat namespace preterm /-- Helper tactic for proof by induction over preterms -/ meta def induce (tac : tactic unit := tactic.skip) : tactic unit := `[ intro t, induction t with m m n t s iht ihs t s iht ihs; tac] /-- Preterm evaluation -/ def val (v : nat → nat) : preterm → nat | (& i) := i | (i ** n) := if i = 1 then v n else (v n) * i | (t1 +* t2) := t1.val + t2.val | (t1 -* t2) := t1.val - t2.val @[simp] lemma val_const {v : nat → nat} {m : nat} : (& m).val v = m := rfl @[simp] lemma val_var {v : nat → nat} {m n : nat} : (m ** n).val v = m * (v n) := begin simp only [val], by_cases h1 : m = 1, rw [if_pos h1, h1, one_mul], rw [if_neg h1, mul_comm], end @[simp] lemma val_add {v : nat → nat} {t s : preterm} : (t +* s).val v = t.val v + s.val v := rfl @[simp] lemma val_sub {v : nat → nat} {t s : preterm} : (t -* s).val v = t.val v - s.val v := rfl /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index | (t1 -* t2) := max t1.fresh_index t2.fresh_index /-- If variable assignments `v` and `w` agree on all variables that occur in term `t`, the value of `t` under `v` and `w` are identical. -/ lemma val_constant (v w : nat → nat) : ∀ t : preterm, (∀ x < t.fresh_index, v x = w x) → t.val v = t.val w | (& n) h1 := rfl | (m ** n) h1 := begin simp only [val_var], apply congr_arg (λ y, m * y), apply h1 _ (lt_add_one _) end | (t +* s) h1 := begin simp only [val_add], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end | (t -* s) h1 := begin simp only [val_sub], have ht := val_constant t (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_left _ _))), have hs := val_constant s (λ x hx, h1 _ (lt_of_lt_of_le hx (le_max_right _ _))), rw [ht, hs] end def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" | (t1 -* t2) := "(" ++ t1.repr ++ " - " ++ t2.repr ++ ")" @[simp] def add_one (t : preterm) : preterm := t +* (&1) /-- Preterm is free of subtractions -/ def sub_free : preterm → Prop | (& m) := true | (m ** n) := true | (t +* s) := t.sub_free ∧ s.sub_free | (_ -* _) := false end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& m) := ⟨↑m, []⟩ | (m ** n) := ⟨0, [] {n ↦ ↑m}⟩ | (t +* s) := term.add (canonize t) (canonize s) | (_ -* _) := ⟨0, []⟩ @[simp] lemma val_canonize {v : nat → nat} : ∀ {t : preterm}, t.sub_free → (canonize t).val (λ x, ↑(v x)) = t.val v | (& i) h1 := by simp only [canonize, preterm.val_const, term.val, coeffs.val_nil, add_zero] | (i ** n) h1 := by simp only [preterm.val_var, coeffs.val_set, term.val, zero_add, int.coe_nat_mul, canonize] | (t +* s) h1 := by simp only [val_canonize h1.left, val_canonize h1.right, int.coe_nat_add, canonize, term.val_add, preterm.val_add] end nat end omega
1759b96d27f6d00d679610ba75ef01ae2432b6d5
d1bbf1801b3dcb214451d48214589f511061da63
/src/linear_algebra/char_poly/coeff.lean
e5e225f7c39ef760297eb131a60b48a272229dd5
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,973
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark. -/ import data.matrix.char_p import linear_algebra.char_poly.basic import linear_algebra.matrix import ring_theory.polynomial.basic import algebra.polynomial.big_operators import group_theory.perm.cycles import field_theory.finite.basic /-! # Characteristic polynomials We give methods for computing coefficients of the characteristic polynomial. ## Main definitions - `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial over a nonzero ring is the dimension of the matrix - `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the characteristic polynomial, up to sign. - `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the characteristic polynomial, where d is the dimension of the matrix. For a nonzero ring, this is the second-highest coefficient. -/ noncomputable theory universes u v w z open polynomial matrix open_locale big_operators variables {R : Type u} [comm_ring R] variables {n G : Type v} [decidable_eq n] [fintype n] variables {α β : Type v} [decidable_eq α] open finset open polynomial variable {M : matrix n n R} lemma char_matrix_apply_nat_degree [nontrivial R] (i j : n) : (char_matrix M i j).nat_degree = ite (i = j) 1 0 := by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], } lemma char_matrix_apply_nat_degree_le (i j : n) : (char_matrix M i j).nat_degree ≤ ite (i = j) 1 0 := by split_ifs; simp [h, nat_degree_X_sub_C_le] variable (M) lemma char_poly_sub_diagonal_degree_lt : (char_poly M - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) := begin rw [char_poly, det, ← insert_erase (mem_univ (equiv.refl n)), sum_insert (not_mem_erase (equiv.refl n) univ), add_comm], simp only [char_matrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one, units.coe_one, add_sub_cancel, equiv.coe_refl], rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)), intros c hc, rw [← C_eq_int_cast, C_mul'], apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c), rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe, apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)), apply le_trans (polynomial.nat_degree_prod_le univ (λ i : n, (char_matrix M (c i) i))) _, rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum, intros, apply char_matrix_apply_nat_degree_le, end lemma char_poly_coeff_eq_prod_coeff_of_le {k : ℕ} (h : fintype.card n - 1 ≤ k) : (char_poly M).coeff k = (∏ i : n, (X - C (M i i))).coeff k := begin apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt, apply lt_of_lt_of_le (char_poly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h, end lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 := by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext, tauto } theorem char_poly_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).degree = fintype.card n := begin by_cases fintype.card n = 0, { rw h, unfold char_poly, rw det_of_card_zero, {simp}, {assumption} }, rw ← sub_add_cancel (char_poly M) (∏ (i : n), (X - C (M i i))), have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n, { rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h, rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp, simp_rw (monic_X_sub_C _).leading_coeff, simp, }, rw degree_add_eq_right_of_degree_lt, exact h1, rw h1, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem char_poly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).nat_degree = fintype.card n := nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M) lemma char_poly_monic (M : matrix n n R) : monic (char_poly M) := begin nontriviality, by_cases fintype.card n = 0, {rw [char_poly, det_of_card_zero h], apply monic_one}, have mon : (∏ (i : n), (X - C (M i i))).monic, { apply monic_prod_of_monic univ (λ i : n, (X - C (M i i))), simp [monic_X_sub_C], }, rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) (char_poly M) at mon, rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon, rw char_poly_degree_eq_dim, rw ← neg_sub, rw degree_neg, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem trace_eq_neg_char_poly_coeff [nonempty n] (M : matrix n n R) : (matrix.trace n R R) M = -(char_poly M).coeff (fintype.card n - 1) := begin nontriviality, rw char_poly_coeff_eq_prod_coeff_of_le, swap, refl, rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (λ i : n, M i i)], simp, rw [← fintype.card, fintype.card_pos_iff], apply_instance, end -- I feel like this should use polynomial.alg_hom_eval₂_algebra_map lemma mat_poly_equiv_eval (M : matrix n n (polynomial R)) (r : R) (i j : n) : (mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r := begin unfold polynomial.eval, unfold eval₂, transitivity finsupp.sum (mat_poly_equiv M) (λ (e : ℕ) (a : matrix n n R), (a * (scalar n) r ^ e) i j), { unfold finsupp.sum, rw sum_apply, rw sum_apply, dsimp, refl, }, { simp_rw ← (scalar n).map_pow, simp_rw ← (matrix.scalar.commute _ _).eq, simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply, smul_apply, mul_eq_mul, algebra.smul_mul_assoc], have h : ∀ x : ℕ, (λ (e : ℕ) (a : R), r ^ e * a) x 0 = 0 := by simp, symmetry, rw ← finsupp.sum_map_range_index h, swap, refl, refine congr (congr rfl _) (by {ext, rw mul_comm}), ext, rw finsupp.map_range_apply, simp [apply_eq_coeff], } end lemma eval_det (M : matrix n n (polynomial R)) (r : R) : polynomial.eval r M.det = (polynomial.eval (matrix.scalar n r) (mat_poly_equiv M)).det := begin rw [polynomial.eval, ← coe_eval₂_ring_hom, ring_hom.map_det], apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _, end theorem det_eq_sign_char_poly_coeff (M : matrix n n R) : M.det = (-1)^(fintype.card n) * (char_poly M).coeff 0:= begin rw [coeff_zero_eq_eval_zero, char_poly, eval_det, mat_poly_equiv_char_matrix, ← det_smul], simp end variables {p : ℕ} [fact p.prime] @[simp] lemma finite_field.char_poly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : char_poly (M ^ (fintype.card K)) = char_poly M := begin by_cases hn : nonempty n, { letI := hn, cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩, letI : fact p.prime := hp, dsimp at hk, rw hk at *, apply (frobenius_inj (polynomial K) p).iterate k, repeat { rw iterate_frobenius, rw ← hk }, rw ← finite_field.expand_card, unfold char_poly, rw [alg_hom.map_det, ← is_monoid_hom.map_pow], apply congr_arg det, apply mat_poly_equiv.injective, swap, { apply_instance }, rw [← mat_poly_equiv.coe_alg_hom, alg_hom.map_pow, mat_poly_equiv.coe_alg_hom, mat_poly_equiv_char_matrix, hk, sub_pow_char_pow_of_commute, ← C_pow], swap, { apply polynomial.commute_X }, -- the following is a nasty case bash that should be abstracted as a lemma -- (and maybe it can be proven more... algebraically?) ext, rw [coeff_sub, coeff_C], by_cases hij : i = j; simp [char_matrix, hij, coeff_X_pow]; simp only [coeff_C]; split_ifs; simp *, }, { congr, apply @subsingleton.elim _ (subsingleton_of_empty_left hn) _ _, }, end @[simp] lemma zmod.char_poly_pow_card (M : matrix n n (zmod p)) : char_poly (M ^ p) = char_poly M := by { have h := finite_field.char_poly_pow_card M, rwa zmod.card at h, } lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] [nonempty n] (M : matrix n n K) : trace n K K (M ^ (fintype.card K)) = (trace n K K M) ^ (fintype.card K) := by rw [trace_eq_neg_char_poly_coeff, trace_eq_neg_char_poly_coeff, finite_field.char_poly_pow_card, finite_field.pow_card] lemma zmod.trace_pow_card {p:ℕ} [fact p.prime] [nonempty n] (M : matrix n n (zmod p)) : trace n (zmod p) (zmod p) (M ^ p) = (trace n (zmod p) (zmod p) M)^p := by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, } namespace matrix theorem is_integral : is_integral R M := ⟨char_poly M, ⟨char_poly_monic M, aeval_self_char_poly M⟩⟩ theorem min_poly_dvd_char_poly {K : Type*} [field K] (M : matrix n n K) : (minpoly M.is_integral) ∣ char_poly M := minpoly.dvd M.is_integral (aeval_self_char_poly M) end matrix
5583b59fe2805e8f26c6bbbda82247f9166bfd57
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/continued_fractions/computation/terminates_iff_rat.lean
ae7a918728e6bddd827b57c389144e3eddf72af7
[ "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
14,462
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.approximations import algebra.continued_fractions.computation.correctness_terminating import data.rat /-! # Termination of Continued Fraction Computations (`gcf.of`) ## Summary We show that the continued fraction for a value `v`, as defined in `algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a rational number, that is `↑v = q` for some `q : ℚ`. ## Main Theorems - `generalized_continued_fraction.coe_of_rat` shows that `generalized_continued_fraction.of v = generalized_continued_fraction.of q` for `v : α` given that `↑v = q` and `q : ℚ`. - `generalized_continued_fraction.terminates_iff_rat` shows that `generalized_continued_fraction.of v` terminates if and only if `↑v = q` for some `q : ℚ`. ## Tags rational, continued fraction, termination -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {K : Type*} [linear_ordered_field K] [floor_ring K] /- We will have to constantly coerce along our structures in the following proofs using their provided map functions. -/ local attribute [simp] gcf.pair.map gcf.int_fract_pair.mapFr section rat_of_terminates /-! ### Terminating Continued Fractions Are Rational We want to show that the computation of a continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right. We first show that every finite convergent corresponds to a rational number `q` and then use the finite correctness proof (`of_correctness_of_terminates`) of `generalized_continued_fraction.of` to show that `v = ↑q`. -/ variables (v : K) (n : ℕ) lemma exists_gcf_pair_rat_eq_of_nth_conts_aux : ∃ (conts : gcf.pair ℚ), (gcf.of v).continuants_aux n = (conts.map coe : gcf.pair K) := nat.strong_induction_on n begin clear n, let g := gcf.of v, assume n IH, rcases n with _|_|n, -- n = 0 { suffices : ∃ (gp : gcf.pair ℚ), gcf.pair.mk (1 : K) 0 = gp.map coe, by simpa [continuants_aux], use (gcf.pair.mk 1 0), simp }, -- n = 1 { suffices : ∃ (conts : gcf.pair ℚ), gcf.pair.mk g.h 1 = conts.map coe, by simpa [continuants_aux], use (gcf.pair.mk ⌊v⌋ 1), simp }, -- 2 ≤ n { cases (IH (n + 1) $ lt_add_one (n + 1)) with pred_conts pred_conts_eq, -- invoke the IH cases s_ppred_nth_eq : (g.s.nth n) with gp_n, -- option.none { use pred_conts, have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq, simp only [this, pred_conts_eq] }, -- option.some { -- invoke the IH a second time cases (IH n $ lt_of_le_of_lt (n.le_succ) $ lt_add_one $ n + 1) with ppred_conts ppred_conts_eq, obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ (z : ℤ), gp_n.b = (z : K), from of_part_num_eq_one_and_exists_int_part_denom_eq s_ppred_nth_eq, -- finally, unfold the recurrence to obtain the required rational value. simp only [a_eq_one, b_eq_z, (continuants_aux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq)], use (next_continuants 1 (z : ℚ) ppred_conts pred_conts), cases ppred_conts, cases pred_conts, simp [next_continuants, next_numerator, next_denominator] } } end lemma exists_gcf_pair_rat_eq_nth_conts : ∃ (conts : gcf.pair ℚ), (gcf.of v).continuants n = (conts.map coe : gcf.pair K) := by { rw [nth_cont_eq_succ_nth_cont_aux], exact (exists_gcf_pair_rat_eq_of_nth_conts_aux v $ n + 1) } lemma exists_rat_eq_nth_numerator : ∃ (q : ℚ), (gcf.of v).numerators n = (q : K) := begin rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨a, _⟩, nth_cont_eq⟩, use a, simp [num_eq_conts_a, nth_cont_eq], end lemma exists_rat_eq_nth_denominator : ∃ (q : ℚ), (gcf.of v).denominators n = (q : K) := begin rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨_, b⟩, nth_cont_eq⟩, use b, simp [denom_eq_conts_b, nth_cont_eq] end /-- Every finite convergent corresponds to a rational number. -/ lemma exists_rat_eq_nth_convergent : ∃ (q : ℚ), (gcf.of v).convergents n = (q : K) := begin rcases (exists_rat_eq_nth_numerator v n) with ⟨Aₙ, nth_num_eq⟩, rcases (exists_rat_eq_nth_denominator v n) with ⟨Bₙ, nth_denom_eq⟩, use (Aₙ / Bₙ), simp [nth_num_eq, nth_denom_eq, convergent_eq_num_div_denom] end variable {v} /-- Every terminating continued fraction corresponds to a rational number. -/ theorem exists_rat_eq_of_terminates (terminates : (gcf.of v).terminates) : ∃ (q : ℚ), v = ↑q := begin obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (gcf.of v).convergents n, from of_correctness_of_terminates terminates, obtain ⟨q, conv_eq_q⟩ : ∃ (q : ℚ), (gcf.of v).convergents n = (↑q : K), from exists_rat_eq_nth_convergent v n, have : v = (↑q : K), from eq.trans v_eq_conv conv_eq_q, use [q, this] end end rat_of_terminates section rat_translation /-! ### Technical Translation Lemmas Before we can show that the continued fraction of a rational number terminates, we have to prove some technical translation lemmas. More precisely, in this section, we show that, given a rational number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide. In particular, we show that ```lean (↑(generalized_continued_fraction.of q : generalized_continued_fraction ℚ) : generalized_continued_fraction K) = generalized_continued_fraction.of v` ``` in `generalized_continued_fraction.coe_of_rat`. To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in the computation first and then lift the results step-by-step. -/ /- The lifting works for arbitrary linear ordered fields with a floor function. -/ variables {v : K} {q : ℚ} (v_eq_q : v = (↑q : K)) (n : ℕ) include v_eq_q /-! First, we show the correspondence for the very basic functions in `generalized_continued_fraction.int_fract_pair`. -/ namespace int_fract_pair lemma coe_of_rat_eq : ((int_fract_pair.of q).mapFr coe : int_fract_pair K) = int_fract_pair.of v := by simp [int_fract_pair.of, v_eq_q, fract] lemma coe_stream_nth_rat_eq : ((int_fract_pair.stream q n).map (mapFr coe) : option $ int_fract_pair K) = int_fract_pair.stream v n := begin induction n with n IH, case nat.zero : { simp [int_fract_pair.stream, (coe_of_rat_eq v_eq_q)] }, case nat.succ : { rw v_eq_q at IH, cases stream_q_nth_eq : (int_fract_pair.stream q n) with ifp_n, case option.none : { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq] }, case option.some : { cases ifp_n with b fr, cases decidable.em (fr = 0) with fr_zero fr_ne_zero, { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero] }, { replace IH : some (int_fract_pair.mk b ↑fr) = int_fract_pair.stream ↑q n, by rwa [stream_q_nth_eq] at IH, have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K), by norm_cast, have coe_of_fr := (coe_of_rat_eq this), simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero], unfold_coes, simpa [coe_of_fr] } } } end lemma coe_stream_rat_eq : ((int_fract_pair.stream q).map (option.map (mapFr coe)) : stream $ option $ int_fract_pair K) = int_fract_pair.stream v := by { funext n, exact (int_fract_pair.coe_stream_nth_rat_eq v_eq_q n) } end int_fract_pair /-! Now we lift the coercion results to the continued fraction computation. -/ lemma coe_of_h_rat_eq : (↑((gcf.of q).h : ℚ) : K) = (gcf.of v).h := begin unfold gcf.of int_fract_pair.seq1, rw ←(int_fract_pair.coe_of_rat_eq v_eq_q), simp end lemma coe_of_s_nth_rat_eq : (((gcf.of q).s.nth n).map (gcf.pair.map coe) : option $ gcf.pair K) = (gcf.of v).s.nth n := begin simp only [gcf.of, gcf.int_fract_pair.seq1, seq.map_nth, seq.nth_tail], simp only [seq.nth], rw [←(int_fract_pair.coe_stream_rat_eq v_eq_q)], rcases succ_nth_stream_eq : (int_fract_pair.stream q (n + 1)) with _ | ⟨_, _⟩; simp [stream.map, stream.nth, succ_nth_stream_eq] end lemma coe_of_s_rat_eq : (((gcf.of q).s).map (gcf.pair.map coe) : seq $ gcf.pair K) = (gcf.of v).s := by { ext n, rw ←(coe_of_s_nth_rat_eq v_eq_q), refl } /-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/ lemma coe_of_rat_eq : (⟨(gcf.of q).h, (gcf.of q).s.map (gcf.pair.map coe)⟩ : gcf K) = gcf.of v := begin cases gcf_v_eq : (gcf.of v) with h s, have : ↑⌊↑q⌋ = h, by { rw v_eq_q at gcf_v_eq, injection gcf_v_eq }, simp [(coe_of_h_rat_eq v_eq_q), (coe_of_s_rat_eq v_eq_q), gcf_v_eq], rwa [←(@rat.cast_floor K _ _ q), floor_ring_unique] end lemma of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) : (gcf.of v).terminates ↔ (gcf.of q).terminates := begin split; intro h; cases h with n h; use n; simp only [seq.terminated_at, (coe_of_s_nth_rat_eq v_eq_q n).symm] at h ⊢; cases ((gcf.of q).s.nth n); trivial end end rat_translation section terminates_of_rat /-! ### Continued Fractions of Rationals Terminate Finally, we show that the continued fraction of a rational number terminates. The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `fract q` is smaller than the numerator of `q`. As the continued fraction computation recursively operates on the fractional part of a value `v` and `0 ≤ fract v < 1`, we infer that the numerator of the fractional part in the computation decreases by at least one in each step. As `0 ≤ fract v`, this process must stop after finite number of steps, and the computation hence terminates. -/ namespace int_fract_pair variables {q : ℚ} {n : ℕ} /-- Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of `int_fract_pair.of q⁻¹` is smaller than the numerator of `q`. -/ lemma of_inv_fr_num_lt_num_of_pos (q_pos : 0 < q) : (int_fract_pair.of q⁻¹).fr.num < q.num := rat.fract_inv_num_lt_num_of_pos q_pos /-- Shows that the sequence of numerators of the fractional parts of the stream is strictly monotonically decreasing. -/ lemma stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : int_fract_pair ℚ} (stream_nth_eq : int_fract_pair.stream q n = some ifp_n) (stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) : ifp_succ_n.fr.num < ifp_n.fr.num := begin obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, int_fract_pair.of_eq_ifp_succ_n⟩ : ∃ ifp_n', int_fract_pair.stream q n = some ifp_n' ∧ ifp_n'.fr ≠ 0 ∧ int_fract_pair.of ifp_n'.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq, have : ifp_n = ifp_n', by injection (eq.trans stream_nth_eq.symm stream_nth_eq'), cases this, rw [←int_fract_pair.of_eq_ifp_succ_n], cases (nth_stream_fr_nonneg_lt_one stream_nth_eq) with zero_le_ifp_n_fract ifp_n_fract_lt_one, have : 0 < ifp_n.fr, from (lt_of_le_of_ne zero_le_ifp_n_fract $ ifp_n_fract_ne_zero.symm), exact (of_inv_fr_num_lt_num_of_pos this) end lemma stream_nth_fr_num_le_fr_num_sub_n_rat : ∀ {ifp_n : int_fract_pair ℚ}, int_fract_pair.stream q n = some ifp_n → ifp_n.fr.num ≤ (int_fract_pair.of q).fr.num - n := begin induction n with n IH, case nat.zero { assume ifp_zero stream_zero_eq, have : int_fract_pair.of q = ifp_zero, by injection stream_zero_eq, simp [le_refl, this.symm] }, case nat.succ { assume ifp_succ_n stream_succ_nth_eq, suffices : ifp_succ_n.fr.num + 1 ≤ (int_fract_pair.of q).fr.num - n, by { rw [int.coe_nat_succ, sub_add_eq_sub_sub], solve_by_elim [le_sub_right_of_add_le] }, rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with ⟨ifp_n, stream_nth_eq, -⟩, have : ifp_succ_n.fr.num < ifp_n.fr.num, from stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq, have : ifp_succ_n.fr.num + 1 ≤ ifp_n.fr.num, from int.add_one_le_of_lt this, exact (le_trans this (IH stream_nth_eq)) } end lemma exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none := begin let fract_q_num := (fract q).num, let n := fract_q_num.nat_abs + 1, cases stream_nth_eq : (int_fract_pair.stream q n) with ifp, { use n, exact stream_nth_eq }, { -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional -- value is nonnegative. have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n, from stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq, have : fract_q_num - n = -1, by { have : 0 ≤ fract_q_num, from rat.num_nonneg_iff_zero_le.elim_right (fract_nonneg q), simp [(int.nat_abs_of_nonneg this), sub_add_eq_sub_sub_swap, sub_right_comm] }, have : ifp.fr.num ≤ -1, by rwa this at ifp_fr_num_le_q_fr_num_sub_n, have : 0 ≤ ifp.fr, from (nth_stream_fr_nonneg_lt_one stream_nth_eq).left, have : 0 ≤ ifp.fr.num, from rat.num_nonneg_iff_zero_le.elim_right this, linarith } end end int_fract_pair /-- The continued fraction of a rational number terminates. -/ theorem terminates_of_rat (q : ℚ) : (gcf.of q).terminates := exists.elim (int_fract_pair.exists_nth_stream_eq_none_of_rat q) ( assume n stream_nth_eq_none, exists.intro n ( have int_fract_pair.stream q (n + 1) = none, from int_fract_pair.stream_is_seq q stream_nth_eq_none, (of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right this) ) ) end terminates_of_rat /-- The continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`. -/ theorem terminates_iff_rat (v : K) : (gcf.of v).terminates ↔ ∃ (q : ℚ), v = (q : K) := iff.intro ( assume terminates_v : (gcf.of v).terminates, show ∃ (q : ℚ), v = (q : K), from exists_rat_eq_of_terminates terminates_v ) ( assume exists_q_eq_v : ∃ (q : ℚ), v = (↑q : K), exists.elim exists_q_eq_v ( assume q, assume v_eq_q : v = ↑q, have (gcf.of q).terminates, from terminates_of_rat q, (of_terminates_iff_of_rat_terminates v_eq_q).elim_right this ) ) end generalized_continued_fraction
69002e4f14eef31f1f4fac84ffbe651b96c8c8f4
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Delaborator.lean
d1ac3bfaa1ebc5f7828a97879685cfc4c4f543b4
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,639
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! The delaborator is the first stage of the pretty printer, and the inverse of the elaborator: it turns fully elaborated `Expr` core terms back into surface-level `Syntax`, omitting some implicit information again and using higher-level syntax abstractions like notations where possible. The exact behavior can be customized using pretty printer options; activating `pp.all` should guarantee that the delaborator is injective and that re-elaborating the resulting `Syntax` round-trips. Pretty printer options can be given not only for the whole term, but also specific subterms. This is used both when automatically refining pp options until round-trip and when interactively selecting pp options for a subterm (both TBD). The association of options to subterms is done by assigning a unique, synthetic Nat position to each subterm derived from its position in the full term. This position is added to the corresponding Syntax object so that elaboration errors and interactions with the pretty printer output can be traced back to the subterm. The delaborator is extensible via the `[delab]` attribute. -/ import Lean.KeyedDeclsAttribute import Lean.ProjFns import Lean.Syntax import Lean.Elab.Term namespace Lean -- TODO: move, maybe namespace Level protected partial def quote : Level → Syntax | zero _ => Unhygienic.run `(level|0) | l@(succ _ _) => match l.toNat with | some n => Unhygienic.run `(level|$(mkStxNumLitAux n):numLit) | none => Unhygienic.run `(level|$(quote l.getLevelOffset) + $(mkStxNumLitAux l.getOffset):numLit) | max l1 l2 _ => match_syntax quote l2 with | `(level|max $ls*) => Unhygienic.run `(level|max $(quote l1) $ls*) | l2 => Unhygienic.run `(level|max $(quote l1) $l2) | imax l1 l2 _ => match_syntax quote l2 with | `(level|imax $ls*) => Unhygienic.run `(level|imax $(quote l1) $ls*) | l2 => Unhygienic.run `(level|imax $(quote l1) $l2) | param n _ => Unhygienic.run `(level|$(mkIdent n):ident) -- HACK: approximation | mvar n _ => Unhygienic.run `(level|_) instance HasQuote : HasQuote Level := ⟨Level.quote⟩ end Level def getPPBinderTypes (o : Options) : Bool := o.get `pp.binder_types true def getPPCoercions (o : Options) : Bool := o.get `pp.coercions true def getPPExplicit (o : Options) : Bool := o.get `pp.explicit false def getPPNotation (o : Options) : Bool := o.get `pp.notation true def getPPStructureProjections (o : Options) : Bool := o.get `pp.structure_projections true def getPPStructureInstances (o : Options) : Bool := o.get `pp.structure_instances true def getPPStructureInstanceType (o : Options) : Bool := o.get `pp.structure_instance_type false def getPPUniverses (o : Options) : Bool := o.get `pp.universes false def getPPFullNames (o : Options) : Bool := o.get `pp.full_names false def getPPPrivateNames (o : Options) : Bool := o.get `pp.private_names false def getPPUnicode (o : Options) : Bool := o.get `pp.unicode true def getPPAll (o : Options) : Bool := o.get `pp.all false @[init] def ppOptions : IO Unit := do registerOption `pp.explicit { defValue := false, group := "pp", descr := "(pretty printer) display implicit arguments" }; registerOption `pp.structure_instance_type { defValue := false, group := "pp", descr := "(pretty printer) display type of structure instances" }; -- TODO: register other options when old pretty printer is removed --registerOption `pp.universes { defValue := false, group := "pp", descr := "(pretty printer) display universes" }; pure () /-- Associate pretty printer options to a specific subterm using a synthetic position. -/ abbrev OptionsPerPos := Std.RBMap Nat Options (fun a b => a < b) namespace Delaborator open Lean.Meta structure Context := -- In contrast to other systems like the elaborator, we do not pass the current term explicitly as a -- parameter, but store it in the monad so that we can keep it in sync with `pos`. (expr : Expr) (pos : Nat := 1) (defaultOptions : Options) (optionsPerPos : OptionsPerPos) (currNamespace : Name) (openDecls : List OpenDecl) -- Exceptions from delaborators are not expected. We use an internal exception to signal whether -- the delaborator was able to produce a Syntax object. def registerDelabFailureId : IO InternalExceptionId := registerInternalExceptionId `delabFailure @[init registerDelabFailureId] constant delabFailureId : InternalExceptionId := arbitrary _ abbrev DelabM := ReaderT Context MetaM abbrev Delab := DelabM Syntax instance DelabM.inhabited {α} : Inhabited (DelabM α) := ⟨throw $ arbitrary _⟩ @[inline] protected def orelse {α} (d₁ d₂ : DelabM α) : DelabM α := do catchInternalId delabFailureId d₁ (fun _ => d₂) protected def failure {α} : DelabM α := throw $ Exception.internal delabFailureId instance : Alternative DelabM := { orelse := fun _ => Delaborator.orelse, failure := fun _ => Delaborator.failure } -- HACK: necessary since it would otherwise prefer the instance from MonadExcept instance {α} : HasOrelse (DelabM α) := alternativeHasOrelse _ _ -- Macro scopes in the delaborator output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance DelabM.monadQuotation : MonadQuotation DelabM := { getCurrMacroScope := pure $ arbitrary _, getMainModule := pure $ arbitrary _, withFreshMacroScope := fun α x => x, } unsafe def mkDelabAttribute : IO (KeyedDeclsAttribute Delab) := KeyedDeclsAttribute.init { builtinName := `builtinDelab, name := `delab, descr := "Register a delaborator. [delab k] registers a declaration of type `Lean.Delaborator.Delab` for the `Lean.Expr` constructor `k`. Multiple delaborators for a single constructor are tried in turn until the first success. If the term to be delaborated is an application of a constant `c`, elaborators for `app.c` are tried first; this is also done for `Expr.const`s (\"nullary applications\") to reduce special casing. If the term is an `Expr.mdata` with a single key `k`, `mdata.k` is tried first.", valueTypeName := `Lean.Delaborator.Delab } `Lean.Delaborator.delabAttribute @[init mkDelabAttribute] constant delabAttribute : KeyedDeclsAttribute Delab := arbitrary _ def getExpr : DelabM Expr := do ctx ← read; pure ctx.expr def getExprKind : DelabM Name := do e ← getExpr; pure $ match e with | Expr.bvar _ _ => `bvar | Expr.fvar _ _ => `fvar | Expr.mvar _ _ => `mvar | Expr.sort _ _ => `sort | Expr.const c _ _ => -- we identify constants as "nullary applications" to reduce special casing `app ++ c | Expr.app fn _ _ => match fn.getAppFn with | Expr.const c _ _ => `app ++ c | _ => `app | Expr.lam _ _ _ _ => `lam | Expr.forallE _ _ _ _ => `forallE | Expr.letE _ _ _ _ _ => `letE | Expr.lit _ _ => `lit | Expr.mdata m _ _ => match m.entries with | [(key, _)] => `mdata ++ key | _ => `mdata | Expr.proj _ _ _ _ => `proj | Expr.localE _ _ _ _ => `localE /-- Evaluate option accessor, using subterm-specific options if set. Default to `true` if `pp.all` is set. -/ def getPPOption (opt : Options → Bool) : DelabM Bool := do ctx ← read; let opt := fun opts => opt opts || getPPAll opts; let val := opt ctx.defaultOptions; match ctx.optionsPerPos.find? ctx.pos with | some opts => pure $ opt opts | none => pure val def whenPPOption (opt : Options → Bool) (d : Delab) : Delab := do b ← getPPOption opt; if b then d else failure def whenNotPPOption (opt : Options → Bool) (d : Delab) : Delab := do b ← getPPOption opt; if b then failure else d /-- Descend into `child`, the `childIdx`-th subterm of the current term, and update position. Because `childIdx < 3` in the case of `Expr`, we can injectively map a path `childIdxs` to a natural number by computing the value of the 3-ary representation `1 :: childIdxs`, since n-ary representations without leading zeros are unique. Note that `pos` is initialized to `1` (case `childIdxs == []`). -/ def descend {α} (child : Expr) (childIdx : Nat) (d : DelabM α) : DelabM α := adaptReader (fun (cfg : Context) => { cfg with expr := child, pos := cfg.pos * 3 + childIdx }) d def withAppFn {α} (d : DelabM α) : DelabM α := do Expr.app fn _ _ ← getExpr | unreachable!; descend fn 0 d def withAppArg {α} (d : DelabM α) : DelabM α := do Expr.app _ arg _ ← getExpr | unreachable!; descend arg 1 d partial def withAppFnArgs {α} : DelabM α → (α → DelabM α) → DelabM α | fnD, argD => do Expr.app fn arg _ ← getExpr | fnD; a ← withAppFn (withAppFnArgs fnD argD); withAppArg (argD a) def withBindingDomain {α} (d : DelabM α) : DelabM α := do e ← getExpr; descend e.bindingDomain! 0 d def withBindingBody {α} (n : Name) (d : DelabM α) : DelabM α := do e ← getExpr; withLocalDecl n e.binderInfo e.bindingDomain! fun fvar => let b := e.bindingBody!.instantiate1 fvar; descend b 1 d def withProj {α} (d : DelabM α) : DelabM α := do Expr.proj _ _ e _ ← getExpr | unreachable!; descend e 0 d def withMDataExpr {α} (d : DelabM α) : DelabM α := do Expr.mdata _ e _ ← getExpr | unreachable!; descend e 0 d partial def annotatePos (pos : Nat) : Syntax → Syntax | stx@(Syntax.ident _ _ _ _) => stx.setInfo { pos := pos } -- app => annotate function | stx@(Syntax.node `Lean.Parser.Term.app args) => stx.modifyArg 0 annotatePos -- otherwise, annotate first direct child token if any | stx => match stx.getArgs.findIdx? Syntax.isAtom with | some idx => stx.modifyArg idx (Syntax.setInfo { pos := pos }) | none => stx def annotateCurPos (stx : Syntax) : Delab := do ctx ← read; pure $ annotatePos ctx.pos stx @[inline] def liftMetaM {α} (x : MetaM α) : DelabM α := liftM x partial def delabFor : Name → Delab | k => do env ← getEnv; (match (delabAttribute.ext.getState env).table.find? k with | some delabs => delabs.firstM id >>= annotateCurPos | none => failure) <|> (match k with | Name.str Name.anonymous _ _ => failure | Name.str n _ _ => delabFor n.getRoot -- have `app.Option.some` fall back to `app` etc. | _ => failure) def delab : Delab := do k ← getExprKind; delabFor k <|> (liftM $ show MetaM Syntax from throwError $ "don't know how to delaborate '" ++ toString k ++ "'") @[builtinDelab fvar] def delabFVar : Delab := do Expr.fvar id _ ← getExpr | unreachable!; catch do { l ← getLocalDecl id; pure $ mkIdent l.userName } -- loose free variable, use internal name fun _ => pure $ mkIdent id -- loose bound variable, use pseudo syntax @[builtinDelab bvar] def delabBVar : Delab := do Expr.bvar idx _ ← getExpr | unreachable!; pure $ mkIdent $ mkNameSimple $ "#" ++ toString idx @[builtinDelab mvar] def delabMVar : Delab := do Expr.mvar n _ ← getExpr | unreachable!; let n := n.replacePrefix `_uniq `m; `(?$(mkIdent n)) @[builtinDelab sort] def delabSort : Delab := do Expr.sort l _ ← getExpr | unreachable!; match l with | Level.zero _ => `(Prop) | Level.succ (Level.zero _) _ => `(Type) | _ => match l.dec with | some l' => `(Type $(quote l')) | none => `(Sort $(quote l)) -- find shorter names for constants, in reverse to Lean.Elab.ResolveName private def unresolveQualifiedName (ns : Name) (c : Name) : DelabM Name := do let c' := c.replacePrefix ns Name.anonymous; env ← getEnv; guard $ c' != c && !c'.isAnonymous && (!c'.isAtomic || !isProtected env c); pure c' private def unresolveUsingNamespace (c : Name) : Name → DelabM Name | ns@(Name.str p _ _) => do unresolveQualifiedName ns c <|> unresolveUsingNamespace p | _ => failure private def unresolveOpenDecls (c : Name) : List OpenDecl → DelabM Name | [] => failure | OpenDecl.simple ns exs :: openDecls => let c' := c.replacePrefix ns Name.anonymous; if c' != c && exs.elem c' then unresolveOpenDecls openDecls else unresolveQualifiedName ns c <|> unresolveOpenDecls openDecls | OpenDecl.explicit openedId resolvedId :: openDecls => guard (c == resolvedId) *> pure openedId <|> unresolveOpenDecls openDecls -- NOTE: not a registered delaborator, as `const` is never called (see [delab] description) def delabConst : Delab := do Expr.const c ls _ ← getExpr | unreachable!; c ← condM (getPPOption getPPFullNames) (pure c) do { ctx ← read; env ← getEnv; let as := getRevAliases env c; -- might want to use a more clever heuristic such as selecting the shortest alias... let c := as.headD c; unresolveUsingNamespace c ctx.currNamespace <|> unresolveOpenDecls c ctx.openDecls <|> pure c }; c ← condM (getPPOption getPPPrivateNames) (pure c) (pure $ (privateToUserName? c).getD c); ppUnivs ← getPPOption getPPUniverses; if ls.isEmpty || !ppUnivs then pure $ mkIdent c else `($(mkIdent c).{$(mkSepArray (ls.toArray.map quote) (mkAtom ","))*}) inductive ParamKind | explicit -- combines implicit params, optParams, and autoParams | implicit (defVal : Option Expr) /-- Return array with n-th element set to kind of n-th parameter of `e`. -/ def getParamKinds (e : Expr) : MetaM (Array ParamKind) := do t ← inferType e; forallTelescopeReducing t $ fun params _ => params.mapM $ fun param => do l ← getLocalDecl param.fvarId!; match l.type.getOptParamDefault? with | some val => pure $ ParamKind.implicit val | _ => if l.type.isAutoParam || !l.binderInfo.isExplicit then pure $ ParamKind.implicit none else pure ParamKind.explicit @[builtinDelab app] def delabAppExplicit : Delab := do (fnStx, argStxs) ← withAppFnArgs (do fn ← getExpr; stx ← if fn.isConst then delabConst else delab; paramKinds ← liftM $ getParamKinds fn <|> pure #[]; stx ← if paramKinds.any (fun k => match k with | ParamKind.explicit => false | _ => true) then `(@$stx) else pure stx; pure (stx, #[])) (fun ⟨fnStx, argStxs⟩ => do argStx ← delab; pure (fnStx, argStxs.push argStx)); -- avoid degenerate `app` node if argStxs.isEmpty then pure fnStx else `($fnStx $argStxs*) @[builtinDelab app] def delabAppImplicit : Delab := whenNotPPOption getPPExplicit $ do (fnStx, _, argStxs) ← withAppFnArgs (do fn ← getExpr; stx ← if fn.isConst then delabConst else delab; paramKinds ← liftM $ getParamKinds fn <|> pure #[]; pure (stx, paramKinds.toList, #[])) (fun ⟨fnStx, paramKinds, argStxs⟩ => do arg ← getExpr; let implicit := match paramKinds with | [ParamKind.implicit (some v)] => !v.hasLooseBVars && v == arg | ParamKind.implicit none :: _ => true | _ => false; if implicit then pure (fnStx, paramKinds.tailD [], argStxs) else do argStx ← delab; pure (fnStx, paramKinds.tailD [], argStxs.push argStx)); -- avoid degenerate `app` node if argStxs.isEmpty then pure fnStx else `($fnStx $argStxs*) @[builtinDelab mdata] def elabMData : Delab := -- ignore mdata by default withMDataExpr delab /-- Check for a `Syntax.ident` of the given name anywhere in the tree. This is usually a bad idea since it does not check for shadowing bindings, but in the delaborator we assume that bindings are never shadowed. -/ partial def hasIdent (id : Name) : Syntax → Bool | Syntax.ident _ _ id' _ => id == id' | Syntax.node _ args => args.any hasIdent | _ => false /-- Return `true` iff current binder should be merged with the nested binder, if any, into a single binder group: * both binders must have same binder info and domain * they cannot be inst-implicit (`[a b : A]` is not valid syntax) * `pp.binder_types` must be the same value for both terms * prefer `fun a b` over `fun (a b)` -/ private def shouldGroupWithNext : DelabM Bool := do e ← getExpr; ppEType ← getPPOption getPPBinderTypes; let go (e' : Expr) := do { ppE'Type ← withBindingBody `_ $ getPPOption getPPBinderTypes; pure $ e.binderInfo == e'.binderInfo && e.bindingDomain! == e'.bindingDomain! && e'.binderInfo != BinderInfo.instImplicit && ppEType == ppE'Type && (e'.binderInfo != BinderInfo.default || ppE'Type) }; match e with | Expr.lam _ _ e'@(Expr.lam _ _ _ _) _ => go e' | Expr.forallE _ _ e'@(Expr.forallE _ _ _ _) _ => go e' | _ => pure false private partial def delabBinders (delabGroup : Array Syntax → Syntax → Delab) : optParam (Array Syntax) #[] → Delab -- Accumulate names (`Syntax.ident`s with position information) of the current, unfinished -- binder group `(d e ...)` as determined by `shouldGroupWithNext`. We cannot do grouping -- inside-out, on the Syntax level, because it depends on comparing the Expr binder types. | curNames => do lctx ← liftMetaM $ getLCtx; e ← getExpr; let n := lctx.getUnusedName e.bindingName!; stxN ← annotateCurPos (mkIdent n); let curNames := curNames.push stxN; condM shouldGroupWithNext -- group with nested binder => recurse immediately (withBindingBody n $ delabBinders curNames) -- don't group => delab body and prepend current binder group (withBindingBody n delab >>= delabGroup curNames) @[builtinDelab lam] def delabLam : Delab := delabBinders $ fun curNames stxBody => do e ← getExpr; stxT ← withBindingDomain delab; ppTypes ← getPPOption getPPBinderTypes; expl ← getPPOption getPPExplicit; -- leave lambda implicit if possible let blockImplicitLambda := expl || e.binderInfo == BinderInfo.default || Elab.Term.blockImplicitLambda stxBody || curNames.any (fun n => hasIdent n.getId stxBody); if !blockImplicitLambda then pure stxBody else do group ← match e.binderInfo, ppTypes with | BinderInfo.default, true => do -- "default" binder group is the only one that expects binder names -- as a term, i.e. a single `Syntax.ident` or an application thereof stxCurNames ← if curNames.size > 1 then `($(curNames.get! 0) $(curNames.eraseIdx 0)*) else pure $ curNames.get! 0; `(funBinder| ($stxCurNames : $stxT)) | BinderInfo.default, false => pure curNames.back -- here `curNames.size == 1` | BinderInfo.implicit, true => `(funBinder| {$curNames* : $stxT}) | BinderInfo.implicit, false => `(funBinder| {$curNames*}) | BinderInfo.instImplicit, _ => `(funBinder| [$curNames.back : $stxT]) -- here `curNames.size == 1` | _ , _ => unreachable!; match_syntax stxBody with | `(fun $binderGroups* => $stxBody) => `(fun $group $binderGroups* => $stxBody) | _ => `(fun $group => $stxBody) @[builtinDelab forallE] def delabForall : Delab := delabBinders $ fun curNames stxBody => do e ← getExpr; stxT ← withBindingDomain delab; match e.binderInfo with | BinderInfo.default => -- heuristic: use non-dependent arrows only if possible for whole group to avoid -- noisy mix like `(α : Type) → Type → (γ : Type) → ...`. let dependent := curNames.any $ fun n => hasIdent n.getId stxBody; -- NOTE: non-dependent arrows are available only for the default binder info if dependent then do `(($curNames* : $stxT) → $stxBody) else curNames.foldrM (fun _ stxBody => `($stxT → $stxBody)) stxBody | BinderInfo.implicit => `({$curNames* : $stxT} → $stxBody) -- here `curNames.size == 1` | BinderInfo.instImplicit => `([$curNames.back : $stxT] → $stxBody) | _ => unreachable! @[builtinDelab letE] def delabLetE : Delab := do Expr.letE n t v b _ ← getExpr | unreachable!; lctx ← getLCtx; let n := lctx.getUnusedName n; stxT ← descend t 0 delab; stxV ← descend v 1 delab; stxB ← withLetDecl n t v (fun fvar => let b := b.instantiate1 fvar; descend b 2 delab); `(let $(mkIdent n) : $stxT := $stxV; $stxB) @[builtinDelab lit] def delabLit : Delab := do Expr.lit l _ ← getExpr | unreachable!; match l with | Literal.natVal n => pure $ quote n | Literal.strVal s => pure $ quote s -- `ofNat 0` ~> `0` @[builtinDelab app.HasOfNat.ofNat] def delabOfNat : Delab := whenPPOption getPPCoercions $ do e@(Expr.app _ (Expr.lit (Literal.natVal n) _) _) ← getExpr | failure; pure $ quote n /-- Delaborate a projection primitive. These do not usually occur in user code, but are pretty-printed when e.g. `#print`ing a projection function. -/ @[builtinDelab proj] def delabProj : Delab := do Expr.proj _ idx _ _ ← getExpr | unreachable!; e ← withProj delab; -- not perfectly authentic: elaborates to the `idx`-th named projection -- function (e.g. `e.1` is `Prod.fst e`), which unfolds to the actual -- `proj`. let idx := mkStxLit fieldIdxKind (toString (idx + 1)); `($(e).$idx:fieldIdx) /-- Delaborate a call to a projection function such as `Prod.fst`. -/ @[builtinDelab app] def delabProjectionApp : Delab := whenPPOption getPPStructureProjections $ do e@(Expr.app fn _ _) ← getExpr | failure; Expr.const c@(Name.str _ f _) _ _ ← pure fn.getAppFn | failure; env ← getEnv; some info ← pure $ env.getProjectionFnInfo? c | failure; -- can't use with classes since the instance parameter is implicit guard $ !info.fromClass; -- projection function should be fully applied (#struct params + 1 instance parameter) -- TODO: support over-application guard $ e.getAppNumArgs == info.nparams + 1; -- If pp.explicit is true, and the structure has parameters, we should not -- use field notation because we will not be able to see the parameters. expl ← getPPOption getPPExplicit; guard $ !expl || info.nparams == 0; appStx ← withAppArg delab; `($(appStx).$(mkIdent f):ident) @[builtinDelab app] def delabStructureInstance : Delab := whenPPOption getPPStructureInstances do env ← getEnv; e ← getExpr; some s ← pure $ e.isConstructorApp? env | failure; guard $ isStructure env s.induct; /- If implicit arguments should be shown, and the structure has parameters, we should not pretty print using { ... }, because we will not be able to see the parameters. -/ explicit ← getPPOption getPPExplicit; guard !(explicit && s.nparams > 0); let fieldNames := getStructureFields env s.induct; (_, fields) ← withAppFnArgs (pure (0, #[])) fun ⟨idx, fields⟩ => if idx < s.nparams then pure (idx + 1, fields) else do { val ← delab; let field := Syntax.node `Lean.Parser.Term.structInstField #[ mkIdent $ fieldNames.get! (idx - s.nparams), mkNullNode, mkAtom ":=", val ]; pure (idx + 1, fields.push field) }; let fields := mkSepArray fields (mkAtom ","); condM (getPPOption getPPStructureInstanceType) (do ty ← inferType e; -- `ty` is not actually part of `e`, but since `e` must be an application or constant, we know that -- index 2 is unused. stxTy ← descend ty 2 delab; `({ $fields:structInstField* : $stxTy })) `({ $fields:structInstField* }) @[builtinDelab app.Prod.mk] def delabTuple : Delab := whenPPOption getPPNotation do e ← getExpr; guard $ e.getAppNumArgs == 4; a ← withAppFn $ withAppArg delab; b ← withAppArg delab; match_syntax b with | `(($b, $bs*)) => let bs := #[b, mkAtom ","] ++ bs; `(($a, $bs*)) | _ => `(($a, $b)) -- abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β @[builtinDelab app.coe] def delabCoe : Delab := whenPPOption getPPCoercions $ do e ← getExpr; guard $ e.getAppNumArgs >= 4; -- delab as application, then discard function stx ← delabAppImplicit; match_syntax stx with | `($fn $args*) => if args.size == 1 then pure $ args.get! 0 else `($(args.get! 0) $(args.eraseIdx 0)*) | _ => failure -- abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a @[builtinDelab app.coeFun] def delabCoeFun : Delab := delabCoe def delabInfixOp (op : Bool → Syntax → Syntax → Delab) : Delab := whenPPOption getPPNotation do stx ← delabAppImplicit <|> delabAppExplicit; guard $ stx.isOfKind `Lean.Parser.Term.app && (stx.getArg 1).getNumArgs == 2; unicode ← getPPOption getPPUnicode; let args := stx.getArg 1; op unicode (args.getArg 0) (args.getArg 1) def delabPrefixOp (op : Bool → Syntax → Delab) : Delab := whenPPOption getPPNotation do stx ← delabAppImplicit <|> delabAppExplicit; guard $ stx.isOfKind `Lean.Parser.Term.app && (stx.getArg 1).getNumArgs == 1; unicode ← getPPOption getPPUnicode; let args := stx.getArg 1; op unicode (args.getArg 0) @[builtinDelab app.Prod] def delabProd : Delab := delabInfixOp fun _ x y => `($x × $y) @[builtinDelab app.Function.comp] def delabFComp : Delab := delabInfixOp fun _ x y => `($x ∘ $y) @[builtinDelab app.HasAdd.add] def delabAdd : Delab := delabInfixOp fun _ x y => `($x + $y) @[builtinDelab app.HasSub.sub] def delabSub : Delab := delabInfixOp fun _ x y => `($x - $y) @[builtinDelab app.HasMul.mul] def delabMul : Delab := delabInfixOp fun _ x y => `($x * $y) @[builtinDelab app.HasDiv.div] def delabDiv : Delab := delabInfixOp fun _ x y => `($x / $y) @[builtinDelab app.HasMod.mod] def delabMod : Delab := delabInfixOp fun _ x y => `($x % $y) @[builtinDelab app.HasModN.modn] def delabModN : Delab := delabInfixOp fun _ x y => `($x %ₙ $y) @[builtinDelab app.HasPow.pow] def delabPow : Delab := delabInfixOp fun _ x y => `($x ^ $y) @[builtinDelab app.HasLessEq.LessEq] def delabLE : Delab := delabInfixOp fun b x y => cond b `($x ≤ $y) `($x <= $y) @[builtinDelab app.GreaterEq] def delabGE : Delab := delabInfixOp fun b x y => cond b `($x ≥ $y) `($x >= $y) @[builtinDelab app.HasLess.Less] def delabLT : Delab := delabInfixOp fun _ x y => `($x < $y) @[builtinDelab app.Greater] def delabGT : Delab := delabInfixOp fun _ x y => `($x > $y) @[builtinDelab app.Eq] def delabEq : Delab := delabInfixOp fun _ x y => `($x = $y) @[builtinDelab app.Ne] def delabNe : Delab := delabInfixOp fun _ x y => `($x ≠ $y) @[builtinDelab app.HasBeq.beq] def delabBEq : Delab := delabInfixOp fun _ x y => `($x == $y) @[builtinDelab app.bne] def delabBNe : Delab := delabInfixOp fun _ x y => `($x != $y) @[builtinDelab app.HEq] def delabHEq : Delab := delabInfixOp fun b x y => cond b `($x ≅ $y) `($x ~= $y) @[builtinDelab app.HasEquiv.Equiv] def delabEquiv : Delab := delabInfixOp fun _ x y => `($x ≈ $y) @[builtinDelab app.And] def delabAnd : Delab := delabInfixOp fun b x y => cond b `($x ∧ $y) `($x /\ $y) @[builtinDelab app.Or] def delabOr : Delab := delabInfixOp fun b x y => cond b `($x ∨ $y) `($x || $y) @[builtinDelab app.Iff] def delabIff : Delab := delabInfixOp fun b x y => cond b `($x ↔ $y) `($x <-> $y) @[builtinDelab app.and] def delabBAnd : Delab := delabInfixOp fun _ x y => `($x && $y) @[builtinDelab app.or] def delabBOr : Delab := delabInfixOp fun _ x y => `($x || $y) @[builtinDelab app.HasAppend.append] def delabAppend : Delab := delabInfixOp fun _ x y => `($x ++ $y) @[builtinDelab app.List.cons] def delabCons : Delab := delabInfixOp fun _ x y => `($x :: $y) @[builtinDelab app.HasAndthen.andthen] def delabAndThen : Delab := delabInfixOp fun _ x y => `($x >> $y) @[builtinDelab app.HasBind.bind] def delabBind : Delab := delabInfixOp fun _ x y => `($x >>= $y) @[builtinDelab app.HasSeq.seq] def delabseq : Delab := delabInfixOp fun _ x y => `($x <*> $y) @[builtinDelab app.HasSeqLeft.seqLeft] def delabseqLeft : Delab := delabInfixOp fun _ x y => `($x <* $y) @[builtinDelab app.HasSeqRight.seqRight] def delabseqRight : Delab := delabInfixOp fun _ x y => `($x *> $y) @[builtinDelab app.Functor.map] def delabMap : Delab := delabInfixOp fun _ x y => `($x <$> $y) @[builtinDelab app.Functor.mapRev] def delabMapRev : Delab := delabInfixOp fun _ x y => `($x <&> $y) @[builtinDelab app.HasOrelse.orelse] def delabOrElse : Delab := delabInfixOp fun _ x y => `($x <|> $y) @[builtinDelab app.orM] def delabOrM : Delab := delabInfixOp fun _ x y => `($x <||> $y) @[builtinDelab app.andM] def delabAndM : Delab := delabInfixOp fun _ x y => `($x <&&> $y) @[builtinDelab app.Not] def delabNot : Delab := delabPrefixOp fun _ x => `(¬ $x) @[builtinDelab app.not] def delabBNot : Delab := delabPrefixOp fun _ x => `(! $x) end Delaborator /-- "Delaborate" the given term into surface-level syntax using the default and given subterm-specific options. -/ def delab (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) (optionsPerPos : OptionsPerPos := {}) : MetaM Syntax := do opts ← getOptions; catchInternalId Delaborator.delabFailureId (Delaborator.delab.run { expr := e, defaultOptions := opts, optionsPerPos := optionsPerPos, currNamespace := currNamespace, openDecls := openDecls }) (fun _ => unreachable!) end Lean
7818169eb3d5e25b877c4a4dc58bfae27732d82f
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/stdio.lean
13e995b9b744aff1d0ffd9df5e5b458393b5030f
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
689
lean
open IO.FS #eval do out ← IO.getStdout; (out.putStrLn "print stdout" : IO Unit) #eval do err ← IO.getStderr; (err.putStr "print stderr" : IO Unit) open IO def test : IO Unit := do FS.withFile "stdout1.txt" IO.FS.Mode.write $ fun h₁ => do { h₂ ← FS.Handle.mk "stdout2.txt" IO.FS.Mode.write; withStdout (Stream.ofHandle h₁) $ do println "line 1"; catch ( do withStdout (Stream.ofHandle h₂) $ println "line 2"; throw $ IO.userError "my error" ) ( fun e => println e ); println "line 3" }; println "line 4"; println "\n> stdout1.txt"; readFile "stdout1.txt" >>= print; println "\n> stdout2.txt"; readFile "stdout2.txt" >>= print #eval test
b17a5f6d4a9d5e99ead20597a1c8d1a888839107
7afc29faca4febb6e5005c20aa4aa5c3df5cf35c
/src/tactics.lean
c584a02fc1f32f1063754cce7794811bbabe50b7
[ "MIT" ]
permissive
Piwry/Proof-of-Surreal
ad2883027e275050b43a578c5513ae3fe350515b
6b92baf2382ac23dd0d700f5c958aa910ad4b754
refs/heads/master
1,670,521,185,736
1,599,657,591,000
1,599,657,591,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,153
lean
import tactic defs single height lemma branch_left : ∀ t, ⟨t⟩ → ⟨⟦t∣⟧⟩ := begin intros, apply is_branch.left_nl, assumption end lemma branch_left_leaf : ∀ t, ⟨t⟩ → ⟨⟦t,●⟧⟩ := begin intros, apply is_branch.left_l, assumption end lemma branch_right : ∀ t, ⟨t⟩ → ⟨⟦∣t⟧⟩ := begin intros, apply is_branch.right_nl, assumption end lemma branch_right_leaf : ∀ t, ⟨t⟩ → ⟨⟦●,t⟧⟩ := begin intros, apply is_branch.right_l, assumption end meta def auto_branch_core : tactic unit := do h ← tactic.target, match h with | `(is_branch %%b):= match b with | `(●) := tactic.exact `(is_branch.single) | `(⟦%%t∣⟧) := do tactic.applyc `branch_left, auto_branch_core | `(⟦∣%%t⟧) := do tactic.applyc `branch_right, auto_branch_core | `(⟦%%t,●⟧):= do tactic.applyc `branch_left_leaf, auto_branch_core | `(⟦●,%%t⟧):= do tactic.applyc `branch_right_leaf, auto_branch_core | _ := tactic.try (tactic.assumption <|> tactic.tautology) end | _ := tactic.fail "should not exists" end meta def reduce_trivial_tree_core : list expr → tactic unit | [] := tactic.skip | (h :: hs) := do t ← tactic.infer_type h, match t with | `(%%b ↣ ●) := tactic.replace h.to_string ``(single_grow %%b %%h) | `(height %%b ≤ 1) := tactic.replace h.to_string ``(height_le1_single %%b %%h) | _ := tactic.skip end, reduce_trivial_tree_core hs meta def reduce_trivial_tree : tactic unit := do h ← tactic.local_context, reduce_trivial_tree_core h meta def rewrite_ci_core : list expr → tactic unit | [] := tactic.skip | (h :: hs) := do t ← tactic.infer_type h, match t with | `(%%b = ●) := tactic.try (tactic.subst h) | _ := tactic.skip end, rewrite_ci_core hs meta def rewrite_ci : tactic unit := do reduce_trivial_tree, h ← tactic.local_context, rewrite_ci_core h meta def auto_grow_core : tactic unit := do h ← tactic.target, match h with | `(grow %%t %%t') := match t, t' with | `(●), _ := tactic.applyc `grow.single_grow | `(⟦%%u∣⟧), `(⟦%%u'∣⟧) := do tactic.applyc `grow.left_grow, auto_grow_core | `(⟦∣%%v⟧), `(⟦∣%%v'⟧) := do tactic.applyc `grow.right_grow, auto_grow_core | `(⟦%%u, %%v⟧), `(⟦%%u', %%v'⟧) := do tactic.applyc `grow.full_grow, auto_grow_core, auto_grow_core | _, _ := tactic.try (tactic.assumption <|> tactic.tautology) end | _ := tactic.fail "should not exists" end meta def auto_grow : tactic unit := do rewrite_ci, auto_grow_core meta def auto_branch : tactic unit := do rewrite_ci, auto_branch_core
9a1ef3f17da4402920832c07182c015c75e72316
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/data/default.lean
ee59243fe0ee9713f53068fd726e040e0a6cfad9
[ "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
341
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.data.basic init.data.sigma init.data.nat init.data.char init.data.string import init.data.list init.data.sum init.data.subtype init.data.int init.data.array
02890626f989c3d797edcfe469b9b95ecea2bce3
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/algebra/category/Semigroup/basic.lean
67dfa3c96e3d45b58ee32dffa1195352fe21a59b
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,345
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer (heavily based on `Mon.basic` by Scott Morrison) -/ import category_theory.concrete_category.bundled_hom import category_theory.concrete_category.reflects_isomorphisms import algebra.pempty_instances /-! # Category instances for has_mul, has_add, semigroup and add_semigroup We introduce the bundled categories: * `Magma` * `AddMagma` * `Semigroup` * `AddSemigroup` along with the relevant forgetful functors between them. ## TODO * Limits in these categories * adjoining a unit adjunction to Mon * free/forgetful adjunctions -/ universes u v open category_theory /-- The category of magmas and magma morphisms. -/ @[to_additive AddMagma] def Magma : Type (u+1) := bundled has_mul /-- The category of additive magmas and additive magma morphisms. -/ add_decl_doc AddMagma namespace Magma @[to_additive] instance bundled_hom : bundled_hom @mul_hom := ⟨@mul_hom.to_fun, @mul_hom.id, @mul_hom.comp, @mul_hom.coe_inj⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Magma AddMagma /-- Construct a bundled `Magma` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [has_mul M] : Magma := bundled.of M /-- Construct a bundled `Magma` from the underlying type and typeclass. -/ add_decl_doc AddMagma.of @[to_additive] instance : inhabited Magma := ⟨Magma.of pempty⟩ @[to_additive] instance (M : Magma) : has_mul M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [has_mul R] : (Magma.of R : Type u) = R := rfl end Magma /-- The category of semigroups and semigroup morphisms. -/ @[to_additive AddSemigroup] def Semigroup : Type (u+1) := bundled semigroup /-- The category of additive semigroups and semigroup morphisms. -/ add_decl_doc AddSemigroup namespace Semigroup @[to_additive] instance : bundled_hom.parent_projection semigroup.to_has_mul := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Semigroup AddSemigroup /-- Construct a bundled `Semigroup` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [semigroup M] : Semigroup := bundled.of M /-- Construct a bundled `AddSemigroup` from the underlying type and typeclass. -/ add_decl_doc AddSemigroup.of @[to_additive] instance : inhabited Semigroup := ⟨Semigroup.of pempty⟩ @[to_additive] instance (M : Semigroup) : semigroup M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [semigroup R] : (Semigroup.of R : Type u) = R := rfl @[to_additive has_forget_to_AddMagma] instance has_forget_to_Magma : has_forget₂ Semigroup Magma := bundled_hom.forget₂ _ _ end Semigroup variables {X Y : Type u} section variables [has_mul X] [has_mul Y] /-- Build an isomorphism in the category `Magma` from a `mul_equiv` between `has_mul`s. -/ @[simps, to_additive add_equiv.to_AddMagma_iso "Build an isomorphism in the category `AddMagma` from an `add_equiv` between `has_add`s."] def mul_equiv.to_Magma_iso (e : X ≃* Y) : Magma.of X ≅ Magma.of Y := { hom := e.to_mul_hom, inv := e.symm.to_mul_hom } end section variables [semigroup X] [semigroup Y] /-- Build an isomorphism in the category `Semigroup` from a `mul_equiv` between `semigroup`s. -/ @[simps, to_additive add_equiv.to_AddSemigroup_iso "Build an isomorphism in the category `AddSemigroup` from an `add_equiv` between `add_semigroup`s."] def mul_equiv.to_Semigroup_iso (e : X ≃* Y) : Semigroup.of X ≅ Semigroup.of Y := { hom := e.to_mul_hom, inv := e.symm.to_mul_hom } end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Magma`. -/ @[to_additive AddMagma_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMagma`."] def Magma_iso_to_mul_equiv {X Y : Magma} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := begin rw function.left_inverse, simp end, right_inv := begin rw function.right_inverse, rw function.left_inverse, simp end, map_mul' := by simp } /-- Build a `mul_equiv` from an isomorphism in the category `Semigroup`. -/ @[to_additive "Build an `add_equiv` from an isomorphism in the category `AddSemigroup`."] def Semigroup_iso_to_mul_equiv {X Y : Semigroup} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := begin rw function.left_inverse, simp end, right_inv := begin rw function.right_inverse, rw function.left_inverse, simp end, map_mul' := by simp } end category_theory.iso /-- multiplicative equivalences between `has_mul`s are the same as (isomorphic to) isomorphisms in `Magma` -/ @[to_additive add_equiv_iso_AddMagma_iso "additive equivalences between `has_add`s are the same as (isomorphic to) isomorphisms in `AddMagma`"] def mul_equiv_iso_Magma_iso {X Y : Type u} [has_mul X] [has_mul Y] : (X ≃* Y) ≅ (Magma.of X ≅ Magma.of Y) := { hom := λ e, e.to_Magma_iso, inv := λ i, i.Magma_iso_to_mul_equiv } /-- multiplicative equivalences between `semigroup`s are the same as (isomorphic to) isomorphisms in `Semigroup` -/ @[to_additive add_equiv_iso_AddSemigroup_iso "additive equivalences between `add_semigroup`s are the same as (isomorphic to) isomorphisms in `AddSemigroup`"] def mul_equiv_iso_Semigroup_iso {X Y : Type u} [semigroup X] [semigroup Y] : (X ≃* Y) ≅ (Semigroup.of X ≅ Semigroup.of Y) := { hom := λ e, e.to_Semigroup_iso, inv := λ i, i.Semigroup_iso_to_mul_equiv } @[to_additive] instance Magma.forget_reflects_isos : reflects_isomorphisms (forget Magma.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Magma).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_Magma_iso }, end } @[to_additive] instance Semigroup.forget_reflects_isos : reflects_isomorphisms (forget Semigroup.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Semigroup).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_Semigroup_iso }, end } /-! Once we've shown that the forgetful functors to type reflect isomorphisms, we automatically obtain that the `forget₂` functors between our concrete categories reflect isomorphisms. -/ example : reflects_isomorphisms (forget₂ Semigroup Magma) := by apply_instance
d0f33f23e23e6fb97c7db5a54abdb05a47a68a6f
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/real/nnreal.lean
420bebc07f5f4a28c7d691bcba040a40d44dc72d
[ "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
29,819
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.linear_ordered_comm_group_with_zero import algebra.big_operators.ring import data.real.basic import data.indicator_function import algebra.algebra.basic /-! # Nonnegative real numbers In this file we define `nnreal` (notation: `ℝ≥0`) to be the type of non-negative real numbers, a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`: * the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally complete linear order with a bottom element, `conditionally_complete_linear_order_bot`; * `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`; these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a linear ordered archimedean commutative semifield; we have no typeclass for this in `mathlib` yet, so we define the following instances instead: - `linear_ordered_semiring ℝ≥0`; - `comm_semiring ℝ≥0`; - `canonically_ordered_comm_semiring ℝ≥0`; - `linear_ordered_comm_group_with_zero ℝ≥0`; - `archimedean ℝ≥0`. * `nnreal.of_real x` is defined as `⟨max x 0, _⟩`, i.e. `↑(nnreal.of_real x) = x` when `0 ≤ x` and `↑(nnreal.of_real x) = 0` otherwise. We also define an instance `can_lift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurences of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis `hf : ∀ x, 0 ≤ f x`. ## Notations This file defines `ℝ≥0` as a localized notation for `nnreal`. -/ noncomputable theory open_locale classical big_operators /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : ℝ≥0) : n.val = n := rfl instance : can_lift ℝ ℝ≥0 := { coe := coe, cond := λ r, 0 ≤ r, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff /-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/ protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a / b, div_nonneg a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ protected lemma coe_injective : function.injective (coe : ℝ≥0 → ℝ) := subtype.coe_injective @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := nnreal.coe_injective.eq_iff @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast instance : comm_semiring ℝ≥0 := { zero := 0, add := (+), one := 1, mul := (*), .. nnreal.coe_injective.comm_semiring _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) } /-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/ def to_real_hom : ℝ≥0 →+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ /-- The real numbers are an algebra over the non-negative reals. -/ instance : algebra ℝ≥0 ℝ := to_real_hom.to_algebra @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl instance : comm_group_with_zero ℝ≥0 := { zero := 0, mul := (*), one := 1, inv := has_inv.inv, div := (/), .. nnreal.coe_injective.comm_group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) } @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (λ x, f x) a := (to_real_hom : ℝ≥0 →+ ℝ).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := to_real_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) := to_real_hom.map_sum _ _ lemma of_real_sum_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : nnreal.of_real (∑ a in s, f a) = ∑ a in s, nnreal.of_real (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_sum, nnreal.coe_of_real _ (finset.sum_nonneg hf)], exact finset.sum_congr rfl (λ x hxs, by rw nnreal.coe_of_real _ (hf x hxs)), end @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) := to_real_hom.map_prod _ _ lemma of_real_prod_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : nnreal.of_real (∏ a in s, f a) = ∏ a in s, nnreal.of_real (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_prod, nnreal.coe_of_real _ (finset.prod_nonneg hf)], exact finset.prod_congr rfl (λ x hxs, by rw nnreal.coe_of_real _ (hf x hxs)), end @[norm_cast] lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℝ) := to_real_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := to_real_hom.map_nat_cast n instance : linear_order ℝ≥0 := linear_order.lift (coe : ℝ≥0 → ℝ) nnreal.coe_injective @[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma of_real_mono : monotone nnreal.of_real := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 @[simp] lemma mk_coe_nat (n : ℕ) : @eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n := nnreal.eq (nnreal.coe_nat_cast n).symm @[simp] lemma of_real_coe_nat (n : ℕ) : nnreal.of_real n = n := nnreal.eq $ by simp [coe_of_real] /-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (λ _, of_real_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.linear_order } instance : canonically_linear_ordered_add_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ a b _ _ _ h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ a b c _ _ _, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ _ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_le_one := @zero_le_one ℝ _, exists_pair_ne := ⟨0, 1, ne_of_lt (@zero_lt_one ℝ _ _)⟩, .. nnreal.canonically_linear_ordered_add_monoid, .. nnreal.comm_semiring, } instance : linear_ordered_comm_group_with_zero ℝ≥0 := { mul_le_mul_left := assume a b h c, mul_le_mul (le_refl c) h (zero_le a) (zero_le c), zero_le_one := zero_le 1, .. nnreal.linear_ordered_semiring, .. nnreal.comm_group_with_zero } instance : canonically_ordered_comm_semiring ℝ≥0 := { .. nnreal.canonically_linear_ordered_add_monoid, .. nnreal.comm_semiring, .. (show no_zero_divisors ℝ≥0, by apply_instance), .. nnreal.comm_group_with_zero } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := exists_between h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : ℝ≥0 → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : ℝ≥0 → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : ℝ≥0 → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : ℝ≥0 → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set ℝ≥0) : (↑(Sup s) : ℝ) = Sup ((coe : ℝ≥0 → ℝ) '' s) := rfl lemma coe_Inf (s : set ℝ≥0) : (↑(Inf s) : ℝ) = Inf ((coe : ℝ≥0 → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : ℝ≥0 → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : ℝ≥0 → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_linear_order, .. nnreal.order_bot } instance : archimedean ℝ≥0 := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (n • y : ℝ≥0), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ lemma le_of_forall_pos_le_add {a b : ℝ≥0} (h : ∀ε, 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℝ≥0} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, simp } lemma le_of_add_le_right {a b c : ℝ≥0} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, simp } lemma lt_iff_exists_rat_btwn (a b : ℝ≥0) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : ℝ≥0) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : ℝ≥0) : ((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : ℝ≥0) : ((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } section of_real @[simp] lemma zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : nnreal.of_real r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp] lemma le_of_real_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := (le_or_lt 0 p).elim le_of_real_iff_coe_le $ λ hp, by simp only [(hp.trans_le r.coe_nonneg).not_le, of_real_eq_zero.2 hp.le, hr.not_le] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end @[simp] lemma of_real_bit0 {r : ℝ} (hr : 0 ≤ r) : nnreal.of_real (bit0 r) = bit0 (nnreal.of_real r) := of_real_add hr hr @[simp] lemma of_real_bit1 {r : ℝ} (hr : 0 ≤ r) : nnreal.of_real (bit1 r) = bit1 (nnreal.of_real r) := (of_real_add (by simp [hr]) zero_le_one).trans (by simp [of_real_one, bit1, hr]) end of_real section mul lemma mul_eq_mul_left {a b c : ℝ≥0} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact mul_left_cancel' (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, simp [nnreal.of_real, hp, hq, max_eq_left, mul_nonneg] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end end mul section pow lemma pow_mono_decr_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) : a ^ n ≤ a ^ m := begin rcases le_iff_exists_add.mp mn with ⟨k, rfl⟩, rw [← mul_one (a ^ m), pow_add], refine mul_le_mul rfl.le (pow_le_one _ (zero_le a) a1) _ _; exact pow_nonneg (zero_le _) _, end end pow section sub lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : ℝ≥0} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : ℝ≥0} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : ℝ≥0} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_self lemma add_sub_cancel' {r p : ℝ≥0} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] lemma sub_add_eq_max {r p : ℝ≥0} : (r - p) + p = max r p := nnreal.eq $ by rw [sub_def, nnreal.coe_add, coe_max, nnreal.of_real, coe_mk, ← max_add_add_right, zero_add, sub_add_cancel] lemma add_sub_eq_max {r p : ℝ≥0} : p + (r - p) = max p r := by rw [add_comm, sub_add_eq_max, max_comm] @[simp] lemma sub_add_cancel_of_le {a b : ℝ≥0} (h : b ≤ a) : (a - b) + b = a := by rw [sub_add_eq_max, max_eq_left h] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] lemma lt_sub_iff_add_lt {p q r : ℝ≥0} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : ℝ≥0) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_self) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end lemma sub_lt_iff_lt_add {a b c : ℝ≥0} (h : b ≤ a) : a - b < c ↔ a < b + c := by simp only [←nnreal.coe_lt_coe, nnreal.coe_sub h, nnreal.coe_add, sub_lt_iff_lt_add'] lemma sub_eq_iff_eq_add {a b c : ℝ≥0} (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [←nnreal.eq_iff, nnreal.coe_sub h, ←nnreal.eq_iff, nnreal.coe_add, sub_eq_iff_eq_add] end sub section inv lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) : (∑ i in s, f i) / b = ∑ i in s, (f i / b) := by simp only [div_eq_mul_inv, finset.sum_mul] @[simp] lemma inv_pos {r : ℝ≥0} : 0 < r⁻¹ ↔ 0 < r := by simp [pos_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp) protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev' _ _ lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 := if h : r = 0 then by simp [h] else by rw [div_self h] @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r := @div_le_iff ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ r * b := @div_le_iff' ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma le_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := @le_div_iff ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma le_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ r * a ≤ b := @le_div_iff' ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma div_lt_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < b * r := lt_iff_lt_of_le_iff_le (le_div_iff hr) lemma div_lt_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < r * b := lt_iff_lt_of_le_iff_le (le_div_iff' hr) lemma lt_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b := lt_iff_lt_of_le_iff_le (div_le_iff hr) lemma lt_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ r * a < b := lt_iff_lt_of_le_iff_le (div_le_iff' hr) lemma mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b := begin refine (lt_div_iff $ λ hr, false.elim _).1 h, subst r, simpa using h end lemma div_le_div_left_of_le {a b c : ℝ≥0} (b0 : 0 < b) (c0 : 0 < c) (cb : c ≤ b) : a / b ≤ a / c := begin by_cases a0 : a = 0, { rw [a0, zero_div, zero_div] }, { cases a with a ha, replace a0 : 0 < a := lt_of_le_of_ne ha (ne_of_lt (zero_lt_iff.mpr a0)), exact (div_le_div_left a0 b0 c0).mpr cb } end lemma div_le_div_left {a b c : ℝ≥0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) : a / b ≤ a / c ↔ c ≤ b := by rw [nnreal.div_le_iff b0.ne.symm, div_mul_eq_mul_div, nnreal.le_div_iff_mul_le c0.ne.symm, mul_le_mul_left a0] lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv'], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa using half_lt_self zero_ne_one.symm lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma of_real_inv {x : ℝ} : nnreal.of_real x⁻¹ = (nnreal.of_real x)⁻¹ := begin by_cases hx : 0 ≤ x, { nth_rewrite 0 ← coe_of_real x hx, rw [←nnreal.coe_inv, of_real_coe], }, { have hx' := le_of_not_ge hx, rw [of_real_eq_zero.mpr hx', inv_zero, of_real_eq_zero.mpr (inv_nonpos.mpr hx')], }, end lemma of_real_div {x y : ℝ} (hx : 0 ≤ x) : nnreal.of_real (x / y) = nnreal.of_real x / nnreal.of_real y := by rw [div_eq_mul_inv, div_eq_mul_inv, ←of_real_inv, ←of_real_mul hx] lemma of_real_div' {x y : ℝ} (hy : 0 ≤ y) : nnreal.of_real (x / y) = nnreal.of_real x / nnreal.of_real y := by rw [div_eq_inv_mul, div_eq_inv_mul, of_real_mul (inv_nonneg.2 hy), of_real_inv] end inv @[simp] lemma abs_eq (x : ℝ≥0) : abs (x : ℝ) = x := abs_of_nonneg x.property end nnreal /-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/ @[pp_nodot] def real.nnabs (x : ℝ) : ℝ≥0 := ⟨abs x, abs_nonneg x⟩ @[norm_cast, simp] lemma nnreal.coe_nnabs (x : ℝ) : (real.nnabs x : ℝ) = abs x := by simp [real.nnabs] @[simp] lemma real.nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : real.nnabs x = nnreal.of_real x := by { ext, simp [nnreal.coe_of_real x h, abs_of_nonneg h] } lemma nnreal.coe_of_real_le (x : ℝ) : (nnreal.of_real x : ℝ) ≤ abs x := begin by_cases h : 0 ≤ x, { simp [h, nnreal.coe_of_real x h, le_abs_self] }, { simp [nnreal.of_real, h, le_abs_self, abs_nonneg] } end
734828e4819a44dc968f72073b19a39f456fc809
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/metric_space/basic.lean
de0baf9a61b0a4e4b30ce51caa71efd7d806bb4f
[ "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
139,643
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import tactic.positivity import topology.algebra.order.compact import topology.metric_space.emetric_space import topology.bornology.constructions /-! # Metric spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines metric spaces. Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity ## Main definitions * `has_dist α`: Endows a space `α` with a function `dist a b`. * `pseudo_metric_space α`: A space endowed with a distance function, which can be zero even if the two elements are non-equal. * `metric.ball x ε`: The set of all points `y` with `dist y x < ε`. * `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded. * `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`. Additional useful definitions: * `nndist a b`: `dist` as a function to the non-negative reals. * `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`. * `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`. * `proper_space α`: A `pseudo_metric_space` where all closed balls are compact. * `metric.diam s` : The `supr` of the distances of members of `s`. Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite. TODO (anyone): Add "Main results" section. ## Implementation notes Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize to `metric_space` at the end. ## Tags metric, pseudo_metric, dist -/ open set filter topological_space bornology open_locale uniformity topology big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} {X ι : Type*} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_fun dist dist_self dist_comm dist_triangle $ λ ε ε0, ⟨ε / 2, half_pos ε0, λ x hx y hy, add_halves ε ▸ add_lt_add hx hy⟩ /-- This is an internal lemma used to construct a bornology from a metric in `bornology.of_dist`. -/ private lemma bounded_iff_aux {α : Type*} (dist : α → α → ℝ) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (s : set α) (a : α) : (∃ c, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ c) ↔ (∃ r, ∀ ⦃x⦄, x ∈ s → dist x a ≤ r) := begin split; rintro ⟨C, hC⟩, { rcases s.eq_empty_or_nonempty with rfl | ⟨x, hx⟩, { exact ⟨0, by simp⟩ }, { exact ⟨C + dist x a, λ y hy, (dist_triangle y x a).trans (add_le_add_right (hC hy hx) _)⟩ } }, { exact ⟨C + C, λ x hx y hy, (dist_triangle x a y).trans (add_le_add (hC hx) (by {rw dist_comm, exact hC hy}))⟩ } end /-- Construct a bornology from a distance function and metric space axioms. -/ def bornology.of_dist {α : Type*} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : bornology α := bornology.of_bounded { s : set α | ∃ C, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C } ⟨0, λ x hx y, hx.elim⟩ (λ s ⟨c, hc⟩ t h, ⟨c, λ x hx y hy, hc (h hx) (h hy)⟩) (λ s hs t ht, begin rcases s.eq_empty_or_nonempty with rfl | ⟨z, hz⟩, { exact (empty_union t).symm ▸ ht }, { simp only [λ u, bounded_iff_aux dist dist_comm dist_triangle u z] at hs ht ⊢, rcases ⟨hs, ht⟩ with ⟨⟨r₁, hr₁⟩, ⟨r₂, hr₂⟩⟩, exact ⟨max r₁ r₂, λ x hx, or.elim hx (λ hx', (hr₁ hx').trans (le_max_left _ _)) (λ hx', (hr₂ hx').trans (le_max_right _ _))⟩ } end) (λ z, ⟨0, λ x hx y hy, by { rw [eq_of_mem_singleton hx, eq_of_mem_singleton hy], exact (dist_self z).le }⟩) /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ @[ext] class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/ private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_right this zero_lt_two /-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is used. -/ protected meta def pseudo_metric_space.edist_dist_tac : tactic unit := tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac] /-- Pseudo metric and Metric spaces A pseudo metric space is endowed with a distance for which the requirement `d(x,y)=0 → x = y` might not hold. A metric space is a pseudo metric space such that `d(x,y)=0 → x = y`. Each pseudo metric space induces a canonical `uniform_space` and hence a canonical `topological_space` This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each (pseudo) metric space induces a (pseudo) emetric space structure. It is included in the structure, but filled in by default. -/ class pseudo_metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ℝ≥0∞ := λ x y, @coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) (to_bornology : bornology α := bornology.of_dist dist dist_self dist_comm dist_triangle) (cobounded_sets : (bornology.cobounded α).sets = { s | ∃ C, ∀ ⦃x⦄, x ∈ sᶜ → ∀ ⦃y⦄, y ∈ sᶜ → dist x y ≤ C } . control_laws_tac) /-- Two pseudo metric space structures with the same distance function coincide. -/ @[ext] lemma pseudo_metric_space.ext {α : Type*} {m m' : pseudo_metric_space α} (h : m.to_has_dist = m'.to_has_dist) : m = m' := begin unfreezingI { rcases m, rcases m' }, dsimp at h, unfreezingI { subst h }, congr, { ext x y : 2, dsimp at m_edist_dist m'_edist_dist, simp [m_edist_dist, m'_edist_dist] }, { dsimp at m_uniformity_dist m'_uniformity_dist, rw ← m'_uniformity_dist at m_uniformity_dist, exact uniform_space_eq m_uniformity_dist }, { ext1, dsimp at m_cobounded_sets m'_cobounded_sets, rw ← m'_cobounded_sets at m_cobounded_sets, exact filter_eq m_cobounded_sets } end variables [pseudo_metric_space α] attribute [priority 100, instance] pseudo_metric_space.to_uniform_space attribute [priority 100, instance] pseudo_metric_space.to_bornology @[priority 200] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩ /-- Construct a pseudo-metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def pseudo_metric_space.of_dist_topology {α : Type u} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) : pseudo_metric_space α := { dist := dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := { is_open_uniformity := λ s, (H s).trans $ forall₂_congr $ λ x _, ((uniform_space.has_basis_of_fun (exists_gt (0 : ℝ)) dist _ _ _ _).comap (prod.mk x)).mem_iff.symm.trans mem_comap_prod_mk, to_core := (uniform_space_of_dist dist dist_self dist_comm dist_triangle).to_core }, uniformity_dist := rfl, to_bornology := bornology.of_dist dist dist_self dist_comm dist_triangle, cobounded_sets := rfl } @[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := pseudo_metric_space.edist_dist x y theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := pseudo_metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 } lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 } /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico_self, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) := nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle section open tactic tactic.positivity /-- Extension for the `positivity` tactic: distances are nonnegative. -/ @[positivity] meta def _root_.tactic.positivity_dist : expr → tactic strictness | `(dist %%a %%b) := nonnegative <$> mk_app ``dist_nonneg [a, b] | _ := failed end @[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b := abs_of_nonneg dist_nonneg /-- A version of `has_dist` that takes value in `ℝ≥0`. -/ class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0) export has_nndist (nndist) /-- Distance as a nonnegative real number. -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] } @[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y := (edist_nndist x y).symm @[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} : edist x y < c ↔ nndist x y < c := by rw [edist_nndist, ennreal.coe_lt_coe] @[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} : edist x y ≤ c ↔ nndist x y ≤ c := by rw [edist_nndist, ennreal.coe_le_coe] /--In a pseudometric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ := (edist_dist x y).symm ▸ ennreal.of_real_lt_top /--In a pseudometric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl @[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y := (dist_nndist x y).symm @[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} : dist x y < c ↔ nndist x y < c := iff.rfl @[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} : dist x y ≤ c ↔ nndist x y ≤ c := iff.rfl @[simp] lemma edist_lt_of_real {x y : α} {r : ℝ} : edist x y < ennreal.of_real r ↔ dist x y < r := by rw [edist_dist, ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg] @[simp] lemma edist_le_of_real {x y : α} {r : ℝ} (hr : 0 ≤ r) : edist x y ≤ ennreal.of_real r ↔ dist x y ≤ r := by rw [edist_dist, ennreal.of_real_le_of_real_iff hr] /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) := by rw [dist_nndist, real.to_nnreal_coe] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := dist_triangle _ _ _ theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := dist_triangle_left _ _ _ theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := dist_triangle_right _ _ _ /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate pseudometric space as a topology -/ variables {x y z : α} {δ ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw [dist_comm, mem_ball] theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := dist_nonneg.trans_lt hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption @[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε := ⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩ @[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt] @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty] /-- If a point belongs to an open ball, then there is a strictly smaller radius whose ball also contains it. See also `exists_lt_subset_ball`. -/ lemma exists_lt_mem_ball_of_mem_ball (h : x ∈ ball y ε) : ∃ ε' < ε, x ∈ ball y ε' := begin simp only [mem_ball] at h ⊢, exact ⟨(ε + dist x y) / 2, by linarith, by linarith⟩, end lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } @[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x) @[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ := Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn, hn.trans (lt_add_one _) /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by rw [dist_comm, mem_closed_ball] /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl theorem mem_sphere' : y ∈ sphere x ε ↔ dist x y = ε := by rw [dist_comm, mem_sphere] theorem ne_of_mem_sphere (h : y ∈ sphere x ε) (hε : ε ≠ 0) : y ≠ x := by { contrapose! hε, symmetry, simpa [hε] using h } theorem nonneg_of_mem_sphere (hy : y ∈ sphere x ε) : 0 ≤ ε := dist_nonneg.trans_eq hy @[simp] theorem sphere_eq_empty_of_neg (hε : ε < 0) : sphere x ε = ∅ := set.eq_empty_iff_forall_not_mem.mpr $ λ y hy, (nonneg_of_mem_sphere hy).not_lt hε theorem sphere_eq_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) : sphere x ε = ∅ := set.eq_empty_iff_forall_not_mem.mpr $ λ y hy, ne_of_mem_sphere hy hε (subsingleton.elim _ _) theorem sphere_is_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) : is_empty (sphere x ε) := by simp only [sphere_eq_empty_of_subsingleton hε, set.has_emptyc.emptyc.is_empty α] theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption @[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε := ⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩ @[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le] /-- Closed balls and spheres coincide when the radius is non-positive -/ theorem closed_ball_eq_sphere_of_nonpos (hε : ε ≤ 0) : closed_ball x ε = sphere x ε := set.ext $ λ _, (hε.trans dist_nonneg).le_iff_eq theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq lemma closed_ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (closed_ball x δ) (ball y ε) := set.disjoint_left.mpr $ λ a ha1 ha2, (h.trans $ dist_triangle_left _ _ _).not_lt $ add_lt_add_of_le_of_lt ha1 ha2 lemma ball_disjoint_closed_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (closed_ball y ε) := (closed_ball_disjoint_ball $ by rwa [add_comm, dist_comm]).symm lemma ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (ball y ε) := (closed_ball_disjoint_ball h).mono_left ball_subset_closed_ball lemma closed_ball_disjoint_closed_ball (h : δ + ε < dist x y) : disjoint (closed_ball x δ) (closed_ball y ε) := set.disjoint_left.mpr $ λ a ha1 ha2, h.not_le $ (dist_triangle_left _ _ _).trans $ add_le_add ha1 ha2 theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := set.disjoint_left.mpr $ λ y hy₁ hy₂, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm.le_bot] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm.le_bot] theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by rw [mem_ball', mem_ball] theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε := by rw [mem_closed_ball', mem_closed_ball] theorem mem_sphere_comm : x ∈ sphere y ε ↔ y ∈ sphere x ε := by rw [mem_sphere', mem_sphere] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h lemma closed_ball_eq_bInter_ball : closed_ball x ε = ⋂ δ > ε, ball x δ := by ext y; rw [mem_closed_ball, ← forall_lt_iff_le', mem_Inter₂]; refl lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... < ε₁ + dist x y : add_lt_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_ball (h : ε₁ < ε₂) : closed_ball x ε₁ ⊆ ball x ε₂ := λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h lemma closed_ball_subset_ball' (h : ε₁ + dist x y < ε₂) : closed_ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... < ε₂ : h lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball (h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y ≤ ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2 lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2 lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := begin rw inter_comm at h, rw [add_comm, dist_comm], exact dist_lt_add_of_nonempty_closed_ball_inter_ball h end lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := dist_lt_add_of_nonempty_closed_ball_inter_ball $ h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl) @[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x) lemma Union_inter_closed_ball_nat (s : set α) (x : α) : (⋃ (n : ℕ), s ∩ closed_ball x n) = s := by rw [← inter_Union, Union_closed_ball_nat, inter_univ] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ /-- If a property holds for all points in closed balls of arbitrarily large radii, then it holds for all points. -/ lemma forall_of_forall_mem_closed_ball (p : α → Prop) (x : α) (H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ closed_ball x R, p y) (y : α) : p y := begin obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x ≤ R), ∀ (z : α), z ∈ closed_ball x R → p z := frequently_iff.1 H (Ici_mem_at_top (dist y x)), exact h _ hR end /-- If a property holds for all points in balls of arbitrarily large radii, then it holds for all points. -/ lemma forall_of_forall_mem_ball (p : α → Prop) (x : α) (H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ ball x R, p y) (y : α) : p y := begin obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x < R), ∀ (z : α), z ∈ ball x R → p z := frequently_iff.1 H (Ioi_mem_at_top (dist y x)), exact h _ hR end theorem is_bounded_iff {s : set α} : is_bounded s ↔ ∃ C : ℝ, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C := by rw [is_bounded_def, ← filter.mem_sets, (@pseudo_metric_space.cobounded_sets α _).out, mem_set_of_eq, compl_compl] theorem is_bounded_iff_eventually {s : set α} : is_bounded s ↔ ∀ᶠ C in at_top, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C := is_bounded_iff.trans ⟨λ ⟨C, h⟩, eventually_at_top.2 ⟨C, λ C' hC' x hx y hy, (h hx hy).trans hC'⟩, eventually.exists⟩ theorem is_bounded_iff_exists_ge {s : set α} (c : ℝ) : is_bounded s ↔ ∃ C, c ≤ C ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C := ⟨λ h, ((eventually_ge_at_top c).and (is_bounded_iff_eventually.1 h)).exists, λ h, is_bounded_iff.2 $ h.imp $ λ _, and.right⟩ theorem is_bounded_iff_nndist {s : set α} : is_bounded s ↔ ∃ C : ℝ≥0, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → nndist x y ≤ C := by simp only [is_bounded_iff_exists_ge 0, nnreal.exists, ← nnreal.coe_le_coe, ← dist_nndist, nnreal.coe_mk, exists_prop] theorem to_uniform_space_eq : ‹pseudo_metric_space α›.to_uniform_space = uniform_space_of_dist dist dist_self dist_comm dist_triangle := uniform_space_eq pseudo_metric_space.uniformity_dist theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw [to_uniform_space_eq], exact uniform_space.has_basis_of_fun (exists_gt _) _ _ _ _ _ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_rat : (𝓤 α).has_basis (λ r : ℚ, 0 < r) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ _, rat.cast_pos.2) $ λ ε hε, let ⟨r, hr0, hrε⟩ := exists_rat_btwn hε in ⟨r, rat.cast_pos.1 hr0, hrε.le⟩ theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, by exact_mod_cast hn.le⟩) theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) := metric.mk_uniformity_basis (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) : (𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ r, and.left) $ λ r hr, ⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩, min_le_left _ _⟩ /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) := metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε := metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := begin simp only [uniformity_basis_dist.uniform_embedding_iff uniformity_basis_dist, exists_prop], refl end /-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩ /-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing uniform convergence using `dist` -/ lemma tendsto_uniformly_on_filter_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {p' : filter β} : tendsto_uniformly_on_filter F f p p' ↔ ∀ ε > 0, ∀ᶠ (n : ι × β) in (p ×ᶠ p'), dist (f n.snd) (F n.fst n.snd) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, refine (H ε εpos).mono (λ n hn, hε hn), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem eventually_nhds_iff {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y := mem_nhds_iff lemma eventually_nhds_iff_ball {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y := mem_nhds_iff /-- A version of `filter.eventually_prod_iff` where the second filter consists of neighborhoods in a pseudo-metric space.-/ lemma eventually_prod_nhds_iff {f : filter ι} {x₀ : α} {p : ι × α → Prop}: (∀ᶠ x in f ×ᶠ 𝓝 x₀, p x) ↔ ∃ (pa : ι → Prop) (ha : ∀ᶠ i in f, pa i) (ε > 0), ∀ {i}, pa i → ∀ {x}, dist x x₀ < ε → p (i, x) := begin simp_rw [eventually_prod_iff, metric.eventually_nhds_iff], refine exists_congr (λ q, exists_congr $ λ hq, _), split, { rintro ⟨r, ⟨ε, hε, hεr⟩, hp⟩, exact ⟨ε, hε, λ i hi x hx, hp hi $ hεr hx⟩ }, { rintro ⟨ε, hε, hp⟩, exact ⟨λ x, dist x x₀ < ε, ⟨ε, hε, λ y, id⟩, @hp⟩ } end /-- A version of `filter.eventually_prod_iff` where the first filter consists of neighborhoods in a pseudo-metric space.-/ lemma eventually_nhds_prod_iff {ι α} [pseudo_metric_space α] {f : filter ι} {x₀ : α} {p : α × ι → Prop}: (∀ᶠ x in 𝓝 x₀ ×ᶠ f, p x) ↔ ∃ (ε > (0 : ℝ)) (pa : ι → Prop) (ha : ∀ᶠ i in f, pa i) , ∀ {x}, dist x x₀ < ε → ∀ {i}, pa i → p (x, i) := begin rw [eventually_swap_iff, metric.eventually_prod_nhds_iff], split; { rintro ⟨a1, a2, a3, a4, a5⟩, refine ⟨a3, a4, a1, a2, λ b1 b2 b3 b4, a5 b4 b2⟩ } end theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1) theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1) theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open_ball.mem_nhds (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem closed_ball_mem_nhds_of_mem {x c : α} {ε : ℝ} (h : x ∈ ball c ε) : closed_ball c ε ∈ 𝓝 x := mem_of_superset (is_open_ball.mem_nhds h) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ, forall_congr $ λ x, by simp; itauto theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] theorem continuous_iff [pseudo_metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } /-- A variant of `tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_max_order β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε := (at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} : is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x := by simp [is_open_iff, subset_singleton_iff, mem_ball] /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball centered at `x` and intersecting `s` only at `x`. -/ lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.ball x ε ∩ s = {x} := nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball of positive radius centered at `x` and intersecting `s` only at `x`. -/ lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.closed_ball x ε ∩ s = {x} := nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx lemma _root_.dense.exists_dist_lt {s : set α} (hs : dense s) (x : α) {ε : ℝ} (hε : 0 < ε) : ∃ y ∈ s, dist x y < ε := begin have : (ball x ε).nonempty, by simp [hε], simpa only [mem_ball'] using hs.exists_mem_open is_open_ball this end lemma _root_.dense_range.exists_dist_lt {β : Type*} {f : β → α} (hf : dense_range f) (x : α) {ε : ℝ} (hε : 0 < ε) : ∃ y, dist x (f y) < ε := exists_range_iff.1 (hf.exists_dist_lt x hε) end metric open metric /-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma pseudo_metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := pseudo_metric.uniformity_basis_edist.eq_binfi /-- A pseudometric space induces a pseudoemetric space -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α := { edist := edist, edist_self := by simp [edist_dist], edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹pseudo_metric_space α› } /-- In a pseudometric space, an open ball of infinite radius is the whole space -/ lemma metric.eball_top_eq_univ (x : α) : emetric.ball x ∞ = set.univ := set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x) /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h /-- Closed balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } @[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ := eq_univ_of_forall $ λ y, edist_lt_top _ _ lemma metric.inseparable_iff {x y : α} : inseparable x y ↔ dist x y = 0 := by rw [emetric.inseparable_iff, edist_nndist, dist_nndist, ennreal.coe_eq_zero, nnreal.coe_eq_zero] /-- Build a new pseudometric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : pseudo_metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans pseudo_metric_space.uniformity_dist } lemma pseudo_metric_space.replace_uniformity_eq {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : m.replace_uniformity H = m := by { ext, refl } /-- Build a new pseudo metric space from an old one where the bundled topological structure is provably (but typically non-definitionaly) equal to some given topological structure. See Note [forgetful inheritance]. -/ @[reducible] def pseudo_metric_space.replace_topology {γ} [U : topological_space γ] (m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) : pseudo_metric_space γ := @pseudo_metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl lemma pseudo_metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) : m.replace_topology H = m := by { ext, refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : pseudo_metric_space α := let m : pseudo_metric_space α := { dist := dist, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := edist, edist_dist := λ x y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the emetric space. -/ def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- Build a new pseudometric space from an old one where the bundled bornology structure is provably (but typically non-definitionaly) equal to some given bornology structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_bornology {α} [B : bornology α] (m : pseudo_metric_space α) (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : pseudo_metric_space α := { to_bornology := B, cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, (H s).trans $ by rw [is_bounded_iff, mem_set_of_eq, compl_compl], .. m } lemma pseudo_metric_space.replace_bornology_eq {α} [m : pseudo_metric_space α] [B : bornology α] (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : pseudo_metric_space.replace_bornology _ H = m := by { ext, refl } /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences (λ n, {p:α×α | dist p.1 p.2 < B n}) (λ n, dist_mem_uniformity $ hB n) H theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a pseudometric space. -/ instance real.pseudo_metric_space : pseudo_metric_space ℝ := { dist := λx y, |x - y|, dist_self := by simp [abs_zero], dist_comm := assume x y, abs_sub_comm _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _ theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| := by simp [real.dist_eq] theorem real.dist_left_le_of_mem_uIcc {x y z : ℝ} (h : y ∈ uIcc x z) : dist x y ≤ dist x z := by simpa only [dist_comm x] using abs_sub_left_of_mem_uIcc h theorem real.dist_right_le_of_mem_uIcc {x y z : ℝ} (h : y ∈ uIcc x z) : dist y z ≤ dist x z := by simpa only [dist_comm _ z] using abs_sub_right_of_mem_uIcc h theorem real.dist_le_of_mem_uIcc {x y x' y' : ℝ} (hx : x ∈ uIcc x' y') (hy : y ∈ uIcc x' y') : dist x y ≤ dist x' y' := abs_sub_le_of_uIcc_subset_uIcc $ uIcc_subset_uIcc (by rwa uIcc_comm) (by rwa uIcc_comm) theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ y' - x' := by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub] using real.dist_le_of_mem_uIcc (Icc_subset_uIcc hx) (Icc_subset_uIcc hy) theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) : dist x y ≤ 1 := by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm] lemma real.ball_eq_Ioo (x r : ℝ) : ball x r = Ioo (x - r) (x + r) := set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq, abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt_comm] lemma real.closed_ball_eq_Icc {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le_comm] theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] theorem real.Icc_eq_closed_ball (x y : ℝ) : Icc x y = closed_ball ((x + y) / 2) ((y - x) / 2) := by rw [real.closed_ball_eq_Icc, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] section metric_ordered variables [preorder α] [compact_Icc_space α] lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) := is_compact_Icc.totally_bounded lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) := totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) := totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) := totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b) end metric_ordered /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h /-- If `u` is a neighborhood of `x`, then for small enough `r`, the closed ball `closed_ball x r` is contained in `u`. -/ lemma eventually_closed_ball_subset {x : α} {u : set α} (hu : u ∈ 𝓝 x) : ∀ᶠ r in 𝓝 (0 : ℝ), closed_ball x r ⊆ u := begin obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u := nhds_basis_closed_ball.mem_iff.1 hu, have : Iic ε ∈ 𝓝 (0 : ℝ) := Iic_mem_nhds εpos, filter_upwards [this] with _ hr using subset.trans (closed_ball_subset_closed_ball hr) hε, end end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the pseudometric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- In a pseudometric space, unifom Cauchy sequences are characterized by the fact that, eventually, the distance between all its elements is uniformly, arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.uniform_cauchy_seq_on_iff {γ : Type*} {F : β → γ → α} {s : set γ} : uniform_cauchy_seq_on F at_top s ↔ ∀ ε : ℝ, ε > 0 → ∃ (N : β), ∀ m : β, m ≥ N → ∀ n : β, n ≥ N → ∀ x : γ, x ∈ s → dist (F m x) (F n x) < ε := begin split, { intros h ε hε, let u := { a : α × α | dist a.fst a.snd < ε }, have hu : u ∈ 𝓤 α := metric.mem_uniformity_dist.mpr ⟨ε, hε, (λ a b, by simp)⟩, rw ←@filter.eventually_at_top_prod_self' _ _ _ (λ m, ∀ x : γ, x ∈ s → dist (F m.fst x) (F m.snd x) < ε), specialize h u hu, rw prod_at_top_at_top_eq at h, exact h.mono (λ n h x hx, set.mem_set_of_eq.mp (h x hx)), }, { intros h u hu, rcases (metric.mem_uniformity_dist.mp hu) with ⟨ε, hε, hab⟩, rcases h ε hε with ⟨N, hN⟩, rw [prod_at_top_at_top_eq, eventually_at_top], use (N, N), intros b hb x hx, rcases hb with ⟨hbl, hbr⟩, exact hab (hN b.fst hbl.ge b.snd hbr.ge x hx), }, end /-- If the distance between `s n` and `s m`, `n ≤ m` is bounded above by `b n` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0' {s : β → α} (b : β → ℝ) (h : ∀ n m : β, n ≤ m → dist (s n) (s m) ≤ b n) (h₀ : tendsto b at_top (𝓝 0)) : cauchy_seq s := metric.cauchy_seq_iff'.2 $ λ ε ε0, (h₀.eventually (gt_mem_nhds ε0)).exists.imp $ λ N hN n hn, calc dist (s n) (s N) = dist (s N) (s n) : dist_comm _ _ ... ≤ b N : h _ _ hn ... < ε : hN /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (𝓝 0)) : cauchy_seq s := cauchy_seq_of_le_tendsto_0' b (λ n m hnm, h _ _ _ le_rfl hnm) h₀ /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, rsuffices ⟨R, R0, H⟩ : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) := λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_rfl, le_rfl⟩, dist_self _⟩, have S0 := λ n, le_cSup (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ (le_trans hn hm') _ (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq /-- Pseudometric space structure pulled back by a function. -/ def pseudo_metric_space.induced {α β} (f : α → β) (m : pseudo_metric_space β) : pseudo_metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := (uniformity_basis_dist.comap _).eq_binfi, to_bornology := bornology.induced f, cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, by simp only [compl_mem_comap, filter.mem_sets, ← is_bounded_def, mem_set_of_eq, compl_compl, is_bounded_iff, ball_image_iff] } /-- Pull back a pseudometric space structure by an inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/ def inducing.comap_pseudo_metric_space {α β} [topological_space α] [pseudo_metric_space β] {f : α → β} (hf : inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_topology hf.induced /-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β] (f : α → β) (h : uniform_inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.pseudo_metric_space {p : α → Prop} : pseudo_metric_space (subtype p) := pseudo_metric_space.induced coe ‹_› theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl theorem subtype.nndist_eq {p : α → Prop} (x y : subtype p) : nndist x y = nndist (x : α) y := rfl namespace mul_opposite @[to_additive] instance : pseudo_metric_space (αᵐᵒᵖ) := pseudo_metric_space.induced mul_opposite.unop ‹_› @[simp, to_additive] theorem dist_unop (x y : αᵐᵒᵖ) : dist (unop x) (unop y) = dist x y := rfl @[simp, to_additive] theorem dist_op (x y : α) : dist (op x) (op y) = dist x y := rfl @[simp, to_additive] theorem nndist_unop (x y : αᵐᵒᵖ) : nndist (unop x) (unop y) = nndist x y := rfl @[simp, to_additive] theorem nndist_op (x y : α) : nndist (op x) (op y) = nndist x y := rfl end mul_opposite section nnreal instance : pseudo_metric_space ℝ≥0 := subtype.pseudo_metric_space lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl lemma nnreal.nndist_eq (a b : ℝ≥0) : nndist a b = max (a - b) (b - a) := begin wlog h : b ≤ a, { rw [nndist_comm, max_comm], exact this b a (le_of_not_le h) }, rw [← nnreal.coe_eq, ← dist_nndist, nnreal.dist_eq, tsub_eq_zero_iff_le.2 h, max_eq_left (zero_le $ a - b), ← nnreal.coe_sub h, abs_of_nonneg (a - b).coe_nonneg], end @[simp] lemma nnreal.nndist_zero_eq_val (z : ℝ≥0) : nndist 0 z = z := by simp only [nnreal.nndist_eq, max_eq_right, tsub_zero, zero_tsub, zero_le'] @[simp] lemma nnreal.nndist_zero_eq_val' (z : ℝ≥0) : nndist z 0 = z := by { rw nndist_comm, exact nnreal.nndist_zero_eq_val z, } lemma nnreal.le_add_nndist (a b : ℝ≥0) : a ≤ b + nndist a b := begin suffices : (a : ℝ) ≤ (b : ℝ) + (dist a b), { exact nnreal.coe_le_coe.mp this, }, linarith [le_of_abs_le (by refl : abs (a-b : ℝ) ≤ (dist a b))], end end nnreal section ulift variables [pseudo_metric_space β] instance : pseudo_metric_space (ulift β) := pseudo_metric_space.induced ulift.down ‹_› lemma ulift.dist_eq (x y : ulift β) : dist x y = dist x.down y.down := rfl lemma ulift.nndist_eq (x y : ulift β) : nndist x y = nndist x.down y.down := rfl @[simp] lemma ulift.dist_up_up (x y : β) : dist (ulift.up x) (ulift.up y) = dist x y := rfl @[simp] lemma ulift.nndist_up_up (x y : β) : nndist (ulift.up x) (ulift.up y) = nndist x y := rfl end ulift section prod variables [pseudo_metric_space β] instance prod.pseudo_metric_space_max : pseudo_metric_space (α × β) := (pseudo_emetric_space.to_pseudo_metric_space_of_dist (λ x y : α × β, dist x.1 y.1 ⊔ dist x.2 y.2) (λ x y, (max_lt (edist_lt_top _ _) (edist_lt_top _ _)).ne) (λ x y, by simp only [sup_eq_max, dist_edist, ← ennreal.to_real_max (edist_ne_top _ _) (edist_ne_top _ _), prod.edist_eq])) .replace_bornology $ λ s, by { simp only [← is_bounded_image_fst_and_snd, is_bounded_iff_eventually, ball_image_iff, ← eventually_and, ← forall_and_distrib, ← max_le_iff], refl } lemma prod.dist_eq {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl @[simp] lemma dist_prod_same_left {x : α} {y₁ y₂ : β} : dist (x, y₁) (x, y₂) = dist y₁ y₂ := by simp [prod.dist_eq, dist_nonneg] @[simp] lemma dist_prod_same_right {x₁ x₂ : α} {y : β} : dist (x₁, y) (x₂, y) = dist x₁ x₂ := by simp [prod.dist_eq, dist_nonneg] theorem ball_prod_same (x : α) (y : β) (r : ℝ) : ball x r ×ˢ ball y r = ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] theorem closed_ball_prod_same (x : α) (y : β) (r : ℝ) : closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] theorem sphere_prod (x : α × β) (r : ℝ) : sphere x r = sphere x.1 r ×ˢ closed_ball x.2 r ∪ closed_ball x.1 r ×ˢ sphere x.2 r := begin obtain hr | rfl | hr := lt_trichotomy r 0, { simp [hr], }, { cases x, simp_rw [←closed_ball_eq_sphere_of_nonpos le_rfl, union_self, closed_ball_prod_same] }, { ext ⟨x', y'⟩, simp_rw [set.mem_union, set.mem_prod, metric.mem_closed_ball, metric.mem_sphere, prod.dist_eq, max_eq_iff], refine or_congr (and_congr_right _) ((and_comm _ _).trans (and_congr_left _)), all_goals { rintro rfl, refl } }, end end prod theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous.dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist.comp (hf.prod_mk hg) @[continuity] theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist.continuous @[continuity] theorem continuous.dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist.comp (hf.prod_mk hg : _) theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma continuous_iff_continuous_dist [topological_space β] {f : β → α} : continuous f ↔ continuous (λ x : β × β, dist (f x.1) (f x.2)) := ⟨λ h, (h.comp continuous_fst).dist (h.comp continuous_snd), λ h, continuous_iff_continuous_at.2 $ λ x, tendsto_iff_dist_tendsto_zero.2 $ (h.comp (continuous_id.prod_mk continuous_const)).tendsto' _ _ $ dist_self _⟩ lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_dist.subtype_mk _ lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist.continuous lemma continuous.nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist.comp (hf.prod_mk hg : _) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq @[simp] theorem closure_sphere : closure (sphere x ε) = sphere x ε := is_closed_sphere.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-characterization of the closure in pseudometric spaces-/ theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a lemma closed_ball_zero' (x : α) : closed_ball x 0 = closure {x} := subset.antisymm (λ y hy, mem_closure_iff.2 $ λ ε ε0, ⟨x, mem_singleton x, (mem_closed_ball.1 hy).trans_lt ε0⟩) (closure_minimal (singleton_subset_iff.2 (dist_self x).le) is_closed_ball) lemma dense_iff {s : set α} : dense s ↔ ∀ x, ∀ r > 0, (ball x r ∩ s).nonempty := forall_congr $ λ x, by simp only [mem_closure_iff, set.nonempty, exists_prop, mem_inter_iff, mem_ball', and_comm] lemma dense_range_iff {f : β → α} : dense_range f ↔ ∀ x, ∀ r > 0, ∃ y, dist x (f y) < r := forall_congr $ λ x, by simp only [mem_closure_iff, exists_range_iff] /-- If a set `s` is separable, then the corresponding subtype is separable in a metric space. This is not obvious, as the countable set whose closure covers `s` does not need in general to be contained in `s`. -/ lemma _root_.topological_space.is_separable.separable_space {s : set α} (hs : is_separable s) : separable_space s := begin classical, rcases eq_empty_or_nonempty s with rfl|⟨⟨x₀, x₀s⟩⟩, { apply_instance }, rcases hs with ⟨c, hc, h'c⟩, haveI : encodable c := hc.to_encodable, obtain ⟨u, -, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), let f : c × ℕ → α := λ p, if h : (metric.ball (p.1 : α) (u p.2) ∩ s).nonempty then h.some else x₀, have fs : ∀ p, f p ∈ s, { rintros ⟨y, n⟩, by_cases h : (ball (y : α) (u n) ∩ s).nonempty, { simpa only [f, h, dif_pos] using h.some_spec.2 }, { simpa only [f, h, not_false_iff, dif_neg] } }, let g : c × ℕ → s := λ p, ⟨f p, fs p⟩, apply separable_space_of_dense_range g, apply metric.dense_range_iff.2, rintros ⟨x, xs⟩ r (rpos : 0 < r), obtain ⟨n, hn⟩ : ∃ n, u n < r / 2 := ((tendsto_order.1 u_lim).2 _ (half_pos rpos)).exists, obtain ⟨z, zc, hz⟩ : ∃ z ∈ c, dist x z < u n := metric.mem_closure_iff.1 (h'c xs) _ (u_pos n), refine ⟨(⟨z, zc⟩, n), _⟩, change dist x (f (⟨z, zc⟩, n)) < r, have A : (metric.ball z (u n) ∩ s).nonempty := ⟨x, hz, xs⟩, dsimp [f], simp only [A, dif_pos], calc dist x A.some ≤ dist x z + dist z A.some : dist_triangle _ _ _ ... < r/2 + r/2 : add_lt_add (hz.trans hn) ((metric.mem_ball'.1 A.some_spec.1).trans hn) ... = r : add_halves _ end /-- The preimage of a separable set by an inducing map is separable. -/ protected lemma _root_.inducing.is_separable_preimage {f : β → α} [topological_space β] (hf : inducing f) {s : set α} (hs : is_separable s) : is_separable (f ⁻¹' s) := begin haveI : second_countable_topology s, { haveI : separable_space s := hs.separable_space, exact uniform_space.second_countable_of_separable _ }, let g : f ⁻¹' s → s := cod_restrict (f ∘ coe) s (λ x, x.2), have : inducing g := (hf.comp inducing_coe).cod_restrict _, haveI : second_countable_topology (f ⁻¹' s) := this.second_countable_topology, rw show f ⁻¹' s = coe '' (univ : set (f ⁻¹' s)), by simpa only [image_univ, subtype.range_coe_subtype], exact (is_separable_of_separable_space _).image continuous_subtype_coe end protected lemma _root_.embedding.is_separable_preimage {f : β → α} [topological_space β] (hf : embedding f) {s : set α} (hs : is_separable s) : is_separable (f ⁻¹' s) := hf.to_inducing.is_separable_preimage hs /-- If a map is continuous on a separable set `s`, then the image of `s` is also separable. -/ lemma _root_.continuous_on.is_separable_image [topological_space β] {f : α → β} {s : set α} (hf : continuous_on f s) (hs : is_separable s) : is_separable (f '' s) := begin rw show f '' s = s.restrict f '' univ, by ext ; simp, exact (is_separable_univ_iff.2 hs.separable_space).image (continuous_on_iff_continuous_restrict.1 hf), end end metric section pi open finset variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] /-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/ instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) := begin /- we construct the instance from the pseudoemetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine (pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g : Π b, π b, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ)) (λ f g, _) (λ f g, _)).replace_bornology (λ s, _), show edist f g ≠ ⊤, from ne_of_lt ((finset.sup_lt_iff bot_lt_top).2 $ λ b hb, edist_lt_top _ _), show ↑(sup univ (λ b, nndist (f b) (g b))) = (sup univ (λ b, edist (f b) (g b))).to_real, by simp only [edist_nndist, ← ennreal.coe_finset_sup, ennreal.coe_to_real], show (@is_bounded _ pi.bornology s ↔ @is_bounded _ pseudo_metric_space.to_bornology _), { simp only [← is_bounded_def, is_bounded_iff_eventually, ← forall_is_bounded_image_eval_iff, ball_image_iff, ← eventually_all, function.eval_apply, @dist_nndist (π _)], refine eventually_congr ((eventually_ge_at_top 0).mono $ λ C hC, _), lift C to ℝ≥0 using hC, refine ⟨λ H x hx y hy, nnreal.coe_le_coe.2 $ finset.sup_le $ λ b hb, H b x hx y hy, λ H b x hx y hy, nnreal.coe_le_coe.2 _⟩, simpa only using finset.sup_le_iff.1 (nnreal.coe_le_coe.1 $ H hx hy) b (finset.mem_univ b) } end lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) := nnreal.eq rfl lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl lemma nndist_pi_le_iff {f g : Πb, π b} {r : ℝ≥0} : nndist f g ≤ r ↔ ∀b, nndist (f b) (g b) ≤ r := by simp [nndist_pi_def] lemma nndist_pi_lt_iff {f g : Πb, π b} {r : ℝ≥0} (hr : 0 < r) : nndist f g < r ↔ ∀ b, nndist (f b) (g b) < r := by simp [nndist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)] lemma nndist_pi_eq_iff {f g : Π b, π b} {r : ℝ≥0} (hr : 0 < r) : nndist f g = r ↔ (∃ i, nndist (f i) (g i) = r) ∧ ∀ b, nndist (f b) (g b) ≤ r := begin rw [eq_iff_le_not_lt, nndist_pi_lt_iff hr, nndist_pi_le_iff, not_forall, and_comm], simp_rw [not_lt, and.congr_left_iff, le_antisymm_iff], intro h, refine exists_congr (λ b, _), apply (and_iff_right $ h _).symm, end lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to ℝ≥0 using hr.le, exact nndist_pi_lt_iff hr, end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to ℝ≥0 using hr, exact nndist_pi_le_iff end lemma dist_pi_eq_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g = r ↔ (∃ i, dist (f i) (g i) = r) ∧ ∀ b, dist (f b) (g b) ≤ r := begin lift r to ℝ≥0 using hr.le, simp_rw [←coe_nndist, nnreal.coe_eq, nndist_pi_eq_iff hr, nnreal.coe_le_coe], end lemma dist_pi_le_iff' [nonempty β] {f g : Π b, π b} {r : ℝ} : dist f g ≤ r ↔ ∀ b, dist (f b) (g b) ≤ r := begin by_cases hr : 0 ≤ r, { exact dist_pi_le_iff hr }, { exact iff_of_false (λ h, hr $ dist_nonneg.trans h) (λ h, hr $ dist_nonneg.trans $ h $ classical.arbitrary _) } end lemma dist_pi_const_le (a b : α) : dist (λ _ : β, a) (λ _, b) ≤ dist a b := (dist_pi_le_iff dist_nonneg).2 $ λ _, le_rfl lemma nndist_pi_const_le (a b : α) : nndist (λ _ : β, a) (λ _, b) ≤ nndist a b := nndist_pi_le_iff.2 $ λ _, le_rfl @[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b := by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b) @[simp] lemma nndist_pi_const [nonempty β] (a b : α) : nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g := by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) } lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g := by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b] /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'` for a version assuming `nonempty β` instead of `0 < r`. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = set.pi univ (λ b, ball (x b) r) := by { ext p, simp [dist_pi_lt_iff hr] } /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi` for a version assuming `0 < r` instead of `nonempty β`. -/ lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : ball x r = set.pi univ (λ b, ball (x b) r) := (lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr] /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'` for a version assuming `nonempty β` instead of `0 ≤ r`. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := by { ext p, simp [dist_pi_le_iff hr] } /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi` for a version assuming `0 ≤ r` instead of `nonempty β`. -/ lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := (le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr] /-- A sphere in a product space is a union of spheres on each component restricted to the closed ball. -/ lemma sphere_pi (x : Πb, π b) {r : ℝ} (h : 0 < r ∨ nonempty β) : sphere x r = (⋃ i : β, function.eval i ⁻¹' sphere (x i) r) ∩ closed_ball x r := begin obtain hr | rfl | hr := lt_trichotomy r 0, { simp [hr], }, { rw [closed_ball_eq_sphere_of_nonpos le_rfl, eq_comm, set.inter_eq_right_iff_subset], letI := h.resolve_left (lt_irrefl _), inhabit β, refine subset_Union_of_subset default _, intros x hx, replace hx := hx.le, rw [dist_pi_le_iff le_rfl] at hx, exact le_antisymm (hx default) dist_nonneg }, { ext, simp [dist_pi_eq_iff hr, dist_pi_le_iff hr.le] }, end @[simp] lemma fin.nndist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*} [Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) : nndist (i.insert_nth x f) (i.insert_nth y g) = max (nndist x y) (nndist f g) := eq_of_forall_ge_iff $ λ c, by simp [nndist_pi_le_iff, i.forall_iff_succ_above] @[simp] lemma fin.dist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*} [Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) : dist (i.insert_nth x f) (i.insert_nth y g) = max (dist x y) (dist f g) := by simp only [dist_nndist, fin.nndist_insert_nth_insert_nth, nnreal.coe_max] lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ dist x' y' := begin refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_uIcc _ _).trans (dist_le_pi_dist _ _ b)); refine Icc_subset_uIcc _, exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩] end end pi section compact /-- Any compact set in a pseudometric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, set.finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls end compact section proper_space open metric /-- A pseudometric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [pseudo_metric_space α] : Prop := (is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) export proper_space (is_compact_closed_ball) /-- In a proper pseudometric space, all spheres are compact. -/ lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : is_compact (sphere x r) := is_compact_of_is_closed_subset (is_compact_closed_ball x r) is_closed_sphere sphere_subset_closed_ball /-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/ instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : compact_space (sphere x r) := is_compact_iff_compact_space.mp (is_compact_sphere _ _) /-- A proper pseudo metric space is sigma compact, and therefore second countable. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin -- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't -- add an instance for `sigma_compact_space`. suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α, rcases em (nonempty α) with ⟨⟨x⟩⟩|hn, { exact ⟨⟨λ n, closed_ball x n, λ n, is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ }, { exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ } end lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) : tendsto (λ y, dist y x) (cocompact α) at_top := (has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr, ⟨closed_ball x r, is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩ lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) : tendsto (dist x) (cocompact α) at_top := by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R le_rfl).inter_right is_closed_ball } end⟩ /- A compact pseudometric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, is_closed_ball.is_compact⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $ λ x ε ε0, is_compact_closed_ball _ _ /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩, have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y yt x xt).le), rcases (is_compact_iff_totally_bounded_is_complete.1 (is_compact_closed_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, -, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A binary product of proper spaces is proper. -/ instance prod_proper_space {α : Type*} {β : Type*} [pseudo_metric_space α] [pseudo_metric_space β] [proper_space α] [proper_space β] : proper_space (α × β) := { is_compact_closed_ball := begin rintros ⟨x, y⟩ r, rw ← closed_ball_prod_same x y, apply (is_compact_closed_ball x r).prod (is_compact_closed_ball y r), end } /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply is_compact_univ_pi (λb, _), apply (h b).is_compact_closed_ball end variables [proper_space α] {x : α} {r : ℝ} {s : set α} /-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' ∈ Ioo 0 r, s ⊆ ball x r' := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne }, { exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ }, have : is_compact s, from is_compact_of_is_closed_subset (is_compact_closed_ball x r) hs (subset.trans h ball_subset_closed_ball), obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x), from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on, have hyr : dist y x < r, from h hys, rcases exists_between hyr with ⟨r', hyr', hrr'⟩, exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩ end /-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' < r, s ⊆ ball x r' := begin cases le_or_lt r 0 with hr hr, { rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s }, exact (exists_lt r).imp (λ r' hr', ⟨hr', empty_subset _⟩) }, { exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) } end end proper_space lemma is_compact.is_separable {s : set α} (hs : is_compact s) : is_separable s := begin haveI : compact_space s := is_compact_iff_compact_space.mp hs, exact is_separable_of_separable_space_subtype s, end namespace metric section second_countable open topological_space /-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which is `ε`-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, s.countable ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _), rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩, choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0), refine ⟨s, hsc, Union₂_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩, exact_mod_cast hyx x end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a pseudometric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} lemma bounded_iff_is_bounded (s : set α) : bounded s ↔ is_bounded s := begin change bounded s ↔ sᶜ ∈ (cobounded α).sets, simp [pseudo_metric_space.cobounded_sets, metric.bounded], end @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x hx y hy, hC x (incl hx) y (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y hy z hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.mono ball_subset_closed_ball /-- Spheres are bounded -/ lemma bounded_sphere : bounded (sphere x r) := bounded_closed_ball.mono sphere_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y hy x hx) _⟩ } }, { exact bounded_closed_ball.mono hC } end lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r := (bounded_iff_subset_ball c).1 h lemma bounded.subset_ball_lt (h : bounded s) (a : ℝ) (c : α) : ∃ r, a < r ∧ s ⊆ closed_ball c r := begin rcases h.subset_ball c with ⟨r, hr⟩, refine ⟨max r (a+1), lt_of_lt_of_le (by linarith) (le_max_right _ _), _⟩, exact subset.trans hr (closed_ball_subset_closed_ball (le_max_left _ _)) end lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := let ⟨C, h⟩ := h in ⟨C, λ a ha b hb, (is_closed_le' C).closure_subset $ map_mem_closure₂ continuous_dist ha hb h⟩ alias bounded_closure_of_bounded ← bounded.closure @[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s := ⟨λ h, h.mono subset_closure, λ h, h.closure⟩ /-- The union of two bounded sets is bounded. -/ lemma bounded.union (hs : bounded s) (ht : bounded t) : bounded (s ∪ t) := begin refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end /-- The union of two sets is bounded iff each of the sets is bounded. -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λ h, ⟨h.mono (by simp), h.mono (by simp)⟩, λ h, h.1.union h.2⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : I.finite) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] protected lemma bounded.prod [pseudo_metric_space β] {s : set α} {t : set β} (hs : bounded s) (ht : bounded t) : bounded (s ×ˢ t) := begin refine bounded_iff_mem_bounded.mpr (λ x hx, _), rcases hs.subset_ball x.1 with ⟨rs, hrs⟩, rcases ht.subset_ball x.2 with ⟨rt, hrt⟩, suffices : s ×ˢ t ⊆ closed_ball x (max rs rt), from bounded_closed_ball.mono this, rw [← @prod.mk.eta _ _ x, ← closed_ball_prod_same], exact prod_mono (hrs.trans $ closed_ball_subset_closed_ball $ le_max_left _ _) (hrt.trans $ closed_ball_subset_closed_ball $ le_max_right _ _) end /-- A totally bounded set is bounded -/ lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s := -- We cover the totally bounded set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball /-- A compact set is bounded -/ lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s := -- A compact set is totally bounded, thus bounded h.totally_bounded.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : s.finite) : bounded s := h.is_compact.bounded alias bounded_of_finite ← _root_.set.finite.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩, by rintro H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩; exact H x y⟩ lemma bounded_range_of_tendsto_cofinite_uniformity {f : β → α} (hf : tendsto (prod.map f f) (cofinite ×ᶠ cofinite) (𝓤 α)) : bounded (range f) := begin rcases (has_basis_cofinite.prod_self.tendsto_iff uniformity_basis_dist).1 hf 1 zero_lt_one with ⟨s, hsf, hs1⟩, rw [← image_univ, ← union_compl_self s, image_union, bounded_union], use [(hsf.image f).bounded, 1], rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact le_of_lt (hs1 (x, y) ⟨hx, hy⟩) end lemma bounded_range_of_cauchy_map_cofinite {f : β → α} (hf : cauchy (map f cofinite)) : bounded (range f) := bounded_range_of_tendsto_cofinite_uniformity $ (cauchy_map_iff.1 hf).2 lemma _root_.cauchy_seq.bounded_range {f : ℕ → α} (hf : cauchy_seq f) : bounded (range f) := bounded_range_of_cauchy_map_cofinite $ by rwa nat.cofinite_eq_at_top lemma bounded_range_of_tendsto_cofinite {f : β → α} {a : α} (hf : tendsto f cofinite (𝓝 a)) : bounded (range f) := bounded_range_of_tendsto_cofinite_uniformity $ (hf.prod_map hf).mono_right $ nhds_prod_eq.symm.trans_le (nhds_le_uniformity a) /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := is_compact_univ.bounded.mono (subset_univ _) lemma bounded_range_of_tendsto (u : ℕ → α) {x : α} (hu : tendsto u at_top (𝓝 x)) : bounded (range u) := hu.cauchy_seq.bounded_range /-- If a function is continuous within a set `s` at every point of a compact set `k`, then it is bounded on some open neighborhood of `k` in `s`. -/ lemma exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at [topological_space β] {k s : set β} {f : β → α} (hk : is_compact k) (hf : ∀ x ∈ k, continuous_within_at f s x) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' (t ∩ s)) := begin apply hk.induction_on, { exact ⟨∅, subset.refl _, is_open_empty, by simp only [image_empty, bounded_empty, empty_inter]⟩ }, { rintros s s' hss' ⟨t, s't, t_open, t_bounded⟩, exact ⟨t, hss'.trans s't, t_open, t_bounded⟩ }, { rintros s s' ⟨t, st, t_open, t_bounded⟩ ⟨t', s't', t'_open, t'_bounded⟩, refine ⟨t ∪ t', union_subset_union st s't', t_open.union t'_open, _⟩, rw [union_inter_distrib_right, image_union], exact t_bounded.union t'_bounded }, { assume x hx, have A : ball (f x) 1 ∈ 𝓝 (f x), from ball_mem_nhds _ zero_lt_one, have B : f ⁻¹' (ball (f x) 1) ∈ 𝓝[s] x, from hf x hx A, obtain ⟨u, u_open, xu, uf⟩ : ∃ (u : set β), is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' ball (f x) 1, from _root_.mem_nhds_within.1 B, refine ⟨u, _, u, subset.refl _, u_open, _⟩, { apply nhds_within_le_nhds, exact u_open.mem_nhds xu }, { apply bounded.mono (image_subset _ uf), exact bounded_ball.mono (image_preimage_subset _ _) } } end /-- If a function is continuous at every point of a compact set `k`, then it is bounded on some open neighborhood of `k`. -/ lemma exists_is_open_bounded_image_of_is_compact_of_forall_continuous_at [topological_space β] {k : set β} {f : β → α} (hk : is_compact k) (hf : ∀ x ∈ k, continuous_at f x) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' t) := begin simp_rw ← continuous_within_at_univ at hf, simpa only [inter_univ] using exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at hk hf, end /-- If a function is continuous on a set `s` containing a compact set `k`, then it is bounded on some open neighborhood of `k` in `s`. -/ lemma exists_is_open_bounded_image_inter_of_is_compact_of_continuous_on [topological_space β] {k s : set β} {f : β → α} (hk : is_compact k) (hks : k ⊆ s) (hf : continuous_on f s) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' (t ∩ s)) := exists_is_open_bounded_image_inter_of_is_compact_of_forall_continuous_within_at hk (λ x hx, hf x (hks hx)) /-- If a function is continuous on a neighborhood of a compact set `k`, then it is bounded on some open neighborhood of `k`. -/ lemma exists_is_open_bounded_image_of_is_compact_of_continuous_on [topological_space β] {k s : set β} {f : β → α} (hk : is_compact k) (hs : is_open s) (hks : k ⊆ s) (hf : continuous_on f s) : ∃ t, k ⊆ t ∧ is_open t ∧ bounded (f '' t) := exists_is_open_bounded_image_of_is_compact_of_forall_continuous_at hk (λ x hx, hf.continuous_at (hs.mem_nhds (hks hx))) /-- The **Heine–Borel theorem**: In a proper space, a closed bounded set is compact. -/ lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) : is_compact s := begin unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) }, { exact is_compact_empty }, { rcases hb.subset_ball x with ⟨r, hr⟩, exact is_compact_of_is_closed_subset (is_compact_closed_ball x r) hc hr } end /-- The **Heine–Borel theorem**: In a proper space, the closure of a bounded set is compact. -/ lemma bounded.is_compact_closure [proper_space α] (h : bounded s) : is_compact (closure s) := is_compact_of_is_closed_bounded is_closed_closure h.closure /-- The **Heine–Borel theorem**: In a proper Hausdorff space, a set is compact if and only if it is closed and bounded. -/ lemma is_compact_iff_is_closed_bounded [t2_space α] [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩ lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) := ⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩ section conditionally_complete_linear_order variables [preorder α] [compact_Icc_space α] lemma bounded_Icc (a b : α) : bounded (Icc a b) := (totally_bounded_Icc a b).bounded lemma bounded_Ico (a b : α) : bounded (Ico a b) := (totally_bounded_Ico a b).bounded lemma bounded_Ioc (a b : α) : bounded (Ioc a b) := (totally_bounded_Ioc a b).bounded lemma bounded_Ioo (a b : α) : bounded (Ioo a b) := (totally_bounded_Ioo a b).bounded /-- In a pseudo metric space with a conditionally complete linear order such that the order and the metric structure give the same topology, any order-bounded set is metric-bounded. -/ lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) : bounded s := let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u) end conditionally_complete_linear_order end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top $ ediam_le_of_forall_dist_le hC) (λ h, ⟨diam s, λ x hx y hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h lemma ediam_univ_eq_top_iff_noncompact [proper_space α] : emetric.diam (univ : set α) = ∞ ↔ noncompact_space α := by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not] @[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] : emetric.diam (univ : set α) = ∞ := ediam_univ_eq_top_iff_noncompact.mpr ‹_› @[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] : diam (univ : set α) = 0 := by simp [diam] /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ := by rwa [bounded_iff_ediam_ne_top, not_not] at h /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := by rw [diam, ediam_of_unbounded h, ennreal.top_to_real] /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.mono (subset_union_left _ _), have ht : bounded t, from H.mono (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end lemma diam_le_of_subset_closed_ball {r : ℝ} (hr : 0 ≤ r) (h : s ⊆ closed_ball x r) : diam s ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg zero_le_two hr) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add (h ha) (h hb) ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_subset_closed_ball h subset.rfl /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r := diam_le_of_subset_closed_ball h ball_subset_closed_ball /-- If a family of complete sets with diameter tending to `0` is such that each finite intersection is nonempty, then the total intersection is also nonempty. -/ lemma _root_.is_complete.nonempty_Inter_of_nonempty_bInter {s : ℕ → set α} (h0 : is_complete (s 0)) (hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty) (h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) : (⋂ n, s n).nonempty := begin let u := λ N, (h N).some, have I : ∀ n N, n ≤ N → u N ∈ s n, { assume n N hn, apply mem_of_subset_of_mem _ ((h N).some_spec), assume x hx, simp only [mem_Inter] at hx, exact hx n hn }, have : ∀ n, u n ∈ s 0 := λ n, I 0 n (zero_le _), have : cauchy_seq u, { apply cauchy_seq_of_le_tendsto_0 _ _ h', assume m n N hm hn, exact dist_le_diam_of_mem (h's N) (I _ _ hm) (I _ _ hn) }, obtain ⟨x, hx, xlim⟩ : ∃ (x : α) (H : x ∈ s 0), tendsto (λ (n : ℕ), u n) at_top (𝓝 x) := cauchy_seq_tendsto_of_is_complete h0 (λ n, I 0 n (zero_le _)) this, refine ⟨x, mem_Inter.2 (λ n, _)⟩, apply (hs n).mem_of_tendsto xlim, filter_upwards [Ici_mem_at_top n] with p hp, exact I n p hp, end /-- In a complete space, if a family of closed sets with diameter tending to `0` is such that each finite intersection is nonempty, then the total intersection is also nonempty. -/ lemma nonempty_Inter_of_nonempty_bInter [complete_space α] {s : ℕ → set α} (hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty) (h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) : (⋂ n, s n).nonempty := (hs 0).is_complete.nonempty_Inter_of_nonempty_bInter hs h's h h' end diam lemma exists_local_min_mem_ball [proper_space α] [topological_space β] [conditionally_complete_linear_order β] [order_topology β] {f : α → β} {a z : α} {r : ℝ} (hf : continuous_on f (closed_ball a r)) (hz : z ∈ closed_ball a r) (hf1 : ∀ z' ∈ sphere a r, f z < f z') : ∃ z ∈ ball a r, is_local_min f z := begin simp_rw [← closed_ball_diff_ball] at hf1, exact (is_compact_closed_ball a r).exists_local_min_mem_open ball_subset_closed_ball hf hz hf1 is_open_ball, end end metric namespace tactic open positivity /-- Extension for the `positivity` tactic: the diameter of a set is always nonnegative. -/ @[positivity] meta def positivity_diam : expr → tactic strictness | `(metric.diam %%s) := nonnegative <$> mk_app ``metric.diam_nonneg [s] | e := pp e >>= fail ∘ format.bracket "The expression " " is not of the form `metric.diam s`" end tactic lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α := begin refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _), rcases hs.bounded.subset_ball x with ⟨r, hr⟩, exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩ end lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α := by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) : comap (λ y, dist y x) at_top = cocompact α := (comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) : comap (dist x) at_top = cocompact α := (comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α) (h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) := by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff } /-- We now define `metric_space`, extending `pseudo_metric_space`. -/ class metric_space (α : Type u) extends pseudo_metric_space α : Type u := (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) /-- Two metric space structures with the same distance coincide. -/ @[ext] lemma metric_space.ext {α : Type*} {m m' : metric_space α} (h : m.to_has_dist = m'.to_has_dist) : m = m' := begin have h' : m.to_pseudo_metric_space = m'.to_pseudo_metric_space := pseudo_metric_space.ext h, unfreezingI { rcases m, rcases m' }, dsimp at h', unfreezingI { subst h' }, end /-- Construct a metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def metric_space.of_dist_topology {α : Type u} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) (eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α := { eq_of_dist_eq_zero := eq_of_dist_eq_zero, ..pseudo_metric_space.of_dist_topology dist dist_self dist_comm dist_triangle H } variables {γ : Type w} [metric_space γ] theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero @[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y := by simpa only [not_iff_not] using dist_eq_zero @[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist] namespace metric variables {x : γ} {s : set γ} @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero @[simp] lemma sphere_zero : sphere x 0 = {x} := set.ext $ λ y, dist_eq_zero lemma subsingleton_closed_ball (x : γ) {r : ℝ} (hr : r ≤ 0) : (closed_ball x r).subsingleton := begin rcases hr.lt_or_eq with hr|rfl, { rw closed_ball_eq_empty.2 hr, exact subsingleton_empty }, { rw closed_ball_zero, exact subsingleton_singleton } end lemma subsingleton_sphere (x : γ) {r : ℝ} (hr : r ≤ 0) : (sphere x r).subsingleton := (subsingleton_closed_ball x hr).anti sphere_subset_closed_ball @[priority 100] -- see Note [lower instance priority] instance _root_.metric_space.to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) := begin simp only [uniform_embedding_iff_uniform_inducing, uniformity_basis_dist.uniform_inducing_iff uniformity_basis_dist, exists_prop], refl end /-- If a `pseudo_metric_space` is a T₀ space, then it is a `metric_space`. -/ def _root_.metric_space.of_t0_pseudo_metric_space (α : Type*) [pseudo_metric_space α] [t0_space α] : metric_space α := { eq_of_dist_eq_zero := λ x y hdist, inseparable.eq $ metric.inseparable_iff.2 hdist, ..‹pseudo_metric_space α› } /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance _root_.metric_space.to_emetric_space : emetric_space γ := emetric_space.of_t0_pseudo_emetric_space γ lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε) (hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s := is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α] {ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : closed_embedding f := closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf /-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then `f` is a uniform embedding with respect to the discrete uniformity on `β`. -/ lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f := uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf end metric /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : metric_space γ := { eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, ..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, } lemma metric_space.replace_uniformity_eq {γ} [U : uniform_space γ] (m : metric_space γ) (H : 𝓤[U] = 𝓤[pseudo_emetric_space.to_uniform_space]) : m.replace_uniformity H = m := by { ext, refl } /-- Build a new metric space from an old one where the bundled topological structure is provably (but typically non-definitionaly) equal to some given topological structure. See Note [forgetful inheritance]. -/ @[reducible] def metric_space.replace_topology {γ} [U : topological_space γ] (m : metric_space γ) (H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) : metric_space γ := @metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl lemma metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : metric_space γ) (H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) : m.replace_topology H = m := by { ext, refl } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := @metric_space.of_t0_pseudo_metric_space α (pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h) _ /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [emetric_space α] (h : ∀ x y : α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λ x y, rfl) /-- Build a new metric space from an old one where the bundled bornology structure is provably (but typically non-definitionaly) equal to some given bornology structure. See Note [forgetful inheritance]. -/ def metric_space.replace_bornology {α} [B : bornology α] (m : metric_space α) (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : metric_space α := { to_bornology := B, .. pseudo_metric_space.replace_bornology _ H, .. m } lemma metric_space.replace_bornology_eq {α} [m : metric_space α] [B : bornology α] (H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) : metric_space.replace_bornology _ H = m := by { ext, refl } /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : metric_space β) : metric_space γ := { eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), ..pseudo_metric_space.induced f m.to_pseudo_metric_space } /-- Pull back a metric space structure by a uniform embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ @[reducible] def uniform_embedding.comap_metric_space {α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) : metric_space α := (metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm /-- Pull back a metric space structure by an embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/ @[reducible] def embedding.comap_metric_space {α β} [topological_space α] [metric_space β] (f : α → β) (h : embedding f) : metric_space α := begin letI : uniform_space α := embedding.comap_uniform_space f h, exact uniform_embedding.comap_metric_space f (h.to_uniform_embedding f), end instance subtype.metric_space {α : Type*} {p : α → Prop} [metric_space α] : metric_space (subtype p) := metric_space.induced coe subtype.coe_injective ‹_› @[to_additive] instance {α : Type*} [metric_space α] : metric_space (αᵐᵒᵖ) := metric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_› instance : metric_space empty := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, edist := λ _ _, 0, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, to_uniform_space := empty.uniform_space, uniformity_dist := subsingleton.elim _ _ } instance : metric_space punit.{u + 1} := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, edist := λ _ _, 0, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, to_uniform_space := punit.uniform_space, uniformity_dist := begin simp only, haveI : ne_bot (⨅ ε > (0 : ℝ), 𝓟 {p : punit.{u + 1} × punit.{u + 1} | 0 < ε}), { exact @uniformity.ne_bot _ (uniform_space_of_dist (λ _ _, 0) (λ _, rfl) (λ _ _, rfl) (λ _ _ _, by rw zero_add)) _ }, refine (eq_top_of_ne_bot _).trans (eq_top_of_ne_bot _).symm, end} section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h, ..real.pseudo_metric_space } end real section nnreal instance : metric_space ℝ≥0 := subtype.metric_space end nnreal instance [metric_space β] : metric_space (ulift β) := metric_space.induced ulift.down ulift.down_injective ‹_› section prod instance prod.metric_space_max [metric_space β] : metric_space (γ × β) := { eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, ..prod.pseudo_metric_space_max, } end prod section pi open finset variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ { eq_of_dist_eq_zero := assume f g eq0, begin have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero], have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1, simp only [finset.sup_le_iff] at eq2, exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b) end, ..pseudo_metric_space_pi } end pi namespace metric section second_countable open topological_space /-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric section eq_rel instance {α : Type u} [pseudo_metric_space α] : has_dist (uniform_space.separation_quotient α) := { dist := λ p q, quotient.lift_on₂' p q dist $ λ x y x' y' hx hy, by rw [dist_edist, dist_edist, ← uniform_space.separation_quotient.edist_mk x, ← uniform_space.separation_quotient.edist_mk x', quot.sound hx, quot.sound hy] } lemma uniform_space.separation_quotient.dist_mk {α : Type u} [pseudo_metric_space α] (p q : α) : @dist (uniform_space.separation_quotient α) _ (quot.mk _ p) (quot.mk _ q) = dist p q := rfl instance {α : Type u} [pseudo_metric_space α] : metric_space (uniform_space.separation_quotient α) := emetric_space.to_metric_space_of_dist dist (λ x y, quotient.induction_on₂' x y edist_ne_top) $ λ x y, quotient.induction_on₂' x y dist_edist end eq_rel /-! ### `additive`, `multiplicative` The distance on those type synonyms is inherited without change. -/ open additive multiplicative section variables [has_dist X] instance : has_dist (additive X) := ‹has_dist X› instance : has_dist (multiplicative X) := ‹has_dist X› @[simp] lemma dist_of_mul (a b : X) : dist (of_mul a) (of_mul b) = dist a b := rfl @[simp] lemma dist_of_add (a b : X) : dist (of_add a) (of_add b) = dist a b := rfl @[simp] lemma dist_to_mul (a b : additive X) : dist (to_mul a) (to_mul b) = dist a b := rfl @[simp] lemma dist_to_add (a b : multiplicative X) : dist (to_add a) (to_add b) = dist a b := rfl end section variables [pseudo_metric_space X] instance : pseudo_metric_space (additive X) := ‹pseudo_metric_space X› instance : pseudo_metric_space (multiplicative X) := ‹pseudo_metric_space X› @[simp] lemma nndist_of_mul (a b : X) : nndist (of_mul a) (of_mul b) = nndist a b := rfl @[simp] lemma nndist_of_add (a b : X) : nndist (of_add a) (of_add b) = nndist a b := rfl @[simp] lemma nndist_to_mul (a b : additive X) : nndist (to_mul a) (to_mul b) = nndist a b := rfl @[simp] lemma nndist_to_add (a b : multiplicative X) : nndist (to_add a) (to_add b) = nndist a b := rfl end instance [metric_space X] : metric_space (additive X) := ‹metric_space X› instance [metric_space X] : metric_space (multiplicative X) := ‹metric_space X› instance [pseudo_metric_space X] [proper_space X] : proper_space (additive X) := ‹proper_space X› instance [pseudo_metric_space X] [proper_space X] : proper_space (multiplicative X) := ‹proper_space X› /-! ### Order dual The distance on this type synonym is inherited without change. -/ open order_dual section variables [has_dist X] instance : has_dist Xᵒᵈ := ‹has_dist X› @[simp] lemma dist_to_dual (a b : X) : dist (to_dual a) (to_dual b) = dist a b := rfl @[simp] lemma dist_of_dual (a b : Xᵒᵈ) : dist (of_dual a) (of_dual b) = dist a b := rfl end section variables [pseudo_metric_space X] instance : pseudo_metric_space Xᵒᵈ := ‹pseudo_metric_space X› @[simp] lemma nndist_to_dual (a b : X) : nndist (to_dual a) (to_dual b) = nndist a b := rfl @[simp] lemma nndist_of_dual (a b : Xᵒᵈ) : nndist (of_dual a) (of_dual b) = nndist a b := rfl end instance [metric_space X] : metric_space Xᵒᵈ := ‹metric_space X› instance [pseudo_metric_space X] [proper_space X] : proper_space Xᵒᵈ := ‹proper_space X›
7a1651e99aa6238e3335468c7f8861823048338c
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/limits/over.lean
1789916a4c054c1f6f321a046c9d26b9963c50e7
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,309
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.over import category_theory.adjunction.opposites import category_theory.limits.preserves.basic import category_theory.limits.shapes.pullbacks import category_theory.limits.creates /-! # Limits and colimits in the over and under categories Show that the forgetful functor `forget X : over X ⥤ C` creates colimits, and hence `over X` has any colimits that `C` has (as well as the dual that `forget X : under X ⟶ C` creates limits). Note that the folder `category_theory.limits.shapes.constructions.over` further shows that `forget X : over X ⥤ C` creates connected limits (so `over X` has connected limits), and that `over X` has `J`-indexed products if `C` has `J`-indexed wide pullbacks. TODO: If `C` has binary products, then `forget X : over X ⥤ C` has a right adjoint. -/ noncomputable theory 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] variable {X : C} namespace category_theory.functor /-- We can interpret a functor `F` into the category of arrows with codomain `X` as a cocone over the diagram given by the domains of the arrows in the image of `F` such that the apex of the cocone is `X`. -/ @[simps] def to_cocone (F : J ⥤ over X) : cocone (F ⋙ over.forget X) := { X := X, ι := { app := λ j, (F.obj j).hom } } /-- We can interpret a functor `F` into the category of arrows with domain `X` as a cone over the diagram given by the codomains of the arrows in the image of `F` such that the apex of the cone is `X`. -/ @[simps] def to_cone (F : J ⥤ under X) : cone (F ⋙ under.forget X) := { X := X, π := { app := λ j, (F.obj j).hom } } end category_theory.functor namespace category_theory.over instance : reflects_colimits (forget X) := { reflects_colimits_of_shape := λ J 𝒥₁, { reflects_colimit := λ F, { reflects := λ c t, by exactI { desc := λ s, hom_mk (t.desc ((forget X).map_cocone s)) $ t.hom_ext $ λ j, by { rw t.fac_assoc, exact ((s.ι.app j).w).trans (c.ι.app j).w.symm }, fac' := λ s j, over_morphism.ext (t.fac _ j), uniq' := λ s m w, over_morphism.ext $ t.uniq ((forget X).map_cocone s) m.left (λ j, congr_arg comma_morphism.left (w j)) } } } } instance : creates_colimits (forget X) := { creates_colimits_of_shape := λ J 𝒥₁, by exactI { creates_colimit := λ K, { lifts := λ c t, { lifted_cocone := { X := mk (t.desc K.to_cocone), ι := { app := λ j, hom_mk (c.ι.app j), naturality' := λ j j' f, over_morphism.ext (c.ι.naturality f) } }, valid_lift := cocones.ext (iso.refl _) (λ j, category.comp_id _) } } } } instance has_colimit {F : J ⥤ over X} [has_colimit (F ⋙ forget X)] : has_colimit F := has_colimit_of_created _ (forget X) instance has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := {} instance has_colimits [has_colimits C] : has_colimits (over X) := {} -- We can automatically infer that the forgetful functor preserves colimits example [has_colimits C] : preserves_colimits (forget X) := infer_instance section variables [has_pullbacks C] open tactic /-- When `C` has pullbacks, a morphism `f : X ⟶ Y` induces a functor `over Y ⥤ over X`, by pulling back a morphism along `f`. -/ @[simps] def pullback {X Y : C} (f : X ⟶ Y) : over Y ⥤ over X := { obj := λ g, over.mk (pullback.snd : pullback g.hom f ⟶ X), map := λ g h k, over.hom_mk (pullback.lift (pullback.fst ≫ k.left) pullback.snd (by simp [pullback.condition])) (by tidy) } /-- `over.map f` is left adjoint to `over.pullback f`. -/ def map_pullback_adj {A B : C} (f : A ⟶ B) : over.map f ⊣ pullback f := adjunction.mk_of_hom_equiv { hom_equiv := λ g h, { to_fun := λ X, over.hom_mk (pullback.lift X.left g.hom (over.w X)) (pullback.lift_snd _ _ _), inv_fun := λ Y, begin refine over.hom_mk _ _, refine Y.left ≫ pullback.fst, dsimp, rw [← over.w Y, category.assoc, pullback.condition, category.assoc], refl, end, left_inv := λ X, by { ext, dsimp, simp, }, right_inv := λ Y, begin ext, dsimp, simp only [pullback.lift_fst], dsimp, rw [pullback.lift_snd, ← over.w Y], refl, end } } /-- pullback (𝟙 A) : over A ⥤ over A is the identity functor. -/ def pullback_id {A : C} : pullback (𝟙 A) ≅ 𝟭 _ := adjunction.right_adjoint_uniq (map_pullback_adj _) (adjunction.id.of_nat_iso_left over.map_id.symm) /-- pullback commutes with composition (up to natural isomorphism). -/ def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : pullback (f ≫ g) ≅ pullback g ⋙ pullback f := adjunction.right_adjoint_uniq (map_pullback_adj _) (((map_pullback_adj _).comp _ _ (map_pullback_adj _)).of_nat_iso_left (over.map_comp _ _).symm) instance pullback_is_right_adjoint {A B : C} (f : A ⟶ B) : is_right_adjoint (pullback f) := ⟨_, map_pullback_adj f⟩ end end category_theory.over namespace category_theory.under instance : reflects_limits (forget X) := { reflects_limits_of_shape := λ J 𝒥₁, { reflects_limit := λ F, { reflects := λ c t, by exactI { lift := λ s, hom_mk (t.lift ((forget X).map_cone s)) $ t.hom_ext $ λ j, by { rw [category.assoc, t.fac], exact (s.π.app j).w.symm.trans (c.π.app j).w }, fac' := λ s j, under_morphism.ext (t.fac _ j), uniq' := λ s m w, under_morphism.ext $ t.uniq ((forget X).map_cone s) m.right (λ j, congr_arg comma_morphism.right (w j)) } } } } instance : creates_limits (forget X) := { creates_limits_of_shape := λ J 𝒥₁, by exactI { creates_limit := λ K, { lifts := λ c t, { lifted_cone := { X := mk (t.lift K.to_cone), π := { app := λ j, hom_mk (c.π.app j), naturality' := λ j j' f, under_morphism.ext (c.π.naturality f) } }, valid_lift := cones.ext (iso.refl _) (λ j, (category.id_comp _).symm) } } } } instance has_limit {F : J ⥤ under X} [has_limit (F ⋙ forget X)] : has_limit F := has_limit_of_created F (forget X) instance has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (under X) := {} instance has_limits [has_limits C] : has_limits (under X) := {} -- We can automatically infer that the forgetful functor preserves limits example [has_limits C] : preserves_limits (forget X) := infer_instance section variables [has_pushouts C] /-- When `C` has pushouts, a morphism `f : X ⟶ Y` induces a functor `under X ⥤ under Y`, by pushing a morphism forward along `f`. -/ @[simps] def pushout {X Y : C} (f : X ⟶ Y) : under X ⥤ under Y := { obj := λ g, under.mk (pushout.inr : Y ⟶ pushout g.hom f), map := λ g h k, under.hom_mk (pushout.desc (k.right ≫ pushout.inl) pushout.inr (by { simp [←pushout.condition], })) (by tidy) } end end category_theory.under
311c45b52a5c5f8ec83065c0a03d2b744a67a546
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/control/fix.lean
6342d1d3b4920662faf67e7e141574cf086c9452
[ "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
3,245
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 data.nat.upto import data.stream.basic import data.pfun /-! # Fixed point This module defines a generic `fix` operator for defining recursive computations that are not necessarily well-founded or productive. An instance is defined for `part`. ## Main definition * class `has_fix` * `part.fix` -/ universes u v open_locale classical variables {α : Type*} {β : α → Type*} /-- `has_fix α` gives us a way to calculate the fixed point of function of type `α → α`. -/ class has_fix (α : Type*) := (fix : (α → α) → α) namespace part open part nat nat.upto section basic variables (f : (Π a, part $ β a) → (Π a, part $ β a)) /-- A series of successive, finite approximation of the fixed point of `f`, defined by `approx f n = f^[n] ⊥`. The limit of this chain is the fixed point of `f`. -/ def fix.approx : stream $ Π a, part $ β a | 0 := ⊥ | (nat.succ i) := f (fix.approx i) /-- loop body for finding the fixed point of `f` -/ def fix_aux {p : ℕ → Prop} (i : nat.upto p) (g : Π j : nat.upto p, i < j → Π a, part $ β a) : Π a, part $ β a := f $ λ x : α, assert (¬p (i.val)) $ λ h : ¬ p (i.val), g (i.succ h) (nat.lt_succ_self _) x /-- The least fixed point of `f`. If `f` is a continuous function (according to complete partial orders), it satisfies the equations: 1. `fix f = f (fix f)` (is a fixed point) 2. `∀ X, f X ≤ X → fix f ≤ X` (least fixed point) -/ protected def fix (x : α) : part $ β x := part.assert (∃ i, (fix.approx f i x).dom) $ λ h, well_founded.fix.{1} (nat.upto.wf h) (fix_aux f) nat.upto.zero x protected lemma fix_def {x : α} (h' : ∃ i, (fix.approx f i x).dom) : part.fix f x = fix.approx f (nat.succ $ nat.find h') x := begin let p := λ (i : ℕ), (fix.approx f i x).dom, have : p (nat.find h') := nat.find_spec h', generalize hk : nat.find h' = k, replace hk : nat.find h' = k + (@upto.zero p).val := hk, rw hk at this, revert hk, dsimp [part.fix], rw assert_pos h', revert this, generalize : upto.zero = z, intros, suffices : ∀ x', well_founded.fix (fix._proof_1 f x h') (fix_aux f) z x' = fix.approx f (succ k) x', from this _, induction k generalizing z; intro, { rw [fix.approx,well_founded.fix_eq,fix_aux], congr, ext : 1, rw assert_neg, refl, rw nat.zero_add at this, simpa only [not_not, subtype.val_eq_coe] }, { rw [fix.approx,well_founded.fix_eq,fix_aux], congr, ext : 1, have hh : ¬(fix.approx f (z.val) x).dom, { apply nat.find_min h', rw [hk,nat.succ_add,← nat.add_succ], apply nat.lt_of_succ_le, apply nat.le_add_left }, rw succ_add_eq_succ_add at this hk, rw [assert_pos hh, k_ih (upto.succ z hh) this hk] } end lemma fix_def' {x : α} (h' : ¬ ∃ i, (fix.approx f i x).dom) : part.fix f x = none := by dsimp [part.fix]; rw assert_neg h' end basic end part namespace part instance : has_fix (part α) := ⟨λ f, part.fix (λ x u, f (x u)) ()⟩ end part open sigma namespace pi instance part.has_fix {β} : has_fix (α → part β) := ⟨part.fix⟩ end pi
00f724f151de0067430e1756fbac84f7737151c3
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Elab/Tactic/Location.lean
ffd80097eb523890103e5e20657a434306a128f7
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,005
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 -/ namespace Lean namespace Elab namespace Tactic inductive Location | wildcard | target | localDecls (userNames : Array Name) /- Recall that ``` def locationWildcard := parser! "*" def locationTarget := parser! unicodeSymbol "⊢" "|-" def locationHyp := parser! many1 ident def location := parser! "at " >> (locationWildcard <|> locationTarget <|> locationHyp) ``` -/ def expandLocation (stx : Syntax) : Location := let arg := stx.getArg 1; if arg.getKind == `Lean.Parser.Tactic.locationWildcard then Location.wildcard else if arg.getKind == `Lean.Parser.Tactic.locationTarget then Location.target else Location.localDecls $ (arg.getArg 0).getArgs.map fun stx => stx.getId def expandOptLocation (stx : Syntax) : Location := if stx.isNone then Location.target else expandLocation $ stx.getArg 0 end Tactic end Elab end Lean
61d37aa19d37949dc0e176c0c321b46bd9b611c5
7cef822f3b952965621309e88eadf618da0c8ae9
/src/ring_theory/power_series.lean
bb38cec622bda6abe80be39ecd0275c94adcfc8f
[ "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
56,748
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp order.complete_lattice algebra.ordered_group data.mv_polynomial import algebra.order_functions import ring_theory.ideal_operations /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as φ, for all m ≤ n, and 0 otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `order_add_ge`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `α` as mv_power_series σ α := (σ →₀ ℕ) → α. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as power_series α := mv_power_series unit α. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by (unit →₀ ℕ), which is of course canonically isomorphic to ℕ. We then build some glue to treat formal power series as if they are indexed by ℕ. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical /-- Multivariate formal power series, where `σ` is the index set of the variables and `α` is the coefficient ring.-/ def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α namespace mv_power_series open finsupp variables {σ : Type*} {α : Type*} instance [has_zero α] : has_zero (mv_power_series σ α) := pi.has_zero instance [add_monoid α] : add_monoid (mv_power_series σ α) := pi.add_monoid instance [add_group α] : add_group (mv_power_series σ α) := pi.add_group instance [add_comm_monoid α] : add_comm_monoid (mv_power_series σ α) := pi.add_comm_monoid instance [add_comm_group α] : add_comm_group (mv_power_series σ α) := pi.add_comm_group section add_monoid variables [add_monoid α] variables (α) /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : α →+ mv_power_series σ α := { to_fun := λ a m, if m = n then a else 0, map_zero' := funext $ λ m, by { split_ifs; refl }, map_add' := λ a b, funext $ λ m, show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0), from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] } /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ α) →+ α := { to_fun := λ φ, φ n, map_zero' := rfl, map_add' := λ _ _, rfl } variables {α} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ α} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := rfl @[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) : coeff α n (monomial α n a) = a := if_pos rfl @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff α n (0 : mv_power_series σ α) = 0 := rfl end add_monoid section semiring variables [semiring α] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α) instance : has_one (mv_power_series σ α) := ⟨monomial α (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff α n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl @[simp] lemma coeff_zero_one : coeff α (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial' 0 1 instance : has_mul (mv_power_series σ α) := ⟨λ φ ψ n, (finsupp.antidiagonal n).support.sum (λ p, φ p.1 * ψ p.2)⟩ lemma coeff_mul : coeff α n (φ * ψ) = (finsupp.antidiagonal n).support.sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := rfl protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)]; simp [mem_antidiagonal_support, coeff_one], show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) → (if (i = 0) then 1 else 0) * (coeff α j) φ = 0, intros i j hij h, rw [if_neg, zero_mul], contrapose! h, simpa [h] using hij, end protected lemma mul_one : φ * 1 = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))], rotate, { rintros ⟨i, j⟩ hij h, rw [coeff_one, if_neg, mul_zero], rw mem_antidiagonal_support at hij, contrapose! h, simpa [h] using hij }, all_goals { simp [mem_antidiagonal_support, coeff_one] } end protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := ext $ λ n, begin simp only [coeff_mul], have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.1)).support) (λ x, coeff α x.2.1 φ₁ * coeff α x.2.2 φ₂ * coeff α x.1.2 φ₃), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.2)).support) (λ x, coeff α x.1.1 φ₁ * (coeff α x.2.1 φ₂ * coeff α x.2.2 φ₃)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, rw mul_assoc }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_antidiagonal_support, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } } end instance : semiring (mv_power_series σ α) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring α] : comm_semiring (mv_power_series σ α) := { mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap) (λ p hp, swap_mem_antidiagonal_support hp) (λ p hp, mul_comm _ _) (λ p q hp hq H, by simpa using congr_arg prod.swap H) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩), .. mv_power_series.semiring } instance [ring α] : ring (mv_power_series σ α) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring α] : comm_ring (mv_power_series σ α) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring α] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : α) : monomial α m a * monomial α n b = monomial α (m + n) (a * b) := begin ext k, rw [coeff_mul, coeff_monomial], split_ifs with h, { rw [h, finset.sum_eq_single (m,n)], { rw [coeff_monomial', coeff_monomial'] }, { rintros ⟨i,j⟩ hij hne, rw [ne.def, prod.mk.inj_iff, not_and] at hne, by_cases H : i = m, { rw [coeff_monomial j n b, if_neg (hne H), mul_zero] }, { rw [coeff_monomial, if_neg H, zero_mul] } }, { intro H, rw finsupp.mem_antidiagonal_support at H, exfalso, exact H rfl } }, { rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, by_cases H : i = m, { subst i, have : j ≠ n, { rintro rfl, exact h hij.symm }, { rw [coeff_monomial j n b, if_neg this, mul_zero] } }, { rw [coeff_monomial, if_neg H, zero_mul] } } end variables (σ) (α) /-- The constant multivariate formal power series.-/ def C : α →+* mv_power_series σ α := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, .. monomial α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma monomial_zero_eq_C : monomial α (0 : σ →₀ ℕ) = C σ α := rfl @[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α (0 : σ →₀ ℕ) a = C σ α a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : α) : coeff α n (C σ α a) = if n = 0 then a else 0 := rfl @[simp] lemma coeff_zero_C (a : α) : coeff α (0 : σ →₀ℕ) (C σ α a) = a := coeff_monomial' 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ α := monomial α (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff α n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl lemma coeff_index_single_X (s t : σ) : coeff α (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 := by { simp only [coeff_X, single_right_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff α (single s 1) (X s : mv_power_series σ α) = 1 := if_pos rfl @[simp] lemma coeff_zero_X (s : σ) : coeff α (0 : σ →₀ ℕ) (X s : mv_power_series σ α) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial α (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ α)^n = monomial α (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero], refl }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff α m ((X s : mv_power_series σ α)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] variables (σ) (α) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ α) →+* α := { to_fun := coeff α (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], .. coeff α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma coeff_zero_eq_constant_coeff : coeff α (0 : σ →₀ ℕ) = constant_coeff σ α := rfl @[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ α) : coeff α (0 : σ →₀ ℕ) φ = constant_coeff σ α φ := rfl @[simp] lemma constant_coeff_C (a : α) : constant_coeff σ α (C σ α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ α).comp (C σ α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ α 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ α (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ α) (h : is_unit φ) : is_unit (constant_coeff σ α φ) := h.map' (constant_coeff σ α) instance : semimodule α (mv_power_series σ α) := { smul := λ a φ, C σ α a * φ, one_smul := λ φ, one_mul _, mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc], smul_add := λ a φ ψ, mul_add _ _ _, smul_zero := λ a, mul_zero _, add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul], zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] } end semiring instance [ring α] : module α (mv_power_series σ α) := { ..mv_power_series.semimodule } instance [comm_ring α] : algebra α (mv_power_series σ α) := { to_fun := C σ α, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, rfl, .. mv_power_series.module } section map variables {β : Type*} {γ : Type*} [semiring α] [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ α →+* mv_power_series σ β := { to_fun := λ φ n, f $ coeff α n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff α n) 1) = (coeff β n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff α n) (φ + ψ)) = f ((coeff α n) φ) + f ((coeff α n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id α) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff β n (map σ f φ) = f (coeff α n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ α) : constant_coeff σ β (map σ f φ) = f (constant_coeff σ α φ) := rfl end map section trunc variables [comm_semiring α] (n : σ →₀ ℕ) -- Auxiliary definition for the truncation function. def trunc_fun (φ : mv_power_series σ α) : mv_polynomial σ α := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (α) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ α →+ mv_polynomial σ α := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {α} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ α) : mv_polynomial.coeff m (trunc α n φ) = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_one : trunc α n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : α) : trunc α n (C σ α a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring α] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff α m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff α (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff α m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext t, simp only [nat.add_sub_cancel_left, add_comm, finsupp.add_apply, add_right_inj, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.add_sub_cancel' H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff α m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ α), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring α] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α | n := if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if h : x.2 < n then coeff α x.1 φ * inv.aux x.2 else 0) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ α) (u : units α) : constant_coeff σ α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring α] /-- Multivariate formal power series over a local ring form a local ring.-/ lemma is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) := begin split, { have H : (0:α) ≠ 1 := ‹is_local_ring α›.1, contrapose! H, simpa using congr_arg (constant_coeff σ α) H }, { intro φ, rcases ‹is_local_ring α›.2 (constant_coeff σ α φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_one _ _ (mul_inv_of_unit _ u _), simpa using h } } end -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] instance : nonzero_comm_ring (mv_power_series σ α) := { zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h, .. mv_power_series.comm_ring } lemma X_inj {s t : σ} : (X s : mv_power_series σ α) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff α (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end nonzero_comm_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (mv_power_series σ α) := local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩ instance map.is_local_ring_hom : is_local_ring_hom (map σ f : mv_power_series σ α → mv_power_series σ β) := { map_one := (map σ f).map_one, map_mul := (map σ f).map_mul, map_add := (map σ f).map_add, map_nonunit := begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ β) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ β ↑ψ) := @is_unit_constant_coeff σ β _ (↑ψ) (is_unit_unit ψ), rw ← h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc) end } end local_ring section discrete_field variables [discrete_field α] protected def inv (φ : mv_power_series σ α) : mv_power_series σ α := inv.aux (constant_coeff σ α φ)⁻¹ φ instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff σ α φ)⁻¹ else - (constant_coeff σ α φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ α) : constant_coeff σ α (φ⁻¹) = (constant_coeff σ α φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ α} : φ⁻¹ = 0 ↔ constant_coeff σ α φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ α) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] end discrete_field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ α) (mv_power_series σ α) := ⟨λ φ n, coeff n φ⟩ @[simp, elim_cast] lemma coeff_coe (φ : mv_polynomial σ α) (n : σ →₀ ℕ) : mv_power_series.coeff α n ↑φ = coeff n φ := rfl @[simp, elim_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : α) : (monomial n a : mv_power_series σ α) = mv_power_series.monomial α n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, elim_cast] lemma coe_zero : ((0 : mv_polynomial σ α) : mv_power_series σ α) = 0 := rfl @[simp, elim_cast] lemma coe_one : ((1 : mv_polynomial σ α) : mv_power_series σ α) = 1 := coe_monomial _ _ @[simp, elim_cast] lemma coe_add (φ ψ : mv_polynomial σ α) : ((φ + ψ : mv_polynomial σ α) : mv_power_series σ α) = φ + ψ := rfl @[simp, elim_cast] lemma coe_mul (φ ψ : mv_polynomial σ α) : ((φ * ψ : mv_polynomial σ α) : mv_power_series σ α) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, elim_cast] lemma coe_C (a : α) : ((C a : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.C σ α a := coe_monomial _ _ @[simp, elim_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.X s := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : mv_polynomial σ α → mv_power_series σ α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end mv_polynomial /-- Formal power series over the coefficient ring `α`.-/ def power_series (α : Type*) := mv_power_series unit α namespace power_series open finsupp (single) variable {α : Type*} instance [add_monoid α] : add_monoid (power_series α) := by delta power_series; apply_instance instance [add_group α] : add_group (power_series α) := by delta power_series; apply_instance instance [add_comm_monoid α] : add_comm_monoid (power_series α) := by delta power_series; apply_instance instance [add_comm_group α] : add_comm_group (power_series α) := by delta power_series; apply_instance instance [semiring α] : semiring (power_series α) := by delta power_series; apply_instance instance [comm_semiring α] : comm_semiring (power_series α) := by delta power_series; apply_instance instance [ring α] : ring (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : comm_ring (power_series α) := by delta power_series; apply_instance instance [nonzero_comm_ring α] : nonzero_comm_ring (power_series α) := by delta power_series; apply_instance instance [semiring α] : semimodule α (power_series α) := by delta power_series; apply_instance instance [ring α] : module α (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : algebra α (power_series α) := by delta power_series; apply_instance section add_monoid variables (α) [add_monoid α] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series α →+ α := mv_power_series.coeff α (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : α →+ power_series α := mv_power_series.monomial α (single () n) variables {α} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff α n = mv_power_series.coeff α s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff α n φ = coeff α n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ /-- Constructor for formal power series.-/ def mk (f : ℕ → α) : power_series α := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff α n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := calc coeff α m (monomial α n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : α) : monomial α n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial' (n : ℕ) (a : α) : coeff α n (monomial α n a) = a := by convert if_pos rfl @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n end add_monoid section semiring variable [semiring α] variable (α) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series α →+* α := mv_power_series.constant_coeff unit α /-- The constant formal power series.-/ def C : α →+* power_series α := mv_power_series.C unit α variable {α} /-- The variable of the formal power series ring.-/ def X : power_series α := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : coeff α 0 = constant_coeff α := begin rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl end @[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : power_series α) : coeff α 0 φ = constant_coeff α φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : monomial α 0 = C α := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] @[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α 0 a = C α a := by rw [monomial_zero_eq_C]; refl lemma coeff_C (n : ℕ) (a : α) : coeff α n (C α a : power_series α) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : α) : coeff α 0 (C α a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a] lemma X_eq : (X : power_series α) = monomial α 1 1 := rfl lemma coeff_X (n : ℕ) : coeff α n (X : power_series α) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff α 0 (X : power_series α) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff α 1 (X : power_series α) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series α)^n = monomial α n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff α m ((X : power_series α)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff α n ((X : power_series α)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff α n (1 : power_series α) = if n = 0 then 1 else 0 := calc coeff α n (1 : power_series α) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } @[simp] lemma coeff_zero_one : coeff α 0 (1 : power_series α) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series α) : coeff α n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma constant_coeff_C (a : α) : constant_coeff α (C α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff α).comp (C α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff α 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff α X = 0 := mv_power_series.coeff_zero_X _ /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series α) (h : is_unit φ) : is_unit (constant_coeff α φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {β : Type*} {γ : Type*} [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series α →+* power_series β := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id α) : power_series α → power_series α) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series α) : coeff β n (map f φ) = f (coeff α n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring α] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series α} : (X : power_series α)^n ∣ φ ↔ ∀ m, m < n → coeff α m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit α _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series α} : (X : power_series α) ∣ φ ↔ constant_coeff α φ = 0 := begin rw [← pow_one (X : power_series α), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series α) : polynomial α := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series α) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series α) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series α) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : α) : trunc n (C α a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series α) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring α] protected def inv.aux : α → power_series α → power_series α := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series α) (u : units α) : power_series α := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series α) (u : units α) : constant_coeff α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain α] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series α) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw classical.or_iff_not_imp_left, intro H, have ex : ∃ m, coeff α m φ ≠ 0, { contrapose! H, exact ext H }, let P : ℕ → Prop := λ k, coeff α k φ ≠ 0, let m := nat.find ex, have hm₁ : coeff α m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff α k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff α n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff α (m + n)) h, rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_left_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series α) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nonzero_comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).is_prime := begin suffices : ideal.span ({X} : set (power_series α)) = is_ring_hom.ker (constant_coeff α), { rw this, exact is_ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [is_ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series α) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff α 1) h } end end integral_domain section local_ring variables [comm_ring α] lemma is_local_ring (h : is_local_ring α) : is_local_ring (power_series α) := mv_power_series.is_local_ring h end local_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (power_series α) := mv_power_series.local_ring instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f end local_ring section discrete_field variables [discrete_field α] protected def inv : power_series α → power_series α := mv_power_series.inv instance : has_inv (power_series α) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series α) : φ⁻¹ = inv.aux (constant_coeff α φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff α φ)⁻¹ else - (constant_coeff α φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff α φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series α) : constant_coeff α (φ⁻¹) = (constant_coeff α φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series α} : φ⁻¹ = 0 ↔ constant_coeff α φ = 0 := mv_power_series.inv_eq_zero @[simp] lemma inv_of_unit_eq (φ : power_series α) (h : constant_coeff α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h end discrete_field end power_series namespace power_series variable {α : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring α] /-- The order of a formal power series `φ` is the smallest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series α) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series α) (h : ∃ n, coeff α n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series α) (h : (order φ).dom) : coeff α (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series α) (n : ℕ) (h : coeff α n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series α) (n : ℕ) (h: ↑n < order φ) : coeff α n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The `0` power series is the unique power series with infinite order.-/ lemma order_eq_top {φ : power_series α} : φ.order = ⊤ ↔ φ = 0 := begin rw eq_top_iff, split, { intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) }, { rintros rfl n, exact dvd_zero _ } end /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series α) = ⊤ := multiplicity.zero _ /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge_nat (φ : power_series α) (n : ℕ) (h : ∀ i < n, coeff α i φ = 0) : order φ ≥ n := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge (φ : power_series α) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff α i φ = 0) : order φ ≥ n := begin induction n using enat.cases_on, { show _ ≤ _, rw [lattice.top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply order_ge_nat, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series α} {n : ℕ} : order φ = n ↔ (coeff α n φ ≠ 0) ∧ (∀ i, i < n → coeff α i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series α} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff α i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff α i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma order_add_ge (φ ψ : power_series α) : order (φ + ψ) ≥ min (order φ) (order ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series α) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [lattice.le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series α) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (order_add_ge _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, lattice.inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series α) : order (φ * ψ) ≥ order φ + order ψ := begin apply order_ge, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add' hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : α) : order (monomial α n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, add_monoid_hom.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : α) (h : a ≠ 0) : order (monomial α n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [nonzero_comm_ring α] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series α) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:α) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series α) = 1 := order_monomial_of_ne_zero 1 (1:α) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series α)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain α] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series α) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial α) (power_series α) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, elim_cast] lemma coeff_coe (φ : polynomial α) (n) : power_series.coeff α n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[reducible] def monomial (n : ℕ) (a : α) : polynomial α := single n a @[simp, elim_cast] lemma coe_monomial (n : ℕ) (a : α) : (monomial n a : power_series α) = power_series.monomial α n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, elim_cast] lemma coe_zero : ((0 : polynomial α) : power_series α) = 0 := rfl @[simp, elim_cast] lemma coe_one : ((1 : polynomial α) : power_series α) = 1 := begin have := coe_monomial 0 (1:α), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, elim_cast] lemma coe_add (φ ψ : polynomial α) : ((φ + ψ : polynomial α) : power_series α) = φ + ψ := rfl @[simp, elim_cast] lemma coe_mul (φ ψ : polynomial α) : ((φ * ψ : polynomial α) : power_series α) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, elim_cast] lemma coe_C (a : α) : ((C a : polynomial α) : power_series α) = power_series.C α a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, elim_cast] lemma coe_X : ((X : polynomial α) : power_series α) = power_series.X := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : polynomial α → power_series α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end polynomial
bb8d44cf047ea3d408c113148b4bcf431ed526cd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/finite/trace.lean
59dd268d8dc49b542d1be3aea8129abb1d37374e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,051
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import ring_theory.trace import field_theory.finite.galois_field /-! # The trace map for finite fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We state the fact that the trace map from a finite field of characteristic `p` to `zmod p` is nondegenerate. ## Tags finite field, trace -/ namespace finite_field /-- The trace map from a finite field to its prime field is nongedenerate. -/ lemma trace_to_zmod_nondegenerate (F : Type*) [field F] [finite F] [algebra (zmod (ring_char F)) F] {a : F} (ha : a ≠ 0) : ∃ b : F, algebra.trace (zmod (ring_char F)) F (a * b) ≠ 0 := begin haveI : fact (ring_char F).prime := ⟨char_p.char_is_prime F _⟩, have htr := trace_form_nondegenerate (zmod (ring_char F)) F a, simp_rw [algebra.trace_form_apply] at htr, by_contra' hf, exact ha (htr hf) end end finite_field
235802f3aa0c8f9a860e95f1fe8f9a389eb83ab0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/interval.lean
99845f4cf77e3f85454d78673df39f3a8ca49da9
[ "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,969
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.finsupp import data.finset.locally_finite import data.finsupp.order /-! # Finite intervals of finitely supported functions This file provides the `locally_finite_order` instance for `ι →₀ α` when `α` itself is locally finite and calculates the cardinality of its finite intervals. ## Main declarations * `finsupp.range_singleton`: Postcomposition with `has_singleton.singleton` on `finset` as a `finsupp`. * `finsupp.range_Icc`: Postcomposition with `finset.Icc` as a `finsupp`. Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely supported. -/ noncomputable theory open finset finsupp function open_locale big_operators classical pointwise variables {ι α : Type*} namespace finsupp section range_singleton variables [has_zero α] {f : ι →₀ α} {i : ι} {a : α} /-- Pointwise `finset.singleton` bundled as a `finsupp`. -/ @[simps] def range_singleton (f : ι →₀ α) : ι →₀ finset α := { to_fun := λ i, {f i}, support := f.support, mem_support_to_fun := λ i, begin rw [←not_iff_not, not_mem_support_iff, not_ne_iff], exact singleton_injective.eq_iff.symm, end } lemma mem_range_singleton_apply_iff : a ∈ f.range_singleton i ↔ a = f i := mem_singleton end range_singleton section range_Icc variables [has_zero α] [partial_order α] [locally_finite_order α] {f g : ι →₀ α} {i : ι} {a : α} /-- Pointwise `finset.Icc` bundled as a `finsupp`. -/ @[simps to_fun] def range_Icc (f g : ι →₀ α) : ι →₀ finset α := { to_fun := λ i, Icc (f i) (g i), support := f.support ∪ g.support, mem_support_to_fun := λ i, begin rw [mem_union, ←not_iff_not, not_or_distrib, not_mem_support_iff, not_mem_support_iff, not_ne_iff], exact Icc_eq_singleton_iff.symm, end } @[simp] lemma range_Icc_support [decidable_eq ι] (f g : ι →₀ α) : (range_Icc f g).support = f.support ∪ g.support := by convert rfl lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc end range_Icc section partial_order variables [partial_order α] [has_zero α] [locally_finite_order α] (f g : ι →₀ α) instance : locally_finite_order (ι →₀ α) := locally_finite_order.of_Icc (ι →₀ α) (λ f g, (f.support ∪ g.support).finsupp $ f.range_Icc g) (λ f g x, begin refine (mem_finsupp_iff_of_support_subset $ finset.subset_of_eq $ range_Icc_support _ _).trans _, simp_rw mem_range_Icc_apply_iff, exact forall_and_distrib, end) lemma Icc_eq [decidable_eq ι] : Icc f g = (f.support ∪ g.support).finsupp (f.range_Icc g) := by convert rfl lemma card_Icc [decidable_eq ι] : (Icc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card := by simp_rw [Icc_eq, card_finsupp, range_Icc_to_fun] lemma card_Ico [decidable_eq ι] : (Ico f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc [decidable_eq ι] : (Ioc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo [decidable_eq ι] : (Ioo f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end partial_order section canonically_ordered variables [canonically_ordered_add_monoid α] [locally_finite_order α] variables (f : ι →₀ α) lemma card_Iic : (Iic f).card = ∏ i in f.support, (Iic (f i)).card := by simp_rw [Iic_eq_Icc, card_Icc, finsupp.bot_eq_zero, support_zero, empty_union, zero_apply, bot_eq_zero] lemma card_Iio : (Iio f).card = ∏ i in f.support, (Iic (f i)).card - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end canonically_ordered end finsupp
1c53201c7c521338339d4e22eca8fe0c8844a8fa
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/sheaves/stalks.lean
5d297414b5cd770737aeb75f6ccd1983f52cf017
[ "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
16,368
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 /-! # 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 following functor (nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ ⥤ C where the functor on the left is the inclusion of categories and the functor on the right is `F`. 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`. In `is_iso_iff_stalk_functor_map_iso`, we prove that a map `f : F ⟶ G` between `Type`-valued sheaves is an isomorphism if and only if all the maps `F.stalk x ⟶ G.stalk x` (given by the stalk functor on `f`) are isomorphisms. 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`. -/ 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⟩) /-- For a `Type` valued presheaf, every point in a stalk is a germ. -/ lemma germ_exist (F : X.presheaf (Type v)) (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 _ (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 (Type v)) {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 erw types.filtered_colimit.colimit_eq_iff at h, rcases h with ⟨W, iU, iV, e⟩, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end @[simp] 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 @[simp] lemma germ_res_apply (F : X.presheaf (Type v)) {U V : opens X} (i : U ⟶ V) (x : U) (f : F.obj (op V)) : germ F x (F.map i.op f) = germ F (i x : V) f := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in congr_fun (colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op) f /-- A variant when the open sets are written in `(opens X)ᵒᵖ`. -/ @[simp] lemma germ_res_apply' (F : X.presheaf (Type v)) {U V : (opens X)ᵒᵖ} (i : V ⟶ U) (x : unop U) (f : F.obj V) : germ F x (F.map i f) = germ F (i.unop x : unop V) f := let i' : (⟨unop U, x.2⟩ : open_nhds x.1) ⟶ ⟨unop V, (i.unop x : unop V).2⟩ := i.unop in congr_fun (colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op) f section local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext {D : Type u} [category.{v} D] [concrete_category D] [has_colimits D] (F : X.presheaf D) {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] end 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 { op_induction U, cases U with U hxU, exact ih U hxU } /-- If two sections agree on all stalks, they must be equal -/ lemma section_ext (F : sheaf (Type v) X) (U : opens X) (s t : F.presheaf.obj (op U)) : (∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) → s = t := begin intro h, -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V`, such that the restrictions of `s` and `t` to `V` coincide. Since a restriction -- map `V ⟶ U` is *data* (lives in `Type`, not `Prop`), we encode all of this as a dependent -- pair (sigma type) let V : Π (x : U), Σ (V : open_nhds x.1), { iVU : V.1 ⟶ U // F.presheaf.map iVU.op s = F.presheaf.map iVU.op t } := λ x, by { choose V m iVU₀ iVU₁ heq using (F.presheaf.germ_eq x.1 x.2 x.2 s t (h x)), refine ⟨⟨V,m⟩,iVU₀,_⟩, convert heq, }, refine F.eq_of_locally_eq' (λ x, (V x).1.1) U (λ x, (V x).2.1) _ s t (λ x, (V x).2.2), -- Here, it remains to show that the choosen neighborhoods really define a cover of `U` intros x hxU, rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x,hxU⟩,(V ⟨x,hxU⟩).1.2⟩, end @[simp, reassoc] 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⟩) @[simp] lemma stalk_functor_map_germ_apply (U : opens X) (x : U) {F G : X.presheaf (Type v)} (f : F ⟶ G) (s : F.obj (op U)) : (stalk_functor (Type v) x.1).map f (germ F x s) = germ G x (f.app (op U) s) := congr_fun (stalk_functor_map_germ U x f) s open function lemma stalk_functor_map_injective_of_app_injective {F G : presheaf (Type v) X} (f : F ⟶ G) (h : ∀ U : opens X, injective (f.app (op U))) (x : X) : injective ((stalk_functor (Type v) 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 [← functor_to_types.naturality, ← functor_to_types.naturality] 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 /- 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 (Type v) X} {G : presheaf (Type v) X} (f : F.presheaf ⟶ G) (h : ∀ x : X, injective ((stalk_functor (Type v) x).map f)) (U : opens X) : injective (f.app (op U)) := λ s t hst, begin apply section_ext, intro x, apply h x.1, simp only [stalk_functor_map_germ_apply, hst], end lemma app_injective_iff_stalk_functor_map_injective {F : sheaf (Type v) X} {G : presheaf (Type v) X} (f : F.presheaf ⟶ G) : (∀ x : X, injective ((stalk_functor (Type v) x).map f)) ↔ (∀ U : opens X, injective (f.app (op U))) := ⟨app_injective_of_stalk_functor_map_injective f, stalk_functor_map_injective_of_app_injective f⟩ lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf (Type v) X} (f : F ⟶ G) (h : ∀ x : X, bijective ((stalk_functor (Type v) x).map f)) (U : opens X) : bijective (f.app (op U)) := begin -- We already know that `f.app (op U)` is injective. We save that fact here as we will -- need it again later. have h_inj := app_injective_of_stalk_functor_map_injective f (λ x, (h x).1), refine ⟨h_inj U, (λ t,_)⟩, -- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. -- First, we show that we can find preimages *locally*. That is, for each `x : U` we construct -- neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` -- agree on `V`. have exists_local_preim : ∀ x : U, ∃ (V : open_nhds x.1) (iVU : V.1 ⟶ U) (s : F.presheaf.obj (op V.1)), f.app (op V.1) s = G.presheaf.map iVU.op t := λ x, by { -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t), -- ... and this preimage must come from some section `s₁` 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 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 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 let s₂ := F.presheaf.map iV₂V₁.op s₁, use [V₂,hxV₂,iV₂U,s₂], rwa functor_to_types.naturality }, -- Now, we use the axiom of choice to create a function `local_preim` giving us for each point -- `x : U` a neighborhood `V` and a local preimage for `t` on `V`. have local_preim : Π x : U, Σ (V : open_nhds x.1) (iVU : V.1 ⟶ U), {s : F.presheaf.obj (op V.1) // f.app (op V.1) s = G.presheaf.map iVU.op t } := λ x, by { choose V iVU s heq using exists_local_preim x, exact ⟨V,iVU,s,heq⟩ }, clear exists_local_preim, -- In particular, we obtain a covering family of opens and a family of sections let V : U → opens X := λ x, (local_preim x).1.1, let sf : Π x : U, F.presheaf.obj (op (V x)) := λ x, (local_preim x).2.2.1, have V_cover : U ≤ supr V := λ x hx, by { rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x,hx⟩,(local_preim _).1.2⟩ }, -- Using this data, we can glue all of the local preimages together, giving us our candidate -- for the preimage of `t` obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U (λ x, (local_preim x).2.1) V_cover sf _, use s, -- Note that we generated an additional goal: We need to show that our family of sections `sf` -- is actually compatible. We get that out of the way first. swap, { intros x y, -- The only thing we know about the sections `sf` is that their image under `f` equals (the -- restriction of) `t`. It is at this point that we need injectivity of `f` again! apply h_inj, -- Here, both sides are equal to a restriction of `t` transitivity ; erw [functor_to_types.naturality, (local_preim _).2.2.2, ← functor_to_types.map_comp_apply], refl }, -- The only thing left to prove is that `s` really is a preimage of `t` -- Of course, we show the equality locally apply G.eq_of_locally_eq' V U (λ x, (local_preim x).2.1) V_cover, intro x, convert congr_arg (f.app (op (V x))) (s_spec x), exacts [(functor_to_types.naturality _ _ f _ _).symm, (local_preim x).2.2.2.symm], end /-- If all the stalk maps of map `f : F ⟶ G` of `Type`-valued sheaves are isomorphisms, then `f` is 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 (Type v) X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor (Type v) x).map f)] : is_iso f := begin -- Rather annoyingly, an isomorphism of presheaves isn't quite the same as an isomorphism of -- sheaves. We have to use that the induced functor from sheaves to presheaves is fully faithful haveI : is_iso ((induced_functor sheaf.presheaf).map f) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.presheaf G.presheaf f (by { intro U, op_induction U, rw is_iso_iff_bijective, exact app_bijective_of_stalk_functor_map_bijective f (λ x, (is_iso_iff_bijective _).mp (_inst_3 x)) U, }), exact is_iso_of_fully_faithful (induced_functor sheaf.presheaf) f, end /-- A morphism of `Type`-valued sheaves `f : F ⟶ G` is an isomorphism if and only if all the stalk maps are isomorphisms -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf (Type v) X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor (Type v) x).map f) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor (Type v) x) f ((induced_functor sheaf.presheaf).map_is_iso f) }, { intro h, resetI, exact is_iso_of_stalk_functor_map_iso f } end variables (C) def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.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) ℱ), 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', cases j, cases j_val, 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, op_induction U, cases U, cases U_val, 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 end stalk_pushforward end Top.presheaf
0a3c7ed6777cd65227d244b11e4c74c06667965f
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/gcd_monoid/basic.lean
71608f7c948e04f381ed39cb7f65ea4106400906
[ "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
46,415
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker -/ import algebra.associated import algebra.group_power.lemmas import data.nat.gcd /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `is_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` * `normalized_gcd_monoid` * `gcd_monoid_of_gcd`, `gcd_monoid_of_exists_gcd`, `normalized_gcd_monoid_of_gcd`, `normalized_gcd_monoid_of_exists_gcd` * `gcd_monoid_of_lcm`, `gcd_monoid_of_exists_lcm`, `normalized_gcd_monoid_of_lcm`, `normalized_gcd_monoid_of_exists_lcm` For the `normalized_gcd_monoid` instances on `ℕ` and `ℤ`, see `ring_theory.int.basic`. ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` contains the definitions of `gcd` and `lcm` with the usual properties. They are both determined up to a unit. * `normalized_gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. * `gcd_monoid_of_gcd` and `normalized_gcd_monoid_of_gcd` noncomputably construct a `gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from the `gcd` and its properties. * `gcd_monoid_of_exists_gcd` and `normalized_gcd_monoid_of_exists_gcd` noncomputably construct a `gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from a proof that any two elements have a (not necessarily normalized) `gcd`. * `gcd_monoid_of_lcm` and `normalized_gcd_monoid_of_lcm` noncomputably construct a `gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from the `lcm` and its properties. * `gcd_monoid_of_exists_lcm` and `normalized_gcd_monoid_of_exists_lcm` noncomputably construct a `gcd_monoid` (resp. `normalized_gcd_monoid`) structure just from a proof that any two elements have a (not necessarily normalized) `lcm`. ## TODO * Port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero ## Tags divisibility, gcd, lcm, normalize -/ variables {α : Type*} /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_monoid (α : Type*) [comm_cancel_monoid_with_zero α] := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_monoid variables [comm_cancel_monoid_with_zero α] [normalization_monoid α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize : monoid_with_zero_hom α α := { to_fun := λ x, x * norm_unit x, map_zero' := by simp, map_one' := by rw [norm_unit_one, units.coe_one, mul_one], map_mul' := λ x y, classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy, by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], } theorem associated_normalize (x : α) : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated (x : α) : associated (normalize x) x := (associated_normalize _).symm lemma associates.mk_normalize (x : α) : associates.mk (normalize x) = associates.mk x := associates.mk_eq_mk_iff_associated.2 (normalize_associated _) @[simp] lemma normalize_apply (x : α) : normalize x = x * norm_unit x := rfl @[simp] lemma normalize_zero : normalize (0 : α) = 0 := normalize.map_zero @[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize _, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ @[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := begin nontriviality α using [subsingleton.elim a 0], obtain rfl|h := eq_or_ne a 0, { rw [norm_unit_zero, zero_mul, norm_unit_zero] }, { rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] } end theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin nontriviality α, rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd end normalization_monoid namespace associates variables [comm_cancel_monoid_with_zero α] [normalization_monoid α] local attribute [instance] associated.setoid /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with `gcd` (greatest common divisor) and `lcm` (least common multiple) operations, determined up to a unit. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (gcd_mul_lcm : ∀a b, associated (gcd a b * lcm a b) (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) /-- Normalized GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ class normalized_gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] extends normalization_monoid α, gcd_monoid α := (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b) export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_monoid variables [comm_cancel_monoid_with_zero α] @[simp] theorem normalize_gcd [normalized_gcd_monoid α] : ∀a b:α, normalize (gcd a b) = gcd a b := normalized_gcd_monoid.normalize_gcd theorem gcd_mul_lcm [gcd_monoid α] : ∀a b:α, associated (gcd a b * lcm a b) (a * b) := gcd_monoid.gcd_mul_lcm section gcd theorem dvd_gcd_iff [gcd_monoid α] (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨h.trans (gcd_dvd_left _ _), h.trans (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm [normalized_gcd_monoid α] (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_comm' [gcd_monoid α] (a b : α) : associated (gcd a b) (gcd b a) := associated_of_dvd_dvd (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc [normalized_gcd_monoid α] (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n)) (dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k))) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k))) theorem gcd_assoc' [gcd_monoid α] (m n k : α) : associated (gcd (gcd m n) k) (gcd m (gcd n k)) := associated_of_dvd_dvd (dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n)) (dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k))) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k))) instance [normalized_gcd_monoid α] : is_commutative α gcd := ⟨gcd_comm⟩ instance [normalized_gcd_monoid α] : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize [normalized_gcd_monoid α] {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left [normalized_gcd_monoid α] (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) theorem gcd_zero_left' [gcd_monoid α] (a : α) : associated (gcd 0 a) a := associated_of_dvd_dvd (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right [normalized_gcd_monoid α] (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) theorem gcd_zero_right' [gcd_monoid α] (a : α) : associated (gcd a 0) a := associated_of_dvd_dvd (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff [gcd_monoid α] (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by { rw [ha, hb, ←zero_dvd_iff], apply dvd_gcd; refl }) @[simp] theorem gcd_one_left [normalized_gcd_monoid α] (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_left' [gcd_monoid α] (a : α) : associated (gcd 1 a) 1 := associated_of_dvd_dvd (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right [normalized_gcd_monoid α] (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) @[simp] theorem gcd_one_right' [gcd_monoid α] (a : α) : associated (gcd a 1) 1 := associated_of_dvd_dvd (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd [gcd_monoid α] {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd ((gcd_dvd_left _ _).trans hab) ((gcd_dvd_right _ _).trans hcd) @[simp] theorem gcd_same [normalized_gcd_monoid α] (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left [normalized_gcd_monoid α] (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize.map_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) theorem gcd_mul_left' [gcd_monoid α] (a b c : α) : associated (gcd (a * b) (a * c)) (a * gcd b c) := begin obtain rfl|ha := eq_or_ne a 0, { simp only [zero_mul, gcd_zero_left'] }, obtain ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c), apply associated_of_dvd_dvd, { rw eq, apply mul_dvd_mul_left, exact dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _) }, { exact (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) }, end @[simp] theorem gcd_mul_right [normalized_gcd_monoid α] (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] @[simp] theorem gcd_mul_right' [gcd_monoid α] (a b c : α) : associated (gcd (b * a) (c * a)) (gcd b c * a) := by simp only [mul_comm, gcd_mul_left'] theorem gcd_eq_left_iff [normalized_gcd_monoid α] (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff [normalized_gcd_monoid α] (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) dvd_rfl theorem gcd_dvd_gcd_mul_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) dvd_rfl theorem gcd_dvd_gcd_mul_left_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd dvd_rfl (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right [gcd_monoid α] (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd dvd_rfl (dvd_mul_right _ _) theorem associated.gcd_eq_left [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) : gcd m k = gcd n k := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd h.dvd dvd_rfl) (gcd_dvd_gcd h.symm.dvd dvd_rfl) theorem associated.gcd_eq_right [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) : gcd k m = gcd k n := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd dvd_rfl h.dvd) (gcd_dvd_gcd dvd_rfl h.symm.dvd) lemma dvd_gcd_mul_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : k ∣ (gcd k m) * n := (dvd_gcd (dvd_mul_right _ n) H).trans (gcd_mul_right' n k m).dvd lemma dvd_mul_gcd_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : k ∣ m * gcd k n := by { rw mul_comm at H ⊢, exact dvd_gcd_mul_of_dvd_mul H } /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. Note: In general, this representation is highly non-unique. -/ lemma exists_dvd_and_dvd_of_dvd_mul [gcd_monoid α] {m n k : α} (H : k ∣ m * n) : ∃ d₁ (hd₁ : d₁ ∣ m) d₂ (hd₂ : d₂ ∣ n), k = d₁ * d₂ := begin by_cases h0 : gcd k m = 0, { rw gcd_eq_zero_iff at h0, rcases h0 with ⟨rfl, rfl⟩, refine ⟨0, dvd_refl 0, n, dvd_refl n, _⟩, simp }, { obtain ⟨a, ha⟩ := gcd_dvd_left k m, refine ⟨gcd k m, gcd_dvd_right _ _, a, _, ha⟩, suffices h : gcd k m * a ∣ gcd k m * n, { cases h with b hb, use b, rw mul_assoc at hb, apply mul_left_cancel₀ h0 hb }, rw ← ha, exact dvd_gcd_mul_of_dvd_mul H } end theorem gcd_mul_dvd_mul_gcd [gcd_monoid α] (k m n : α) : gcd k (m * n) ∣ gcd k m * gcd k n := begin obtain ⟨m', hm', n', hn', h⟩ := (exists_dvd_and_dvd_of_dvd_mul $ gcd_dvd_right k (m * n)), replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := (dvd_mul_right m' n').trans hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := (dvd_mul_left n' m').trans hm'n', exact dvd_gcd hn'k hn' } end theorem gcd_pow_right_dvd_pow_gcd [gcd_monoid α] {a b : α} {k : ℕ} : gcd a (b ^ k) ∣ (gcd a b) ^ k := begin by_cases hg : gcd a b = 0, { rw gcd_eq_zero_iff at hg, rcases hg with ⟨rfl, rfl⟩, exact (gcd_zero_left' (0 ^ k : α)).dvd.trans (pow_dvd_pow_of_dvd (gcd_zero_left' (0 : α)).symm.dvd _) }, { induction k with k hk, { simp only [pow_zero], exact (gcd_one_right' a).dvd, }, rw [pow_succ, pow_succ], transitivity gcd a b * gcd a (b ^ k), apply gcd_mul_dvd_mul_gcd a b (b ^ k), exact (mul_dvd_mul_iff_left hg).mpr hk } end theorem gcd_pow_left_dvd_pow_gcd [gcd_monoid α] {a b : α} {k : ℕ} : gcd (a ^ k) b ∣ (gcd a b) ^ k := calc gcd (a ^ k) b ∣ gcd b (a ^ k) : (gcd_comm' _ _).dvd ... ∣ (gcd b a) ^ k : gcd_pow_right_dvd_pow_gcd ... ∣ (gcd a b) ^ k : pow_dvd_pow_of_dvd (gcd_comm' _ _).dvd _ theorem pow_dvd_of_mul_eq_pow [gcd_monoid α] {a b c d₁ d₂ : α} (ha : a ≠ 0) (hab : is_unit (gcd a b)) {k : ℕ} (h : a * b = c ^ k) (hc : c = d₁ * d₂) (hd₁ : d₁ ∣ a) : d₁ ^ k ≠ 0 ∧ d₁ ^ k ∣ a := begin have h1 : is_unit (gcd (d₁ ^ k) b), { apply is_unit_of_dvd_one, transitivity (gcd d₁ b) ^ k, { exact gcd_pow_left_dvd_pow_gcd }, { apply is_unit.dvd, apply is_unit.pow, apply is_unit_of_dvd_one, apply dvd_trans _ hab.dvd, apply gcd_dvd_gcd hd₁ (dvd_refl b) } }, have h2 : d₁ ^ k ∣ a * b, { use d₂ ^ k, rw [h, hc], exact mul_pow d₁ d₂ k }, rw mul_comm at h2, have h3 : d₁ ^ k ∣ a, { apply (dvd_gcd_mul_of_dvd_mul h2).trans, rw is_unit.mul_left_dvd _ _ _ h1 }, have h4 : d₁ ^ k ≠ 0, { intro hdk, rw hdk at h3, apply absurd (zero_dvd_iff.mp h3) ha }, exact ⟨h4, h3⟩, end theorem exists_associated_pow_of_mul_eq_pow [gcd_monoid α] {a b c : α} (hab : is_unit (gcd a b)) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : α), associated (d ^ k) a := begin casesI subsingleton_or_nontrivial α, { use 0, rw [subsingleton.elim a (0 ^ k)] }, by_cases ha : a = 0, { use 0, rw ha, obtain (rfl | hk) := k.eq_zero_or_pos, { exfalso, revert h, rw [ha, zero_mul, pow_zero], apply zero_ne_one }, { rw zero_pow hk } }, by_cases hb : b = 0, { use 1, rw [one_pow], apply (associated_one_iff_is_unit.mpr hab).symm.trans, rw hb, exact gcd_zero_right' a }, obtain (rfl | hk) := k.eq_zero_or_pos, { use 1, rw pow_zero at h ⊢, use units.mk_of_mul_eq_one _ _ h, rw [units.coe_mk_of_mul_eq_one, one_mul] }, have hc : c ∣ a * b, { rw h, exact dvd_pow_self _ hk.ne' }, obtain ⟨d₁, hd₁, d₂, hd₂, hc⟩ := exists_dvd_and_dvd_of_dvd_mul hc, use d₁, obtain ⟨h0₁, ⟨a', ha'⟩⟩ := pow_dvd_of_mul_eq_pow ha hab h hc hd₁, rw [mul_comm] at h hc, rw (gcd_comm' a b).is_unit_iff at hab, obtain ⟨h0₂, ⟨b', hb'⟩⟩ := pow_dvd_of_mul_eq_pow hb hab h hc hd₂, rw [ha', hb', hc, mul_pow] at h, have h' : a' * b' = 1, { apply (mul_right_inj' h0₁).mp, rw mul_one, apply (mul_right_inj' h0₂).mp, rw ← h, rw [mul_assoc, mul_comm a', ← mul_assoc _ b', ← mul_assoc b', mul_comm b'] }, use units.mk_of_mul_eq_one _ _ h', rw [units.coe_mk_of_mul_eq_one, ha'] end end gcd section lcm lemma lcm_dvd_iff [gcd_monoid α] {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := begin by_cases this : a = 0 ∨ b = 0, { rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt} }, { obtain ⟨h1, h2⟩ := not_or_distrib.1 this, have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, rw [← mul_dvd_mul_iff_left h, (gcd_mul_lcm a b).dvd_iff_dvd_left, ←(gcd_mul_right' c a b).dvd_iff_dvd_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm] } end lemma dvd_lcm_left [gcd_monoid α] (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 dvd_rfl).1 lemma dvd_lcm_right [gcd_monoid α] (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 dvd_rfl).2 lemma lcm_dvd [gcd_monoid α] {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff [gcd_monoid α] (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have associated (a * b) 0 := (gcd_mul_lcm a b).symm.trans $ by rw [h, mul_zero], by simpa only [associated_zero_iff_eq_zero, mul_eq_zero]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm [normalized_gcd_monoid α] (a b : α) : normalize (lcm a b) = lcm a b := normalized_gcd_monoid.normalize_lcm a b theorem lcm_comm [normalized_gcd_monoid α] (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_comm' [gcd_monoid α] (a b : α) : associated (lcm a b) (lcm b a) := associated_of_dvd_dvd (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc [normalized_gcd_monoid α] (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) ((dvd_lcm_left _ _).trans (dvd_lcm_right _ _))) ((dvd_lcm_right _ _).trans (dvd_lcm_right _ _))) (lcm_dvd ((dvd_lcm_left _ _).trans (dvd_lcm_left _ _)) (lcm_dvd ((dvd_lcm_right _ _).trans (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) theorem lcm_assoc' [gcd_monoid α] (m n k : α) : associated (lcm (lcm m n) k) (lcm m (lcm n k)) := associated_of_dvd_dvd (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) ((dvd_lcm_left _ _).trans (dvd_lcm_right _ _))) ((dvd_lcm_right _ _).trans (dvd_lcm_right _ _))) (lcm_dvd ((dvd_lcm_left _ _).trans (dvd_lcm_left _ _)) (lcm_dvd ((dvd_lcm_right _ _).trans (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance [normalized_gcd_monoid α] : is_commutative α lcm := ⟨lcm_comm⟩ instance [normalized_gcd_monoid α] : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize [normalized_gcd_monoid α] {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm [gcd_monoid α] {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (hab.trans (dvd_lcm_left _ _)) (hcd.trans (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left [normalized_gcd_monoid α] (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd dvd_rfl) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right [normalized_gcd_monoid α] (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left [normalized_gcd_monoid α] (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right [normalized_gcd_monoid α] (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same [normalized_gcd_monoid α] (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd dvd_rfl dvd_rfl) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff [normalized_gcd_monoid α] (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left [normalized_gcd_monoid α] (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize.map_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from (dvd_mul_right _ _).trans (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right [normalized_gcd_monoid α] (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff [normalized_gcd_monoid α] (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff [normalized_gcd_monoid α] (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) dvd_rfl theorem lcm_dvd_lcm_mul_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) dvd_rfl theorem lcm_dvd_lcm_mul_left_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm dvd_rfl (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right [gcd_monoid α] (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm dvd_rfl (dvd_mul_right _ _) theorem lcm_eq_of_associated_left [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) : lcm m k = lcm n k := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm h.dvd dvd_rfl) (lcm_dvd_lcm h.symm.dvd dvd_rfl) theorem lcm_eq_of_associated_right [normalized_gcd_monoid α] {m n : α} (h : associated m n) (k : α) : lcm k m = lcm k n := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm dvd_rfl h.dvd) (lcm_dvd_lcm dvd_rfl h.symm.dvd) end lcm namespace gcd_monoid theorem prime_of_irreducible [gcd_monoid α] {x : α} (hi: irreducible x) : prime x := ⟨hi.ne_zero, ⟨hi.1, λ a b h, begin cases gcd_dvd_left x a with y hy, cases hi.is_unit_or_is_unit hy with hu hu, { right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h, rw (gcd_mul_right' b x a).dvd_iff_dvd_left, exact (associated_unit_mul_left _ _ hu).dvd }, { left, rw hy, exact dvd_trans (associated_mul_unit_left _ _ hu).dvd (gcd_dvd_right x a) } end ⟩⟩ theorem irreducible_iff_prime [gcd_monoid α] {p : α} : irreducible p ↔ prime p := ⟨prime_of_irreducible, prime.irreducible⟩ end gcd_monoid end gcd_monoid section unique_unit variables [comm_cancel_monoid_with_zero α] [unique (units α)] @[priority 100] -- see Note [lower instance priority] instance normalization_monoid_of_unique_units : normalization_monoid α := { norm_unit := λ x, 1, norm_unit_zero := rfl, norm_unit_mul := λ x y hx hy, (mul_one 1).symm, norm_unit_coe_units := λ u, subsingleton.elim _ _ } @[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl @[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x end unique_unit section is_domain variables [comm_ring α] [is_domain α] [normalized_gcd_monoid α] lemma gcd_eq_of_dvd_sub_right {a b c : α} (h : a ∣ b - c) : gcd a b = gcd a c := begin apply dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _); rw dvd_gcd_iff; refine ⟨gcd_dvd_left _ _, _⟩, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a b with ⟨e, he⟩, rcases gcd_dvd_left a b with ⟨f, hf⟩, use e - f * d, rw [mul_sub, ← he, ← mul_assoc, ← hf, ← hd, sub_sub_cancel] }, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a c with ⟨e, he⟩, rcases gcd_dvd_left a c with ⟨f, hf⟩, use e + f * d, rw [mul_add, ← he, ← mul_assoc, ← hf, ← hd, ← add_sub_assoc, add_comm c b, add_sub_cancel] } end lemma gcd_eq_of_dvd_sub_left {a b c : α} (h : a ∣ b - c) : gcd b a = gcd c a := by rw [gcd_comm _ a, gcd_comm _ a, gcd_eq_of_dvd_sub_right h] end is_domain section constructors noncomputable theory open associates variables [comm_cancel_monoid_with_zero α] private lemma map_mk_unit_aux [decidable_eq α] {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a * ↑(classical.some (associated_map_mk hinv a)) = f (associates.mk a) := classical.some_spec (associated_map_mk hinv a) /-- Define `normalization_monoid` on a structure from a `monoid_hom` inverse to `associates.mk`. -/ def normalization_monoid_of_monoid_hom_right_inverse [decidable_eq α] (f : associates α →* α) (hinv : function.right_inverse f associates.mk) : normalization_monoid α := { norm_unit := λ a, if a = 0 then 1 else classical.some (associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm), norm_unit_zero := if_pos rfl, norm_unit_mul := λ a b ha hb, by { rw [if_neg (mul_ne_zero ha hb), if_neg ha, if_neg hb, units.ext_iff, units.coe_mul], suffices : (a * b) * ↑(classical.some (associated_map_mk hinv (a * b))) = (a * ↑(classical.some (associated_map_mk hinv a))) * (b * ↑(classical.some (associated_map_mk hinv b))), { apply mul_left_cancel₀ (mul_ne_zero ha hb) _, simpa only [mul_assoc, mul_comm, mul_left_comm] using this }, rw [map_mk_unit_aux hinv a, map_mk_unit_aux hinv (a * b), map_mk_unit_aux hinv b, ← monoid_hom.map_mul, associates.mk_mul_mk] }, norm_unit_coe_units := λ u, by { nontriviality α, rw [if_neg (units.ne_zero u), units.ext_iff], apply mul_left_cancel₀ (units.ne_zero u), rw [units.mul_inv, map_mk_unit_aux hinv u, associates.mk_eq_mk_iff_associated.2 (associated_one_iff_is_unit.2 ⟨u, rfl⟩), associates.mk_one, monoid_hom.map_one] } } /-- Define `gcd_monoid` on a structure just from the `gcd` and its properties. -/ noncomputable def gcd_monoid_of_gcd [decidable_eq α] (gcd : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) : gcd_monoid α := { gcd := gcd, gcd_dvd_left := gcd_dvd_left, gcd_dvd_right := gcd_dvd_right, dvd_gcd := λ a b c, dvd_gcd, lcm := λ a b, if a = 0 then 0 else classical.some ((gcd_dvd_left a b).trans (dvd.intro b rfl)), gcd_mul_lcm := λ a b, by { split_ifs with a0, { rw [mul_zero, a0, zero_mul] }, { rw ←classical.some_spec ((gcd_dvd_left a b).trans (dvd.intro b rfl)) } }, lcm_zero_left := λ a, if_pos rfl, lcm_zero_right := λ a, by { split_ifs with a0, { refl }, have h := (classical.some_spec ((gcd_dvd_left a 0).trans (dvd.intro 0 rfl))).symm, have a0' : gcd a 0 ≠ 0, { contrapose! a0, rw [←associated_zero_iff_eq_zero, ←a0], exact associated_of_dvd_dvd (dvd_gcd (dvd_refl a) (dvd_zero a)) (gcd_dvd_left _ _) }, apply or.resolve_left (mul_eq_zero.1 _) a0', rw [h, mul_zero] } } /-- Define `normalized_gcd_monoid` on a structure just from the `gcd` and its properties. -/ noncomputable def normalized_gcd_monoid_of_gcd [normalization_monoid α] [decidable_eq α] (gcd : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) : normalized_gcd_monoid α := { gcd := gcd, gcd_dvd_left := gcd_dvd_left, gcd_dvd_right := gcd_dvd_right, dvd_gcd := λ a b c, dvd_gcd, normalize_gcd := normalize_gcd, lcm := λ a b, if a = 0 then 0 else classical.some (dvd_normalize_iff.2 ((gcd_dvd_left a b).trans (dvd.intro b rfl))), normalize_lcm := λ a b, by { dsimp [normalize], split_ifs with a0, { exact @normalize_zero α _ _ }, { have := (classical.some_spec (dvd_normalize_iff.2 ((gcd_dvd_left a b).trans (dvd.intro b rfl)))).symm, set l := classical.some (dvd_normalize_iff.2 ((gcd_dvd_left a b).trans (dvd.intro b rfl))), obtain rfl|hb := eq_or_ne b 0, { simp only [normalize_zero, mul_zero, mul_eq_zero] at this, obtain ha|hl := this, { apply (a0 _).elim, rw [←zero_dvd_iff, ←ha], exact gcd_dvd_left _ _ }, { convert @normalize_zero α _ _ } }, have h1 : gcd a b ≠ 0, { have hab : a * b ≠ 0 := mul_ne_zero a0 hb, contrapose! hab, rw [←normalize_eq_zero, ←this, hab, zero_mul] }, have h2 : normalize (gcd a b * l) = gcd a b * l, { rw [this, normalize_idem] }, rw ←normalize_gcd at this, rwa [normalize.map_mul, normalize_gcd, mul_right_inj' h1] at h2 } }, gcd_mul_lcm := λ a b, by { split_ifs with a0, { rw [mul_zero, a0, zero_mul] }, { rw ←classical.some_spec (dvd_normalize_iff.2 ((gcd_dvd_left a b).trans (dvd.intro b rfl))), exact normalize_associated (a * b) } }, lcm_zero_left := λ a, if_pos rfl, lcm_zero_right := λ a, by { split_ifs with a0, { refl }, rw ← normalize_eq_zero at a0, have h := (classical.some_spec (dvd_normalize_iff.2 ((gcd_dvd_left a 0).trans (dvd.intro 0 rfl)))).symm, have gcd0 : gcd a 0 = normalize a, { rw ← normalize_gcd, exact normalize_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_zero a)) }, rw ← gcd0 at a0, apply or.resolve_left (mul_eq_zero.1 _) a0, rw [h, mul_zero, normalize_zero] }, .. (infer_instance : normalization_monoid α) } /-- Define `gcd_monoid` on a structure just from the `lcm` and its properties. -/ noncomputable def gcd_monoid_of_lcm [decidable_eq α] (lcm : α → α → α) (dvd_lcm_left : ∀a b, a ∣ lcm a b) (dvd_lcm_right : ∀a b, b ∣ lcm a b) (lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a): gcd_monoid α := let exists_gcd := λ a b, lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl) in { lcm := lcm, gcd := λ a b, if a = 0 then b else (if b = 0 then a else classical.some (exists_gcd a b)), gcd_mul_lcm := λ a b, by { split_ifs, { rw [h, zero_dvd_iff.1 (dvd_lcm_left _ _), mul_zero, zero_mul] }, { rw [h_1, zero_dvd_iff.1 (dvd_lcm_right _ _), mul_zero] }, rw [mul_comm, ←classical.some_spec (exists_gcd a b)] }, lcm_zero_left := λ a, zero_dvd_iff.1 (dvd_lcm_left _ _), lcm_zero_right := λ a, zero_dvd_iff.1 (dvd_lcm_right _ _), gcd_dvd_left := λ a b, by { split_ifs with h h_1, { rw h, apply dvd_zero }, { exact dvd_rfl }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), mul_comm, mul_dvd_mul_iff_right h], apply dvd_lcm_right }, gcd_dvd_right := λ a b, by { split_ifs with h h_1, { exact dvd_rfl }, { rw h_1, apply dvd_zero }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), mul_dvd_mul_iff_right h_1], apply dvd_lcm_left }, dvd_gcd := λ a b c ac ab, by { split_ifs, { exact ab }, { exact ac }, have h0 : lcm c b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd c b)], rcases ab with ⟨d, rfl⟩, rw mul_eq_zero at h_1, push_neg at h_1, rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1], apply lcm_dvd (dvd.intro d rfl), rw [mul_comm, mul_dvd_mul_iff_right h_1.2], apply ac } } /-- Define `normalized_gcd_monoid` on a structure just from the `lcm` and its properties. -/ noncomputable def normalized_gcd_monoid_of_lcm [normalization_monoid α] [decidable_eq α] (lcm : α → α → α) (dvd_lcm_left : ∀a b, a ∣ lcm a b) (dvd_lcm_right : ∀a b, b ∣ lcm a b) (lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a) (normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b) : normalized_gcd_monoid α := let exists_gcd := λ a b, dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)) in { lcm := lcm, gcd := λ a b, if a = 0 then normalize b else (if b = 0 then normalize a else classical.some (exists_gcd a b)), gcd_mul_lcm := λ a b, by { split_ifs with h h_1, { rw [h, zero_dvd_iff.1 (dvd_lcm_left _ _), mul_zero, zero_mul] }, { rw [h_1, zero_dvd_iff.1 (dvd_lcm_right _ _), mul_zero, mul_zero] }, rw [mul_comm, ←classical.some_spec (exists_gcd a b)], exact normalize_associated (a * b) }, normalize_lcm := normalize_lcm, normalize_gcd := λ a b, by { dsimp [normalize], split_ifs with h h_1, { apply normalize_idem }, { apply normalize_idem }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, apply mul_left_cancel₀ h0, refine trans _ (classical.some_spec (exists_gcd a b)), conv_lhs { congr, rw [← normalize_lcm a b] }, erw [← normalize.map_mul, ← classical.some_spec (exists_gcd a b), normalize_idem] }, lcm_zero_left := λ a, zero_dvd_iff.1 (dvd_lcm_left _ _), lcm_zero_right := λ a, zero_dvd_iff.1 (dvd_lcm_right _ _), gcd_dvd_left := λ a b, by { split_ifs, { rw h, apply dvd_zero }, { exact (normalize_associated _).dvd }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), normalize_dvd_iff, mul_comm, mul_dvd_mul_iff_right h], apply dvd_lcm_right }, gcd_dvd_right := λ a b, by { split_ifs, { exact (normalize_associated _).dvd }, { rw h_1, apply dvd_zero }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), normalize_dvd_iff, mul_dvd_mul_iff_right h_1], apply dvd_lcm_left }, dvd_gcd := λ a b c ac ab, by { split_ifs, { apply dvd_normalize_iff.2 ab }, { apply dvd_normalize_iff.2 ac }, have h0 : lcm c b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl))), dvd_normalize_iff], rcases ab with ⟨d, rfl⟩, rw mul_eq_zero at h_1, push_neg at h_1, rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1], apply lcm_dvd (dvd.intro d rfl), rw [mul_comm, mul_dvd_mul_iff_right h_1.2], apply ac }, .. (infer_instance : normalization_monoid α) } /-- Define a `gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/ noncomputable def gcd_monoid_of_exists_gcd [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) : gcd_monoid α := gcd_monoid_of_gcd (λ a b, (classical.some (h a b))) (λ a b, (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1) (λ a b, (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2) (λ a b c ac ab, ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) /-- Define a `normalized_gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/ noncomputable def normalized_gcd_monoid_of_exists_gcd [normalization_monoid α] [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) : normalized_gcd_monoid α := normalized_gcd_monoid_of_gcd (λ a b, normalize (classical.some (h a b))) (λ a b, normalize_dvd_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1) (λ a b, normalize_dvd_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2) (λ a b c ac ab, dvd_normalize_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) (λ a b, normalize_idem _) /-- Define a `gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/ noncomputable def gcd_monoid_of_exists_lcm [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) : gcd_monoid α := gcd_monoid_of_lcm (λ a b, (classical.some (h a b))) (λ a b, (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1) (λ a b, (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2) (λ a b c ac ab, ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) /-- Define a `normalized_gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/ noncomputable def normalized_gcd_monoid_of_exists_lcm [normalization_monoid α] [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) : normalized_gcd_monoid α := normalized_gcd_monoid_of_lcm (λ a b, normalize (classical.some (h a b))) (λ a b, dvd_normalize_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).1) (λ a b, dvd_normalize_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 dvd_rfl)).2) (λ a b c ac ab, normalize_dvd_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) (λ a b, normalize_idem _) end constructors namespace comm_group_with_zero variables (G₀ : Type*) [comm_group_with_zero G₀] [decidable_eq G₀] @[priority 100] -- see Note [lower instance priority] instance : normalized_gcd_monoid G₀ := { norm_unit := λ x, if h : x = 0 then 1 else (units.mk0 x h)⁻¹, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ x y x0 y0, units.eq_iff.1 (by simp [x0, y0, mul_comm]), norm_unit_coe_units := λ u, by { rw [dif_neg (units.ne_zero _), units.mk0_coe], apply_instance }, gcd := λ a b, if a = 0 ∧ b = 0 then 0 else 1, lcm := λ a b, if a = 0 ∨ b = 0 then 0 else 1, gcd_dvd_left := λ a b, by { split_ifs with h, { rw h.1 }, { exact one_dvd _ } }, gcd_dvd_right := λ a b, by { split_ifs with h, { rw h.2 }, { exact one_dvd _ } }, dvd_gcd := λ a b c hac hab, begin split_ifs with h, { apply dvd_zero }, cases not_and_distrib.mp h with h h; refine is_unit_iff_dvd_one.mp (is_unit_of_dvd_unit _ (is_unit.mk0 _ h)); assumption end, gcd_mul_lcm := λ a b, begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, rw [if_neg (not_and_of_not_left _ ha), one_mul, if_neg (not_or ha hb)], exact (associated_one_iff_is_unit.mpr ((is_unit.mk0 _ ha).mul (is_unit.mk0 _ hb))).symm end, lcm_zero_left := λ b, if_pos (or.inl rfl), lcm_zero_right := λ a, if_pos (or.inr rfl), -- `split_ifs` wants to split `normalize`, so handle the cases manually normalize_gcd := λ a b, if h : a = 0 ∧ b = 0 then by simp [if_pos h] else by simp [if_neg h], normalize_lcm := λ a b, if h : a = 0 ∨ b = 0 then by simp [if_pos h] else by simp [if_neg h] } @[simp] lemma coe_norm_unit {a : G₀} (h0 : a ≠ 0) : (↑(norm_unit a) : G₀) = a⁻¹ := by simp [norm_unit, h0] lemma normalize_eq_one {a : G₀} (h0 : a ≠ 0) : normalize a = 1 := by simp [normalize_apply, h0] end comm_group_with_zero
b427eb710ea2e02edebeecc6542e9f07f1177297
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/group5.lean
0c3996dbdf39a7b87fb6cd9edef910538f452d82
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,988
lean
-- Copyright (c) 2014 Jeremy Avigad. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Jeremy Avigad, Leonardo de Moura -- algebra.group -- ============= -- Various structures with 1, *, inv, including groups. import logic.eq import data.unit data.sigma data.prod import algebra.function algebra.binary open eq namespace algebra structure has_mul [class] (A : Type) := (mul : A → A → A) structure has_one [class] (A : Type) := (one : A) structure has_inv [class] (A : Type) := (inv : A → A) infixl `*` := has_mul.mul postfix `⁻¹` := has_inv.inv notation 1 := !has_one.one structure semigroup [class] (A : Type) extends has_mul A := (assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) set_option pp.notation false -- set_option pp.implicit true -- set_option pp.coercions true print instances has_mul section variables {A : Type} [s : semigroup A] include s variables a b : A example : a * b = semigroup.mul a b := rfl theorem mul_assoc (a b c : A) : a * b * c = a * (b * c) := semigroup.assoc a b c end structure comm_semigroup [class] (A : Type) extends semigroup A := (comm : ∀a b, mul a b = mul b a) namespace comm_semigroup variables {A : Type} [s : comm_semigroup A] include s variables a b c : A theorem mul_comm : a * b = b * a := !comm_semigroup.comm theorem mul_left_comm : a * (b * c) = b * (a * c) := binary.left_comm mul_comm mul_assoc a b c end comm_semigroup structure monoid [class] (A : Type) extends semigroup A, has_one A := (right_id : ∀a, mul a one = a) (left_id : ∀a, mul one a = a) section variables {A : Type} [s : monoid A] variable a : A include s theorem mul_right_id : a * 1 = a := !monoid.right_id theorem mul_left_id : 1 * a = a := !monoid.left_id end structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] end algebra open algebra section examples theorem test1 {S : Semigroup} (a b c d : S) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : {symm !mul_assoc} ... = a * b * (c * d) : !mul_assoc theorem test2 {M : CommSemigroup} (a b : M) : a * b = a * b := rfl theorem test3 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : {symm !mul_assoc} ... = a * b * (c * d) : !mul_assoc -- for test4b to work, we need instances at the level of the bundled structures as well definition Monoid_Semigroup [coercion] (M : Monoid) : Semigroup := Semigroup.mk (Monoid.carrier M) _ theorem test4 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := test1 a b c d theorem test5 {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc theorem test5a {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc theorem test5b {A : Type} {M : monoid A} (a b c : A) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc theorem test6 {M : CommMonoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : !mul_assoc end examples
3ea7329ea2fa5e4f463de414dcb40e40ae8efc8f
2f8bf12144551bc7d8087a6320990c4621741f3d
/library/init/data/nat/basic.lean
95a3f7c009b7d079d002b38fc14a87a9244394af
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean4
eb63a12960e69823749edceb4f23fd33fa2253ce
fa16920a6a7700cabc567aa629ce4ae2478a2f40
refs/heads/master
1,589,935,810,594
1,557,177,860,000
1,557,177,860,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,318
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.core universes u notation `ℕ` := Nat namespace Nat @[extern cpp "lean::nat_dec_eq"] def beq : Nat → Nat → Bool | zero zero := true | zero (succ m) := false | (succ n) zero := false | (succ n) (succ m) := beq n m theorem eqOfBeqEqTt : ∀ {n m : Nat}, beq n m = true → n = m | zero zero h := rfl | zero (succ m) h := Bool.noConfusion h | (succ n) zero h := Bool.noConfusion h | (succ n) (succ m) h := have beq n m = true, from h, have n = m, from eqOfBeqEqTt this, congrArg succ this theorem neOfBeqEqFf : ∀ {n m : Nat}, beq n m = false → n ≠ m | zero zero h₁ h₂ := Bool.noConfusion h₁ | zero (succ m) h₁ h₂ := Nat.noConfusion h₂ | (succ n) zero h₁ h₂ := Nat.noConfusion h₂ | (succ n) (succ m) h₁ h₂ := have beq n m = false, from h₁, have n ≠ m, from neOfBeqEqFf this, Nat.noConfusion h₂ (λ h₂, absurd h₂ this) @[extern cpp "lean::nat_dec_eq"] protected def decEq (n m : @& Nat) : Decidable (n = m) := if h : beq n m = true then isTrue (eqOfBeqEqTt h) else isFalse (neOfBeqEqFf (eqFalseOfNeTrue h)) @[inline] instance : DecidableEq Nat := {decEq := Nat.decEq} @[extern cpp "lean::nat_dec_le"] def ble : Nat → Nat → Bool | zero zero := true | zero (succ m) := true | (succ n) zero := false | (succ n) (succ m) := ble n m protected def le (n m : Nat) : Prop := ble n m = true instance : HasLessEq Nat := ⟨Nat.le⟩ protected def lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat := ⟨Nat.lt⟩ @[extern cpp inline "lean::nat_sub(#1, lean::box(1))"] def pred : Nat → Nat | 0 := 0 | (a+1) := a @[extern cpp "lean::nat_sub"] protected def sub : (@& Nat) → (@& Nat) → Nat | a 0 := a | a (b+1) := pred (sub a b) @[extern cpp "lean::nat_mul"] protected def mul : (@& Nat) → (@& Nat) → Nat | a 0 := 0 | a (b+1) := (mul a b) + a instance : HasSub Nat := ⟨Nat.sub⟩ instance : HasMul Nat := ⟨Nat.mul⟩ @[specialize] def forCore {α : Type u} (f : Nat → α → α) (s : Nat) : Nat → α → α | 0 a := a | (succ n) a := forCore n (f (s - (succ n)) a) @[inline] def for {α : Type u} (f : Nat → α → α) (n : Nat) (a : α) : α := forCore f n n a @[specialize] def repeatCore {α : Type u} (f : α → α) : Nat → α → α | 0 a := a | (succ n) a := repeatCore n (f a) @[inline] def repeat {α : Type u} (f : α → α) (n : Nat) (a : α) : α := repeatCore f n a protected def pow (m : Nat) : Nat → Nat | 0 := 1 | (succ n) := pow n * m instance : HasPow Nat Nat := ⟨Nat.pow⟩ /- Nat.add theorems -/ protected theorem zeroAdd : ∀ n : Nat, 0 + n = n | 0 := rfl | (n+1) := congrArg succ (zeroAdd n) theorem succAdd : ∀ n m : Nat, (succ n) + m = succ (n + m) | n 0 := rfl | n (m+1) := congrArg succ (succAdd n m) theorem addSucc (n m : Nat) : n + succ m = succ (n + m) := rfl protected theorem addZero (n : Nat) : n + 0 = n := rfl theorem addOne (n : Nat) : n + 1 = succ n := rfl theorem succEqAddOne (n : Nat) : succ n = n + 1 := rfl protected theorem addComm : ∀ n m : Nat, n + m = m + n | n 0 := Eq.symm (Nat.zeroAdd n) | n (m+1) := suffices succ (n + m) = succ (m + n), from Eq.symm (succAdd m n) ▸ this, congrArg succ (addComm n m) protected theorem addAssoc : ∀ n m k : Nat, (n + m) + k = n + (m + k) | n m 0 := rfl | n m (succ k) := congrArg succ (addAssoc n m k) protected theorem addLeftComm : ∀ (n m k : Nat), n + (m + k) = m + (n + k) := leftComm Nat.add Nat.addComm Nat.addAssoc protected theorem addRightComm : ∀ (n m k : Nat), (n + m) + k = (n + k) + m := rightComm Nat.add Nat.addComm Nat.addAssoc protected theorem addLeftCancel : ∀ {n m k : Nat}, n + m = n + k → m = k | 0 m k h := Nat.zeroAdd m ▸ Nat.zeroAdd k ▸ h | (succ n) m k h := have n+m = n+k, from have succ (n + m) = succ (n + k), from succAdd n m ▸ succAdd n k ▸ h, Nat.noConfusion this id, addLeftCancel this protected theorem addRightCancel {n m k : Nat} (h : n + m = k + m) : n = k := have m + n = m + k, from Nat.addComm n m ▸ Nat.addComm k m ▸ h, Nat.addLeftCancel this /- Nat.mul theorems -/ protected theorem mulZero (n : Nat) : n * 0 = 0 := rfl theorem mulSucc (n m : Nat) : n * succ m = n * m + n := rfl protected theorem zeroMul : ∀ (n : Nat), 0 * n = 0 | 0 := rfl | (succ n) := (mulSucc 0 n).symm ▸ (zeroMul n).symm ▸ rfl theorem succMul : ∀ (n m : Nat), (succ n) * m = (n * m) + m | n 0 := rfl | n (succ m) := have succ (n * m + m + n) = succ (n * m + n + m), from congrArg succ (Nat.addRightComm _ _ _), (mulSucc n m).symm ▸ (mulSucc (succ n) m).symm ▸ (succMul n m).symm ▸ this protected theorem mulComm : ∀ (n m : Nat), n * m = m * n | n 0 := (Nat.zeroMul n).symm ▸ (Nat.mulZero n).symm ▸ rfl | n (succ m) := (mulSucc n m).symm ▸ (succMul m n).symm ▸ (mulComm n m).symm ▸ rfl protected theorem mulOne : ∀ (n : Nat), n * 1 = n := Nat.zeroAdd protected theorem oneMul (n : Nat) : 1 * n = n := Nat.mulComm n 1 ▸ Nat.mulOne n local infix `◾`:50 := Eq.trans protected theorem leftDistrib : ∀ (n m k : Nat), n * (m + k) = n * m + n * k | 0 m k := (Nat.zeroMul (m + k)).symm ▸ (Nat.zeroMul m).symm ▸ (Nat.zeroMul k).symm ▸ rfl | (succ n) m k := have h₁ : succ n * (m + k) = n * (m + k) + (m + k), from succMul _ _, have h₂ : n * (m + k) + (m + k) = (n * m + n * k) + (m + k), from leftDistrib n m k ▸ rfl, have h₃ : (n * m + n * k) + (m + k) = n * m + (n * k + (m + k)), from Nat.addAssoc _ _ _, have h₄ : n * m + (n * k + (m + k)) = n * m + (m + (n * k + k)), from congrArg (λ x, n*m + x) (Nat.addLeftComm _ _ _), have h₅ : n * m + (m + (n * k + k)) = (n * m + m) + (n * k + k), from (Nat.addAssoc _ _ _).symm, have h₆ : (n * m + m) + (n * k + k) = (n * m + m) + succ n * k, from succMul n k ▸ rfl, have h₇ : (n * m + m) + succ n * k = succ n * m + succ n * k, from succMul n m ▸ rfl, h₁ ◾ h₂ ◾ h₃ ◾ h₄ ◾ h₅ ◾ h₆ ◾ h₇ protected theorem rightDistrib (n m k : Nat) : (n + m) * k = n * k + m * k := have h₁ : (n + m) * k = k * (n + m), from Nat.mulComm _ _, have h₂ : k * (n + m) = k * n + k * m, from Nat.leftDistrib _ _ _, have h₃ : k * n + k * m = n * k + k * m, from Nat.mulComm n k ▸ rfl, have h₄ : n * k + k * m = n * k + m * k, from Nat.mulComm m k ▸ rfl, h₁ ◾ h₂ ◾ h₃ ◾ h₄ protected theorem mulAssoc : ∀ (n m k : Nat), (n * m) * k = n * (m * k) | n m 0 := rfl | n m (succ k) := have h₁ : n * m * succ k = n * m * (k + 1), from rfl, have h₂ : n * m * (k + 1) = (n * m * k) + n * m * 1, from Nat.leftDistrib _ _ _, have h₃ : (n * m * k) + n * m * 1 = (n * m * k) + n * m, from (Nat.mulOne (n*m)).symm ▸ rfl, have h₄ : (n * m * k) + n * m = (n * (m * k)) + n * m, from (mulAssoc n m k).symm ▸ rfl, have h₅ : (n * (m * k)) + n * m = n * (m * k + m), from (Nat.leftDistrib n (m*k) m).symm, have h₆ : n * (m * k + m) = n * (m * succ k), from Nat.mulSucc m k ▸ rfl, h₁ ◾ h₂ ◾ h₃ ◾ h₄ ◾ h₅ ◾ h₆ /- Inequalities -/ protected def leRefl : ∀ n : Nat, n ≤ n | zero := rfl | (succ n) := leRefl n theorem leSucc : ∀ (n : Nat), n ≤ succ n | zero := rfl | (succ n) := leSucc n theorem succLeSucc {n m : Nat} (h : n ≤ m) : succ n ≤ succ m := h theorem succLtSucc {n m : Nat} : n < m → succ n < succ m := succLeSucc theorem leStep : ∀ {n m : Nat}, n ≤ m → n ≤ succ m | zero zero h := rfl | zero (succ n) h := rfl | (succ n) zero h := Bool.noConfusion h | (succ n) (succ m) h := have n ≤ m, from h, have n ≤ succ m, from leStep this, succLeSucc this theorem zeroLe : ∀ (n : Nat), 0 ≤ n | zero := rfl | (succ n) := rfl theorem zeroLtSucc (n : Nat) : 0 < succ n := succLeSucc (zeroLe n) def succPos := zeroLtSucc theorem notSuccLeZero : ∀ (n : Nat), succ n ≤ 0 → False . theorem notLtZero (n : Nat) : ¬ n < 0 := notSuccLeZero n theorem predLePred : ∀ {n m : Nat}, n ≤ m → pred n ≤ pred m | zero zero h := rfl | zero (succ n) h := zeroLe n | (succ n) zero h := Bool.noConfusion h | (succ n) (succ m) h := h theorem leOfSuccLeSucc {n m : Nat} : succ n ≤ succ m → n ≤ m := predLePred @[extern cpp "lean::nat_dec_le"] instance decLe (n m : @& Nat) : Decidable (n ≤ m) := decEq (ble n m) true @[extern cpp "lean::nat_dec_lt"] instance decLt (n m : @& Nat) : Decidable (n < m) := Nat.decLe (succ n) m protected theorem eqOrLtOfLe : ∀ {n m: Nat}, n ≤ m → n = m ∨ n < m | zero zero h := Or.inl rfl | zero (succ n) h := Or.inr $ zeroLe n | (succ n) zero h := Bool.noConfusion h | (succ n) (succ m) h := have n ≤ m, from h, have n = m ∨ n < m, from eqOrLtOfLe this, Or.elim this (λ h, Or.inl $ congrArg succ h) (λ h, Or.inr $ succLtSucc h) theorem ltSuccOfLe {n m : Nat} : n ≤ m → n < succ m := succLeSucc protected theorem subZero (n : Nat) : n - 0 = n := rfl theorem succSubSuccEqSub (n m : Nat) : succ n - succ m = n - m := Nat.recOn m (show succ n - succ zero = n - zero, from (Eq.refl (succ n - succ zero))) (λ m, congrArg pred) theorem notSuccLeSelf : ∀ n : Nat, ¬succ n ≤ n := λ n, Nat.rec (notSuccLeZero 0) (λ a b c, b (leOfSuccLeSucc c)) n protected theorem ltIrrefl (n : Nat) : ¬n < n := notSuccLeSelf n protected theorem leTrans : ∀ {n m k : Nat}, n ≤ m → m ≤ k → n ≤ k | zero m k h₁ h₂ := zeroLe _ | (succ n) zero k h₁ h₂ := Bool.noConfusion h₁ | (succ n) (succ m) zero h₁ h₂ := Bool.noConfusion h₂ | (succ n) (succ m) (succ k) h₁ h₂ := have h₁' : n ≤ m, from h₁, have h₂' : m ≤ k, from h₂, have n ≤ k, from leTrans h₁' h₂', succLeSucc this theorem predLe : ∀ (n : Nat), pred n ≤ n | zero := rfl | (succ n) := leSucc _ theorem predLt : ∀ {n : Nat}, n ≠ 0 → pred n < n | zero h := absurd rfl h | (succ n) h := ltSuccOfLe (Nat.leRefl _) theorem subLe (n m : Nat) : n - m ≤ n := Nat.recOn m (Nat.leRefl (n - 0)) (λ m, Nat.leTrans (predLe (n - m))) theorem subLt : ∀ {n m : Nat}, 0 < n → 0 < m → n - m < n | 0 m h1 h2 := absurd h1 (Nat.ltIrrefl 0) | (n+1) 0 h1 h2 := absurd h2 (Nat.ltIrrefl 0) | (n+1) (m+1) h1 h2 := Eq.symm (succSubSuccEqSub n m) ▸ show n - m < succ n, from ltSuccOfLe (subLe n m) protected theorem ltOfLtOfLe {n m k : Nat} : n < m → m ≤ k → n < k := Nat.leTrans protected theorem leOfEq {n m : Nat} (p : n = m) : n ≤ m := p ▸ Nat.leRefl n theorem leSuccOfLe {n m : Nat} (h : n ≤ m) : n ≤ succ m := Nat.leTrans h (leSucc m) theorem leOfSuccLe {n m : Nat} (h : succ n ≤ m) : n ≤ m := Nat.leTrans (leSucc n) h protected theorem leOfLt {n m : Nat} (h : n < m) : n ≤ m := leOfSuccLe h def lt.step {n m : Nat} : n < m → n < succ m := leStep theorem eqZeroOrPos : ∀ (n : Nat), n = 0 ∨ n > 0 | 0 := Or.inl rfl | (n+1) := Or.inr (succPos _) protected theorem ltTrans {n m k : Nat} (h₁ : n < m) : m < k → n < k := Nat.leTrans (leStep h₁) protected theorem ltOfLeOfLt {n m k : Nat} (h₁ : n ≤ m) : m < k → n < k := Nat.leTrans (succLeSucc h₁) def lt.base (n : Nat) : n < succ n := Nat.leRefl (succ n) theorem ltSuccSelf (n : Nat) : n < succ n := lt.base n protected theorem leAntisymm : ∀ {n m : Nat}, n ≤ m → m ≤ n → n = m | zero zero h₁ h₂ := rfl | (succ n) zero h₁ h₂ := Bool.noConfusion h₁ | zero (succ m) h₁ h₂ := Bool.noConfusion h₂ | (succ n) (succ m) h₁ h₂ := have h₁' : n ≤ m, from h₁, have h₂' : m ≤ n, from h₂, have n = m, from leAntisymm h₁' h₂', congrArg succ this protected theorem ltOrGe : ∀ (n m : Nat), n < m ∨ n ≥ m | n 0 := Or.inr (zeroLe n) | n (m+1) := match ltOrGe n m with | Or.inl h := Or.inl (leSuccOfLe h) | Or.inr h := match Nat.eqOrLtOfLe h with | Or.inl h1 := Or.inl (h1 ▸ ltSuccSelf m) | Or.inr h1 := Or.inr h1 protected theorem leTotal (m n : Nat) : m ≤ n ∨ n ≤ m := Or.elim (Nat.ltOrGe m n) (λ h, Or.inl (Nat.leOfLt h)) Or.inr protected theorem ltOfLeAndNe {m n : Nat} (h1 : m ≤ n) : m ≠ n → m < n := resolveRight (Or.swap (Nat.eqOrLtOfLe h1)) theorem eqZeroOfLeZero {n : Nat} (h : n ≤ 0) : n = 0 := Nat.leAntisymm h (zeroLe _) theorem ltOfSuccLt {n m : Nat} : succ n < m → n < m := leOfSuccLe theorem ltOfSuccLtSucc {n m : Nat} : succ n < succ m → n < m := leOfSuccLeSucc theorem ltOfSuccLe {n m : Nat} (h : succ n ≤ m) : n < m := h theorem succLeOfLt {n m : Nat} (h : n < m) : succ n ≤ m := h theorem ltOrEqOrLeSucc {m n : Nat} (h : m ≤ succ n) : m ≤ n ∨ m = succ n := Decidable.byCases (λ h' : m = succ n, Or.inr h') (λ h' : m ≠ succ n, have m < succ n, from Nat.ltOfLeAndNe h h', have succ m ≤ succ n, from succLeOfLt this, Or.inl (leOfSuccLeSucc this)) theorem leAddRight : ∀ (n k : Nat), n ≤ n + k | n 0 := Nat.leRefl n | n (k+1) := leSuccOfLe (leAddRight n k) theorem leAddLeft (n m : Nat): n ≤ m + n := Nat.addComm n m ▸ leAddRight n m theorem le.dest : ∀ {n m : Nat}, n ≤ m → ∃ k, n + k = m | zero zero h := ⟨0, rfl⟩ | zero (succ n) h := ⟨succ n, show 0 + succ n = succ n, from (Nat.addComm 0 (succ n)).symm ▸ rfl⟩ | (succ n) zero h := Bool.noConfusion h | (succ n) (succ m) h := have n ≤ m, from h, have ∃ k, n + k = m, from le.dest this, match this with | ⟨k, h⟩ := ⟨k, show succ n + k = succ m, from ((succAdd n k).symm ▸ h ▸ rfl)⟩ theorem le.intro {n m k : Nat} (h : n + k = m) : n ≤ m := h ▸ leAddRight n k protected theorem notLeOfGt {n m : Nat} (h : n > m) : ¬ n ≤ m := λ h₁, Or.elim (Nat.ltOrGe n m) (λ h₂, absurd (Nat.ltTrans h h₂) (Nat.ltIrrefl _)) (λ h₂, have Heq : n = m, from Nat.leAntisymm h₁ h₂, absurd (@Eq.subst _ _ _ _ Heq h) (Nat.ltIrrefl m)) theorem gtOfNotLe {n m : Nat} (h : ¬ n ≤ m) : n > m := Or.elim (Nat.ltOrGe m n) (λ h₁, h₁) (λ h₁, absurd h₁ h) protected theorem ltOfLeOfNe {n m : Nat} (h₁ : n ≤ m) (h₂ : n ≠ m) : n < m := Or.elim (Nat.ltOrGe n m) (λ h₃, h₃) (λ h₃, absurd (Nat.leAntisymm h₁ h₃) h₂) protected theorem addLeAddLeft {n m : Nat} (h : n ≤ m) (k : Nat) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ := have h₁ : k + n + w = k + (n + w), from Nat.addAssoc _ _ _, have h₂ : k + (n + w) = k + m, from congrArg _ hw, le.intro $ h₁ ◾ h₂ protected theorem addLeAddRight {n m : Nat} (h : n ≤ m) (k : Nat) : n + k ≤ m + k := have h₁ : n + k = k + n, from Nat.addComm _ _, have h₂ : k + n ≤ k + m, from Nat.addLeAddLeft h k, have h₃ : k + m = m + k, from Nat.addComm _ _, transRelLeft (≤) (transRelRight (≤) h₁ h₂) h₃ protected theorem addLtAddLeft {n m : Nat} (h : n < m) (k : Nat) : k + n < k + m := ltOfSuccLe (addSucc k n ▸ Nat.addLeAddLeft (succLeOfLt h) k) protected theorem addLtAddRight {n m : Nat} (h : n < m) (k : Nat) : n + k < m + k := Nat.addComm k m ▸ Nat.addComm k n ▸ Nat.addLtAddLeft h k protected theorem zeroLtOne : 0 < (1:Nat) := zeroLtSucc 0 theorem leOfLtSucc {m n : Nat} : m < succ n → m ≤ n := leOfSuccLeSucc theorem addLeAdd {a b c d : Nat} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := Nat.leTrans (Nat.addLeAddRight h₁ c) (Nat.addLeAddLeft h₂ b) theorem addLtAdd {a b c d : Nat} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := Nat.ltTrans (Nat.addLtAddRight h₁ c) (Nat.addLtAddLeft h₂ b) /- Basic theorems for comparing numerals -/ theorem natZeroEqZero : Nat.zero = 0 := rfl protected theorem oneNeZero : 1 ≠ (0 : Nat) := assume h, Nat.noConfusion h protected theorem zeroNeOne : 0 ≠ (1 : Nat) := assume h, Nat.noConfusion h theorem succNeZero (n : Nat) : succ n ≠ 0 := assume h, Nat.noConfusion h protected theorem bit0SuccEq (n : Nat) : bit0 (succ n) = succ (succ (bit0 n)) := show succ (succ n + n) = succ (succ (n + n)), from congrArg succ (succAdd n n) protected theorem zeroLtBit0 : ∀ {n : Nat}, n ≠ 0 → 0 < bit0 n | 0 h := absurd rfl h | (succ n) h := have h₁ : 0 < succ (succ (bit0 n)), from zeroLtSucc _, have h₂ : succ (succ (bit0 n)) = bit0 (succ n), from (Nat.bit0SuccEq n).symm, transRelLeft (<) h₁ h₂ protected theorem zeroLtBit1 (n : Nat) : 0 < bit1 n := zeroLtSucc _ protected theorem bit0NeZero : ∀ {n : Nat}, n ≠ 0 → bit0 n ≠ 0 | 0 h := absurd rfl h | (n+1) h := suffices (n+1) + (n+1) ≠ 0, from this, suffices succ ((n+1) + n) ≠ 0, from this, λ h, Nat.noConfusion h protected theorem bit1NeZero (n : Nat) : bit1 n ≠ 0 := show succ (n + n) ≠ 0, from λ h, Nat.noConfusion h protected theorem bit1EqSuccBit0 (n : Nat) : bit1 n = succ (bit0 n) := rfl protected theorem bit1SuccEq (n : Nat) : bit1 (succ n) = succ (succ (bit1 n)) := Eq.trans (Nat.bit1EqSuccBit0 (succ n)) (congrArg succ (Nat.bit0SuccEq n)) protected theorem bit1NeOne : ∀ {n : Nat}, n ≠ 0 → bit1 n ≠ 1 | 0 h h1 := absurd rfl h | (n+1) h h1 := Nat.noConfusion h1 (λ h2, absurd h2 (succNeZero _)) protected theorem bit0NeOne : ∀ n : Nat, bit0 n ≠ 1 | 0 h := absurd h (Ne.symm Nat.oneNeZero) | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succAdd n n ▸ h, Nat.noConfusion h1 (λ h2, absurd h2 (succNeZero (n + n))) protected theorem addSelfNeOne : ∀ (n : Nat), n + n ≠ 1 | 0 h := Nat.noConfusion h | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succAdd n n ▸ h, Nat.noConfusion h1 (λ h2, absurd h2 (Nat.succNeZero (n + n))) protected theorem bit1NeBit0 : ∀ (n m : Nat), bit1 n ≠ bit0 m | 0 m h := absurd h (Ne.symm (Nat.addSelfNeOne m)) | (n+1) 0 h := have h1 : succ (bit0 (succ n)) = 0, from h, absurd h1 (Nat.succNeZero _) | (n+1) (m+1) h := have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from Nat.bit0SuccEq m ▸ Nat.bit1SuccEq n ▸ h, have h2 : bit1 n = bit0 m, from Nat.noConfusion h1 (λ h2', Nat.noConfusion h2' (λ h2'', h2'')), absurd h2 (bit1NeBit0 n m) protected theorem bit0NeBit1 : ∀ (n m : Nat), bit0 n ≠ bit1 m := λ n m : Nat, Ne.symm (Nat.bit1NeBit0 m n) protected theorem bit0Inj : ∀ {n m : Nat}, bit0 n = bit0 m → n = m | 0 0 h := rfl | 0 (m+1) h := absurd h.symm (succNeZero _) | (n+1) 0 h := absurd h (succNeZero _) | (n+1) (m+1) h := have (n+1) + n = (m+1) + m, from Nat.noConfusion h id, have n + (n+1) = m + (m+1), from Nat.addComm (m+1) m ▸ Nat.addComm (n+1) n ▸ this, have succ (n + n) = succ (m + m), from this, have n + n = m + m, from Nat.noConfusion this id, have n = m, from bit0Inj this, congrArg (+1) this protected theorem bit1Inj : ∀ {n m : Nat}, bit1 n = bit1 m → n = m := λ n m h, have succ (bit0 n) = succ (bit0 m), from Nat.bit1EqSuccBit0 n ▸ Nat.bit1EqSuccBit0 m ▸ h, have bit0 n = bit0 m, from Nat.noConfusion this id, Nat.bit0Inj this protected theorem bit0Ne {n m : Nat} : n ≠ m → bit0 n ≠ bit0 m := λ h₁ h₂, absurd (Nat.bit0Inj h₂) h₁ protected theorem bit1Ne {n m : Nat} : n ≠ m → bit1 n ≠ bit1 m := λ h₁ h₂, absurd (Nat.bit1Inj h₂) h₁ protected theorem zeroNeBit0 {n : Nat} : n ≠ 0 → 0 ≠ bit0 n := λ h, Ne.symm (Nat.bit0NeZero h) protected theorem zeroNeBit1 (n : Nat) : 0 ≠ bit1 n := Ne.symm (Nat.bit1NeZero n) protected theorem oneNeBit0 (n : Nat) : 1 ≠ bit0 n := Ne.symm (Nat.bit0NeOne n) protected theorem oneNeBit1 {n : Nat} : n ≠ 0 → 1 ≠ bit1 n := λ h, Ne.symm (Nat.bit1NeOne h) protected theorem oneLtBit1 : ∀ {n : Nat}, n ≠ 0 → 1 < bit1 n | 0 h := absurd rfl h | (succ n) h := suffices succ 0 < succ (succ (bit1 n)), from (Nat.bit1SuccEq n).symm ▸ this, succLtSucc (zeroLtSucc _) protected theorem oneLtBit0 : ∀ {n : Nat}, n ≠ 0 → 1 < bit0 n | 0 h := absurd rfl h | (succ n) h := suffices succ 0 < succ (succ (bit0 n)), from (Nat.bit0SuccEq n).symm ▸ this, succLtSucc (zeroLtSucc _) protected theorem bit0Lt {n m : Nat} (h : n < m) : bit0 n < bit0 m := Nat.addLtAdd h h protected theorem bit1Lt {n m : Nat} (h : n < m) : bit1 n < bit1 m := succLtSucc (Nat.addLtAdd h h) protected theorem bit0LtBit1 {n m : Nat} (h : n ≤ m) : bit0 n < bit1 m := ltSuccOfLe (Nat.addLeAdd h h) protected theorem bit1LtBit0 : ∀ {n m : Nat}, n < m → bit1 n < bit0 m | n 0 h := absurd h (notLtZero _) | n (succ m) h := have n ≤ m, from leOfLtSucc h, have succ (n + n) ≤ succ (m + m), from succLeSucc (addLeAdd this this), have succ (n + n) ≤ succ m + m, from (succAdd m m).symm ▸ this, show succ (n + n) < succ (succ m + m), from ltSuccOfLe this protected theorem oneLeBit1 (n : Nat) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n), from succLeSucc (zeroLe (bit0 n)) protected theorem oneLeBit0 : ∀ (n : Nat), n ≠ 0 → 1 ≤ bit0 n | 0 h := absurd rfl h | (n+1) h := suffices 1 ≤ succ (succ (bit0 n)), from Eq.symm (Nat.bit0SuccEq n) ▸ this, succLeSucc (zeroLe (succ (bit0 n))) /- mul + order -/ theorem mulLeMulLeft {n m : Nat} (k : Nat) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ := have k * n + k * l = k * m, from Nat.leftDistrib k n l ▸ hl.symm ▸ rfl, le.intro this theorem mulLeMulRight {n m : Nat} (k : Nat) (h : n ≤ m) : n * k ≤ m * k := Nat.mulComm k m ▸ Nat.mulComm k n ▸ mulLeMulLeft k h protected theorem mulLeMul {n₁ m₁ n₂ m₂ : Nat} (h₁ : n₁ ≤ n₂) (h₂ : m₁ ≤ m₂) : n₁ * m₁ ≤ n₂ * m₂ := Nat.leTrans (mulLeMulRight _ h₁) (mulLeMulLeft _ h₂) protected theorem mulLtMulOfPosLeft {n m k : Nat} (h : n < m) (hk : k > 0) : k * n < k * m := Nat.ltOfLtOfLe (Nat.addLtAddLeft hk _) (Nat.mulSucc k n ▸ Nat.mulLeMulLeft k (succLeOfLt h)) protected theorem mulLtMulOfPosRight {n m k : Nat} (h : n < m) (hk : k > 0) : n * k < m * k := Nat.mulComm k m ▸ Nat.mulComm k n ▸ Nat.mulLtMulOfPosLeft h hk protected theorem mulPos {n m : Nat} (ha : n > 0) (hb : m > 0) : n * m > 0 := have h : 0 * m < n * m, from Nat.mulLtMulOfPosRight ha hb, Nat.zeroMul m ▸ h /- power -/ theorem powSucc (n m : Nat) : n^(succ m) = n^m * n := rfl theorem powZero (n : Nat) : n^0 = 1 := rfl theorem powLePowOfLeLeft {n m : Nat} (h : n ≤ m) : ∀ i : Nat, n^i ≤ m^i | 0 := Nat.leRefl _ | (succ i) := Nat.mulLeMul (powLePowOfLeLeft i) h theorem powLePowOfLeRight {n : Nat} (hx : n > 0) {i : Nat} : ∀ {j}, i ≤ j → n^i ≤ n^j | 0 h := have i = 0, from eqZeroOfLeZero h, this.symm ▸ Nat.leRefl _ | (succ j) h := Or.elim (ltOrEqOrLeSucc h) (λ h, show n^i ≤ n^j * n, from suffices n^i * 1 ≤ n^j * n, from Nat.mulOne (n^i) ▸ this, Nat.mulLeMul (powLePowOfLeRight h) hx) (λ h, h.symm ▸ Nat.leRefl _) theorem posPowOfPos {n : Nat} (m : Nat) (h : 0 < n) : 0 < n^m := powLePowOfLeRight h (Nat.zeroLe _) /- Max -/ protected def max (n m : Nat) : Nat := if n ≤ m then m else n end Nat
15eb6af053b89ae3bc16817c73f39d3a95d1caad
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/covering/vitali_family.lean
2104ee59faf9f40c0887c5dda6e8f753d9e1a234
[ "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
13,976
lean
/- Copyright (c) 2021 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 measure_theory.measure.measure_space /-! # Vitali families > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. On a metric space `X` with a measure `μ`, consider for each `x : X` a family of measurable sets with nonempty interiors, called `sets_at x`. This family is a Vitali family if it satisfies the following property: consider a (possibly non-measurable) set `s`, and for any `x` in `s` a subfamily `f x` of `sets_at x` containing sets of arbitrarily small diameter. Then one can extract a disjoint subfamily covering almost all `s`. Vitali families are provided by covering theorems such as the Besicovitch covering theorem or the Vitali covering theorem. They make it possible to formulate general versions of theorems on differentiations of measure that apply in both contexts. This file gives the basic definition of Vitali families. More interesting developments of this notion are deferred to other files: * constructions of specific Vitali families are provided by the Besicovitch covering theorem, in `besicovitch.vitali_family`, and by the Vitali covering theorem, in `vitali.vitali_family`. * The main theorem on differentiation of measures along a Vitali family is proved in `vitali_family.ae_tendsto_rn_deriv`. ## Main definitions * `vitali_family μ` is a structure made, for each `x : X`, of a family of sets around `x`, such that one can extract an almost everywhere disjoint covering from any subfamily containing sets of arbitrarily small diameters. Let `v` be such a Vitali family. * `v.fine_subfamily_on` describes the subfamilies of `v` from which one can extract almost everywhere disjoint coverings. This property, called `v.fine_subfamily_on.exists_disjoint_covering_ae`, is essentially a restatement of the definition of a Vitali family. We also provide an API to use efficiently such a disjoint covering. * `v.filter_at x` is a filter on sets of `X`, such that convergence with respect to this filter means convergence when sets in the Vitali family shrink towards `x`. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.8][Federer1996] (Vitali families are called Vitali relations there) -/ open measure_theory metric set filter topological_space measure_theory.measure open_locale filter measure_theory topology variables {α : Type*} [metric_space α] /-- On a metric space `X` with a measure `μ`, consider for each `x : X` a family of measurable sets with nonempty interiors, called `sets_at x`. This family is a Vitali family if it satisfies the following property: consider a (possibly non-measurable) set `s`, and for any `x` in `s` a subfamily `f x` of `sets_at x` containing sets of arbitrarily small diameter. Then one can extract a disjoint subfamily covering almost all `s`. Vitali families are provided by covering theorems such as the Besicovitch covering theorem or the Vitali covering theorem. They make it possible to formulate general versions of theorems on differentiations of measure that apply in both contexts. -/ @[nolint has_nonempty_instance] structure vitali_family {m : measurable_space α} (μ : measure α) := (sets_at : Π (x : α), set (set α)) (measurable_set' : ∀ (x : α), ∀ (a : set α), a ∈ sets_at x → measurable_set a) (nonempty_interior : ∀ (x : α), ∀ (y : set α), y ∈ sets_at x → (interior y).nonempty) (nontrivial : ∀ (x : α) (ε > (0 : ℝ)), ∃ y ∈ sets_at x, y ⊆ closed_ball x ε) (covering : ∀ (s : set α) (f : Π (x : α), set (set α)), (∀ x ∈ s, f x ⊆ sets_at x) → (∀ (x ∈ s) (ε > (0 : ℝ)), ∃ a ∈ f x, a ⊆ closed_ball x ε) → ∃ (t : set (α × set α)), (∀ (p : α × set α), p ∈ t → p.1 ∈ s) ∧ t.pairwise_disjoint (λ p, p.2) ∧ (∀ (p : α × set α), p ∈ t → p.2 ∈ f p.1) ∧ μ (s \ ⋃ (p : α × set α) (hp : p ∈ t), p.2) = 0) namespace vitali_family variables {m0 : measurable_space α} {μ : measure α} include μ /-- A Vitali family for a measure `μ` is also a Vitali family for any measure absolutely continuous with respect to `μ`. -/ def mono (v : vitali_family μ) (ν : measure α) (hν : ν ≪ μ) : vitali_family ν := { sets_at := v.sets_at, measurable_set' := v.measurable_set', nonempty_interior := v.nonempty_interior, nontrivial := v.nontrivial, covering := λ s f h h', begin rcases v.covering s f h h' with ⟨t, ts, disj, mem_f, hμ⟩, exact ⟨t, ts, disj, mem_f, hν hμ⟩ end } /-- Given a Vitali family `v` for a measure `μ`, a family `f` is a fine subfamily on a set `s` if every point `x` in `s` belongs to arbitrarily small sets in `v.sets_at x ∩ f x`. This is precisely the subfamilies for which the Vitali family definition ensures that one can extract a disjoint covering of almost all `s`. -/ def fine_subfamily_on (v : vitali_family μ) (f : α → set (set α)) (s : set α) : Prop := ∀ x ∈ s, ∀ (ε > 0), ∃ a ∈ v.sets_at x ∩ f x, a ⊆ closed_ball x ε namespace fine_subfamily_on variables {v : vitali_family μ} {f : α → set (set α)} {s : set α} (h : v.fine_subfamily_on f s) include h theorem exists_disjoint_covering_ae : ∃ (t : set (α × set α)), (∀ (p : α × set α), p ∈ t → p.1 ∈ s) ∧ t.pairwise_disjoint (λ p, p.2) ∧ (∀ (p : α × set α), p ∈ t → p.2 ∈ v.sets_at p.1 ∩ f p.1) ∧ μ (s \ ⋃ (p : α × set α) (hp : p ∈ t), p.2) = 0 := v.covering s (λ x, v.sets_at x ∩ f x) (λ x hx, inter_subset_left _ _) h /-- Given `h : v.fine_subfamily_on f s`, then `h.index` is a set parametrizing a disjoint covering of almost every `s`. -/ protected def index : set (α × set α) := h.exists_disjoint_covering_ae.some /-- Given `h : v.fine_subfamily_on f s`, then `h.covering p` is a set in the family, for `p ∈ h.index`, such that these sets form a disjoint covering of almost every `s`. -/ @[nolint unused_arguments] protected def covering : α × set α → set α := λ p, p.2 lemma index_subset : ∀ (p : α × set α), p ∈ h.index → p.1 ∈ s := h.exists_disjoint_covering_ae.some_spec.1 lemma covering_disjoint : h.index.pairwise_disjoint h.covering := h.exists_disjoint_covering_ae.some_spec.2.1 lemma covering_disjoint_subtype : pairwise (disjoint on (λ x : h.index, h.covering x)) := (pairwise_subtype_iff_pairwise_set _ _).2 h.covering_disjoint lemma covering_mem {p : α × set α} (hp : p ∈ h.index) : h.covering p ∈ f p.1 := (h.exists_disjoint_covering_ae.some_spec.2.2.1 p hp).2 lemma covering_mem_family {p : α × set α} (hp : p ∈ h.index) : h.covering p ∈ v.sets_at p.1 := (h.exists_disjoint_covering_ae.some_spec.2.2.1 p hp).1 lemma measure_diff_bUnion : μ (s \ ⋃ p ∈ h.index, h.covering p) = 0 := h.exists_disjoint_covering_ae.some_spec.2.2.2 lemma index_countable [second_countable_topology α] : h.index.countable := h.covering_disjoint.countable_of_nonempty_interior (λ x hx, v.nonempty_interior _ _ (h.covering_mem_family hx)) protected lemma measurable_set_u {p : α × set α} (hp : p ∈ h.index) : measurable_set (h.covering p) := v.measurable_set' p.1 _ (h.covering_mem_family hp) lemma measure_le_tsum_of_absolutely_continuous [second_countable_topology α] {ρ : measure α} (hρ : ρ ≪ μ) : ρ s ≤ ∑' (p : h.index), ρ (h.covering p) := calc ρ s ≤ ρ ((s \ ⋃ (p ∈ h.index), h.covering p) ∪ (⋃ (p ∈ h.index), h.covering p)) : measure_mono (by simp only [subset_union_left, diff_union_self]) ... ≤ ρ (s \ ⋃ (p ∈ h.index), h.covering p) + ρ (⋃ (p ∈ h.index), h.covering p) : measure_union_le _ _ ... = ∑' (p : h.index), ρ (h.covering p) : by rw [hρ h.measure_diff_bUnion, measure_bUnion h.index_countable h.covering_disjoint (λ x hx, h.measurable_set_u hx), zero_add] lemma measure_le_tsum [second_countable_topology α] : μ s ≤ ∑' (x : h.index), μ (h.covering x) := h.measure_le_tsum_of_absolutely_continuous measure.absolutely_continuous.rfl end fine_subfamily_on /-- One can enlarge a Vitali family by adding to the sets `f x` at `x` all sets which are not contained in a `δ`-neighborhood on `x`. This does not change the local filter at a point, but it can be convenient to get a nicer global behavior. -/ def enlarge (v : vitali_family μ) (δ : ℝ) (δpos : 0 < δ) : vitali_family μ := { sets_at := λ x, v.sets_at x ∪ {a | measurable_set a ∧ (interior a).nonempty ∧ ¬(a ⊆ closed_ball x δ)}, measurable_set' := λ x a ha, by { cases ha, exacts [v.measurable_set' _ _ ha, ha.1] }, nonempty_interior := λ x a ha, by { cases ha, exacts [v.nonempty_interior _ _ ha, ha.2.1] }, nontrivial := begin assume x ε εpos, rcases v.nontrivial x ε εpos with ⟨a, ha, h'a⟩, exact ⟨a, mem_union_left _ ha, h'a⟩, end, covering := begin assume s f fset ffine, let g : α → set (set α) := λ x, f x ∩ v.sets_at x, have : ∀ x ∈ s, ∀ (ε : ℝ), ε > 0 → (∃ (a : set α) (H : a ∈ g x), a ⊆ closed_ball x ε), { assume x hx ε εpos, obtain ⟨a, af, ha⟩ : ∃ a ∈ f x, a ⊆ closed_ball x (min ε δ), from ffine x hx (min ε δ) (lt_min εpos δpos), rcases fset x hx af with h'a|h'a, { exact ⟨a, ⟨af, h'a⟩, ha.trans (closed_ball_subset_closed_ball (min_le_left _ _))⟩ }, { refine false.elim (h'a.2.2 _), exact ha.trans (closed_ball_subset_closed_ball (min_le_right _ _)) } }, rcases v.covering s g (λ x hx, inter_subset_right _ _) this with ⟨t, ts, tdisj, tg, μt⟩, exact ⟨t, ts, tdisj, λ p hp, (tg p hp).1, μt⟩, end } variable (v : vitali_family μ) include v /-- Given a vitali family `v`, then `v.filter_at x` is the filter on `set α` made of those families that contain all sets of `v.sets_at x` of a sufficiently small diameter. This filter makes it possible to express limiting behavior when sets in `v.sets_at x` shrink to `x`. -/ def filter_at (x : α) : filter (set α) := ⨅ (ε ∈ Ioi (0 : ℝ)), 𝓟 {a ∈ v.sets_at x | a ⊆ closed_ball x ε} lemma mem_filter_at_iff {x : α} {s : set (set α)} : (s ∈ v.filter_at x) ↔ ∃ (ε > (0 : ℝ)), ∀ a ∈ v.sets_at x, a ⊆ closed_ball x ε → a ∈ s := begin simp only [filter_at, exists_prop, gt_iff_lt], rw mem_binfi_of_directed, { simp only [subset_def, and_imp, exists_prop, mem_sep_iff, mem_Ioi, mem_principal] }, { simp only [directed_on, exists_prop, ge_iff_le, le_principal_iff, mem_Ioi, order.preimage, mem_principal], assume x hx y hy, refine ⟨min x y, lt_min hx hy, λ a ha, ⟨ha.1, ha.2.trans (closed_ball_subset_closed_ball (min_le_left _ _))⟩, λ a ha, ⟨ha.1, ha.2.trans (closed_ball_subset_closed_ball (min_le_right _ _))⟩⟩ }, { exact ⟨(1 : ℝ), mem_Ioi.2 zero_lt_one⟩ } end instance filter_at_ne_bot (x : α) : (v.filter_at x).ne_bot := begin simp only [ne_bot_iff, ←empty_mem_iff_bot, mem_filter_at_iff, not_exists, exists_prop, mem_empty_iff_false, and_true, gt_iff_lt, not_and, ne.def, not_false_iff, not_forall], assume ε εpos, obtain ⟨w, w_sets, hw⟩ : ∃ (w ∈ v.sets_at x), w ⊆ closed_ball x ε := v.nontrivial x ε εpos, exact ⟨w, w_sets, hw⟩ end lemma eventually_filter_at_iff {x : α} {P : set α → Prop} : (∀ᶠ a in v.filter_at x, P a) ↔ ∃ (ε > (0 : ℝ)), ∀ a ∈ v.sets_at x, a ⊆ closed_ball x ε → P a := v.mem_filter_at_iff lemma eventually_filter_at_mem_sets (x : α) : ∀ᶠ a in v.filter_at x, a ∈ v.sets_at x := begin simp only [eventually_filter_at_iff, exists_prop, and_true, gt_iff_lt, implies_true_iff] {contextual := tt}, exact ⟨1, zero_lt_one⟩ end lemma eventually_filter_at_subset_closed_ball (x : α) {ε : ℝ} (hε : 0 < ε) : ∀ᶠ (a : set α) in v.filter_at x, a ⊆ closed_ball x ε := begin simp only [v.eventually_filter_at_iff], exact ⟨ε, hε, λ a ha ha', ha'⟩, end lemma tendsto_filter_at_iff {ι : Type*} {l : filter ι} {f : ι → set α} {x : α} : tendsto f l (v.filter_at x) ↔ (∀ᶠ i in l, f i ∈ v.sets_at x) ∧ (∀ (ε > (0 : ℝ)), ∀ᶠ i in l, f i ⊆ closed_ball x ε) := begin refine ⟨λ H, ⟨H.eventually $ v.eventually_filter_at_mem_sets x, λ ε hε, H.eventually $ v.eventually_filter_at_subset_closed_ball x hε⟩, λ H s hs, (_ : ∀ᶠ i in l, f i ∈ s)⟩, obtain ⟨ε, εpos, hε⟩ := v.mem_filter_at_iff.mp hs, filter_upwards [H.1, H.2 ε εpos] with i hi hiε using hε _ hi hiε, end lemma eventually_filter_at_measurable_set (x : α) : ∀ᶠ a in v.filter_at x, measurable_set a := by { filter_upwards [v.eventually_filter_at_mem_sets x] with _ ha using v.measurable_set' _ _ ha } lemma frequently_filter_at_iff {x : α} {P : set α → Prop} : (∃ᶠ a in v.filter_at x, P a) ↔ ∀ (ε > (0 : ℝ)), ∃ a ∈ v.sets_at x, a ⊆ closed_ball x ε ∧ P a := by simp only [filter.frequently, eventually_filter_at_iff, not_exists, exists_prop, not_and, not_not, not_forall] lemma eventually_filter_at_subset_of_nhds {x : α} {o : set α} (hx : o ∈ 𝓝 x) : ∀ᶠ a in v.filter_at x, a ⊆ o := begin rw eventually_filter_at_iff, rcases metric.mem_nhds_iff.1 hx with ⟨ε, εpos, hε⟩, exact ⟨ε/2, half_pos εpos, λ a av ha, ha.trans ((closed_ball_subset_ball (half_lt_self εpos)).trans hε)⟩ end lemma fine_subfamily_on_of_frequently (v : vitali_family μ) (f : α → set (set α)) (s : set α) (h : ∀ x ∈ s, ∃ᶠ a in v.filter_at x, a ∈ f x) : v.fine_subfamily_on f s := begin assume x hx ε εpos, obtain ⟨a, av, ha, af⟩ : ∃ (a : set α) (H : a ∈ v.sets_at x), a ⊆ closed_ball x ε ∧ a ∈ f x := v.frequently_filter_at_iff.1 (h x hx) ε εpos, exact ⟨a, ⟨av, af⟩, ha⟩, end end vitali_family
aa6bd4e3079aa614ff48533003d0ab5c49703fd5
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/transition/production.lean
c1ab875b03b8fd2b9378bbc724106e137ae4b328
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
4,261
lean
import data.cpi.concretion data.cpi.transition.label namespace cpi variables {ℍ : Type} {ω : context} /-- The right hand side of a transition, determined by a specific kind. -/ @[derive decidable_eq, nolint has_inhabited_instance] inductive production (ℍ : Type) (ω : context) (Γ : context) : kind → Type | species (A : species ℍ ω Γ) : production kind.species | concretion {b y} (F : concretion ℍ ω Γ b y) : production kind.concretion instance production.has_repr [has_repr ℍ] {Γ k} : has_repr (production ℍ ω Γ k) := ⟨ λ x, by from production.rec_on x repr (λ _ _ x, repr x), ⟩ /-- Rename a production. This just wraps renaming for species and concretions. -/ def production.rename {Γ Δ} (ρ : name Γ → name Δ) : ∀ {k}, production ℍ ω Γ k → production ℍ ω Δ k | ._ (production.species A) := production.species (species.rename ρ A) | ._ (production.concretion A) := production.concretion (concretion.rename ρ A) lemma production.rename_compose {Γ Δ η} (ρ : name Γ → name Δ) (σ : name Δ → name η) : ∀ {k} (E : production ℍ ω Γ k) , production.rename σ (production.rename ρ E) = production.rename (σ ∘ ρ) E | ._ (production.species A) := congr_arg _ (species.rename_compose ρ σ A) | ._ (production.concretion F) := congr_arg _ (concretion.rename_compose ρ σ F) lemma production.rename_id {Γ} : ∀ {k} (E : production ℍ ω Γ k), production.rename id E = E | ._ (production.species A) := congr_arg _ (species.rename_id A) | ._ (production.concretion F) := congr_arg _ (concretion.rename_id F) /-- Equivalence of productions. This just wraps equivalence of species and concretions. -/ inductive production.equiv [∀ Γ, setoid (species ℍ ω Γ)] [∀ Γ b y, setoid (concretion ℍ ω Γ b y)] {Γ} : ∀ {k : kind}, production ℍ ω Γ k → production ℍ ω Γ k → Prop | species {A B : species ℍ ω Γ} : A ≈ B → production.equiv (production.species A) (production.species B) | concretion {b y} {F G : concretion ℍ ω Γ b y} : F ≈ G → production.equiv (production.concretion F) (production.concretion G) namespace production variables [∀ Γ, setoid (cpi.species ℍ ω Γ)] [∀ Γ b y, setoid (cpi.concretion ℍ ω Γ b y)] lemma equiv.refl {Γ} : ∀ {k : kind} (E : production ℍ ω Γ k), equiv E E | ._ (species A) := equiv.species (refl A) | ._ (concretion F) := equiv.concretion (refl F) lemma equiv.symm {Γ} : ∀ {k : kind} (E F : production ℍ ω Γ k), equiv E F → equiv F E | ._ ._ ._ (equiv.species eq) := equiv.species (symm eq) | ._ ._ ._ (equiv.concretion eq) := equiv.concretion (symm eq) lemma equiv.trans {Γ} : ∀ {k : kind} (E F G : production ℍ ω Γ k), equiv E F → equiv F G → equiv E G | ._ ._ ._ ._ (equiv.species ef) (equiv.species fg) := equiv.species (trans ef fg) | ._ ._ ._ ._ (equiv.concretion ef) (equiv.concretion fg) := equiv.concretion (trans ef fg) instance {Γ} {k} : is_equiv (production ℍ ω Γ k) equiv := { refl := equiv.refl, symm := equiv.symm, trans := equiv.trans } instance {Γ} {k} : is_refl (production ℍ ω Γ k) equiv := ⟨ equiv.refl ⟩ instance {Γ} {k} : setoid (production ℍ ω Γ k) := ⟨ equiv, ⟨ equiv.refl, equiv.symm, equiv.trans ⟩ ⟩ instance setoid.is_equiv {Γ} {k} : is_equiv (production ℍ ω Γ k) has_equiv.equiv := production.is_equiv end production section equivalence variables [∀ Γ, setoid (cpi.species ℍ ω Γ)] [∀ Γ b y, setoid (cpi.concretion ℍ ω Γ b y)] lemma production.equiv.unwrap_s : ∀ {Γ} {A B : species ℍ ω Γ}, production.species A ≈ production.species B → A ≈ B | Γ A B (production.equiv.species eq) := eq lemma production.equiv.arity : ∀ {Γ} {a b x y} {F : concretion ℍ ω Γ a x} {G : concretion ℍ ω Γ b y} , production.concretion F ≈ production.concretion G → a = b ∧ x = y | Γ a b x y F G (production.equiv.concretion eq) := ⟨ rfl, rfl ⟩ lemma production.equiv.unwrap_c : ∀ {Γ} {b y} {F : concretion ℍ ω Γ b y} {G : concretion ℍ ω Γ b y} , production.concretion F ≈ production.concretion G → F ≈ G | Γ b y F G (production.equiv.concretion eq) := eq end equivalence end cpi #lint-
24476a191784092af6b6b204fd3813118cc7f47e
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/num/lemmas.lean
11d4e326465552c216f16f133177c081a3134b82
[ "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
48,649
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.num.bitwise import data.int.char_zero import data.nat.gcd import data.nat.psub /-! # Properties of the binary representation of integers -/ local attribute [simp] add_assoc namespace pos_num variables {α : Type*} @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_zero α] [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp, norm_cast] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm] theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp [add_left_comm] | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm] | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm] | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp [add_left_comm] theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[norm_cast] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((n:ℕ) < m) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[norm_cast] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp, norm_cast] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] @[norm_cast] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] @[simp, norm_cast] theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] @[norm_cast] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.left_inverse.injective to_of_nat h, congr_arg _⟩ @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[norm_cast] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((n:ℕ) < m) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[norm_cast] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp, norm_cast] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat @[norm_cast] theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm, add_comm] instance : ordered_cancel_add_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid } @[norm_cast] theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩ end num namespace pos_num variables {α : Type*} open num @[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] instance : has_dvd pos_num := ⟨λ m n, pos m ∣ pos n⟩ @[norm_cast] theorem dvd_to_nat {m n : pos_num} : (m:ℕ) ∣ n ↔ m ∣ n := num.dvd_to_nat (pos m) (pos n) theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, norm_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast, priority 500] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos @[simp] theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp, norm_cast] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp, norm_cast] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp, norm_cast] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec rfl $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp, norm_cast squash] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : 1 < n) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp, norm_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp, norm_cast] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp, norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp, norm_cast] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp, norm_cast] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit0, sub_eq_add_neg] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm] | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm] @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp, norm_cast] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl @[norm_cast] theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_int h, congr_arg _⟩ @[simp, norm_cast] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp, norm_cast] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n := of_int_cast n @[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n | (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int'] | -[1+ n] := to_int_inj.1 $ by simp [znum.of_int'] theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((n:ℤ) < m) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[norm_cast] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, exists_pair_ne := ⟨0, 1, dec_trivial⟩, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, mul_pos := λ a b, show 0 < a → 0 < b → 0 < a * b, by {transfer_rw, apply mul_pos}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } @[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := rfl | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := rfl | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [pow_succ', ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance decidable_dvd : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num instance pos_num.decidable_dvd : decidable_rel ((∣) : pos_num → pos_num → Prop) | a b := num.decidable_dvd _ _ namespace znum @[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := rfl | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum namespace int def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
c54fe0491836fb928b0a4b649ee05d1e88b8ec62
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group_power/default.lean
550de2e5e2ee3ce6dbe835afd1b0d1e296209d49
[]
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
146
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group_power.lemmas import Mathlib.PostPort namespace Mathlib
a258db1c3193d0a6034610d422d4be65d9b2873e
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Lean/Meta/WHNF.lean
2484fc21577c22c40a9aa16f3301c7c17fdcf8a1
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
27,766
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ToExpr import Lean.AuxRecursor import Lean.ProjFns import Lean.Structure import Lean.Util.Recognizers import Lean.Meta.Basic import Lean.Meta.GetConst import Lean.Meta.Match.MatcherInfo namespace Lean.Meta /- =========================== Smart unfolding support =========================== -/ def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (declName : Name) : Name := Name.mkStr declName smartUnfoldingSuffix register_builtin_option smartUnfolding : Bool := { defValue := true descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } /-- Add auxiliary annotation to indicate the `match`-expression `e` must be reduced when performing smart unfolding. -/ def markSmartUnfoldingMatch (e : Expr) : Expr := mkAnnotation `sunfoldMatch e def smartUnfoldingMatch? (e : Expr) : Option Expr := annotation? `sunfoldMatch e /-- Add auxiliary annotation to indicate expression `e` (a `match` alternative rhs) was successfully reduced by smart unfolding. -/ def markSmartUnfoldigMatchAlt (e : Expr) : Expr := mkAnnotation `sunfoldMatchAlt e def smartUnfoldingMatchAlt? (e : Expr) : Option Expr := annotation? `sunfoldMatchAlt e /- =========================== Helper methods =========================== -/ def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv return isAuxRecursor env constName || isNoConfusion env constName @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls _ => do let (some cinfo) ← getConst? name | failK () k cinfo lvls | _ => failK () /- =========================== Helper functions for reducing recursors =========================== -/ private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none return some ctor private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := do match type.getAppFn with | Expr.const d lvls _ => let (some ctor) ← getFirstCtor d | pure none return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => return none def toCtorIfLit : Expr → Expr | Expr.lit (Literal.natVal v) _ => if v == 0 then mkConst `Nat.zero else mkApp (mkConst `Nat.succ) (mkRawNatLit (v-1)) | Expr.lit (Literal.strVal v) _ => mkApp (mkConst `String.mk) (toExpr v.toList) | e => e private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ _ => recVal.rules.find? fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM Expr := do let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then return major else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then return major else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure major let newType ← inferType newCtorApp if (← isDefEq majorType newType) then return newCtorApp else return major /-- If `major` is not a constructor application, and its type is a structure `C ...`, then return `C.mk major.1 ... major.n` \pre `inductName` is `C`. If `Meta.Config.etaStruct` is `false` or the condition above does not hold, this method just returns `major`. -/ private def toCtorWhenStructure (inductName : Name) (major : Expr) : MetaM Expr := do unless (← getConfig).etaStruct do return major let env ← getEnv if !isStructureLike env inductName then return major else if let some _ := major.isConstructorApp? env then return major else let majorType ← inferType major let majorType ← instantiateMVars (← whnf majorType) let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf inductName then return major match majorType.getAppFn with | Expr.const d us _ => let some ctorName ← getFirstCtor d | pure major let ctorInfo ← getConstInfoCtor ctorName let mut result := mkAppN (mkConst ctorName us) (majorType.getAppArgs.shrink ctorInfo.numParams) for i in [:ctorInfo.numFields] do result := mkApp result (mkProj inductName i major) return result | _ => return major /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← whnf major if recVal.k then major ← toCtorWhenK recVal major major := toCtorIfLit major major ← toCtorWhenStructure recVal.getInduct major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.levelParams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () /- =========================== Helper functions for reducing Quot.lift and Quot.ind =========================== -/ /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK () let f := recArgs[argPos] let r := mkApp f majorArg let recArity := majorPos + 1 successK $ mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () /- =========================== Helper function for extracting "stuck term" =========================== -/ mutual private partial def isRecStuck? (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case return none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else return none private partial def isQuotRecStuck? (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else return none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => return none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? : Expr → MetaM (Option MVarId) | Expr.mdata _ e _ => getStuckMVar? e | Expr.proj _ _ e _ => do getStuckMVar? (← whnf e) | e@(Expr.mvar ..) => do let e ← instantiateMVars e match e with | Expr.mvar mvarId _ => pure (some mvarId) | _ => getStuckMVar? e | e@(Expr.app f _ _) => let f := f.getAppFn match f with | Expr.mvar mvarId _ => return some mvarId | Expr.const fName fLvls _ => do let cinfo? ← getConstNoEx? fName match cinfo? with | some $ ConstantInfo.recInfo recVal => isRecStuck? recVal fLvls e.getAppArgs | some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal fLvls e.getAppArgs | _ => return none | _ => return none | _ => return none end /- =========================== Weak Head Normal Form auxiliary combinators =========================== -/ /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do match e with | Expr.forallE .. => return e | Expr.lam .. => return e | Expr.sort .. => return e | Expr.lit .. => return e | Expr.bvar .. => unreachable! | Expr.letE .. => k e | Expr.const .. => k e | Expr.app .. => k e | Expr.proj .. => k e | Expr.mdata _ e _ => whnfEasyCases e k | Expr.fvar fvarId _ => let decl ← getLocalDecl fvarId match decl with | LocalDecl.cdecl .. => return e | LocalDecl.ldecl (value := v) (nonDep := nonDep) .. => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then return e else if cfg.trackZeta then modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | Expr.mvar mvarId _ => match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => return e @[specialize] private def deltaDefinition (c : ConstantInfo) (lvls : List Level) (failK : Unit → α) (successK : Expr → α) : α := if c.levelParams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls successK val @[specialize] private def deltaBetaDefinition (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → α) (successK : Expr → α) : α := if c.levelParams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls let val := val.betaRev revArgs successK val inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels _ => let some info ← getMatcherInfo? declName | return ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then return ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f := constInfo.instantiateValueLevelParams declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp := mkAppN auxApp hs /- When reducing `match` expressions, if the reducibility setting is at `TransparencyMode.reducible`, we increase it to `TransparencyMode.instance`. We use the `TransparencyMode.reducible` in many places (e.g., `simp`), and this setting prevents us from reducing `match` expressions where the discriminants are terms such as `OfNat.ofNat α n inst`. For example, `simp [Int.div]` will not unfold the application `Int.div 2 1` occuring in the target. TODO: consider other solutions; investigate whether the solution above produces counterintuitive behavior. -/ let mut transparency ← getTransparency if transparency == TransparencyMode.reducible then transparency := TransparencyMode.instances let auxApp ← withTransparency transparency <| whnf auxApp let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i] auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher /- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/ def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e ← whnf e let e := toCtorIfLit e matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.numParams + i if idx < numArgs then return some (e.getArg! idx) else return none /-- Reduce kernel projection `Expr.proj ..` expression. -/ def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c _ => project? c i | _ => return none /- Auxiliary method for reducing terms of the form `?m t_1 ... t_n` where `?m` is delayed assigned. Recall that we can only expand a delayed assignment when all holes/metavariables in the assigned value have been "filled". -/ private def whnfDelayedAssigned? (f' : Expr) (e : Expr) : MetaM (Option Expr) := do if f'.isMVar then match (← getDelayedAssignment? f'.mvarId!) with | none => return none | some { fvars := fvars, val := val, .. } => let args := e.getAppArgs if fvars.size > args.size then -- Insufficient number of argument to expand delayed assignment return none else let newVal ← instantiateMVars val if newVal.hasExprMVar then -- Delayed assignment still contains metavariables return none else let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args return mkAppRange result fvars.size args.size args else return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. -/ partial def whnfCore (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf] e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => whnfCore $ b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← whnfCore f if f'.isLambda then let revArgs := e.getAppRevArgs whnfCore <| f'.betaRev revArgs else if let some eNew ← whnfDelayedAssigned? f' e then whnfCore eNew else let e := if f == f' then e else e.updateFn f' match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => whnfCore eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => matchConstAux f' (fun _ => return e) fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs (fun _ => return e) whnfCore | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs (fun _ => return e) whnfCore | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => return e) whnfCore else return e | _ => return e | Expr.proj .. => match (← reduceProj? e) with | some e => whnfCore e | none => return e | _ => unreachable! /-- Recall that `_sunfold` auxiliary definitions contains the markers: `markSmartUnfoldigMatch` (*) and `markSmartUnfoldigMatchAlt` (**). For example, consider the following definition ``` def r (i j : Nat) : Nat := i + match j with | Nat.zero => 1 | Nat.succ j => i + match j with | Nat.zero => 2 | Nat.succ j => r i j ``` produces the following `_sunfold` auxiliary definition with the markers ``` def r._sunfold (i j : Nat) : Nat := i + (*) match j with | Nat.zero => (**) 1 | Nat.succ j => i + (*) match j with | Nat.zero => (**) 2 | Nat.succ j => (**) r i j ``` `match` expressions marked with `markSmartUnfoldigMatch` (*) must be reduced, otherwise the resulting term is not definitionally equal to the given expression. The recursion may be interrupted as soon as the annotation `markSmartUnfoldingAlt` (**) is reached. For example, the term `r i j.succ.succ` reduces to the definitionally equal term `i + i * r i j` -/ partial def smartUnfoldingReduce? (e : Expr) : MetaM (Option Expr) := go e |>.run where go (e : Expr) : OptionT MetaM Expr := do match e with | Expr.letE n t v b _ => withLetDecl n t (← go v) fun x => do mkLetFVars #[x] (← go (b.instantiate1 x)) | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← go b) | Expr.app f a .. => mkApp (← go f) (← go a) | Expr.proj _ _ s _ => e.updateProj! (← go s) | Expr.mdata _ b _ => if let some m := smartUnfoldingMatch? e then goMatch m else e.updateMData! (← go b) | _ => return e goMatch (e : Expr) : OptionT MetaM Expr := do match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => if let some alt := smartUnfoldingMatchAlt? e then return alt else go e | ReduceMatcherResult.stuck e' => let mvarId ← getStuckMVar? e' /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then goMatch e else failure | _ => failure mutual /-- Auxiliary method for unfolding a class projection. -/ partial def unfoldProjInst? (e : Expr) : MetaM (Option Expr) := do match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { fromClass := true, .. } => match (← withDefault <| unfoldDefinition? e) with | none => return none | some e => match (← withReducibleAndInstances <| reduceProj? e.getAppFn) with | none => return none | some r => return mkAppN r e.getAppArgs |>.headBeta | _ => return none | _ => return none /-- Auxiliary method for unfolding a class projection. when transparency is set to `TransparencyMode.instances`. Recall that class instance projections are not marked with `[reducible]` because we want them to be in "reducible canonical form". -/ private partial def unfoldProjInstWhenIntances? (e : Expr) : MetaM (Option Expr) := do if (← getTransparency) != TransparencyMode.instances then return none else unfoldProjInst? e /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ _ => matchConstAux f.getAppFn (fun _ => unfoldProjInstWhenIntances? e) fun fInfo fLvls => do if fInfo.levelParams.length != fLvls.length then return none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none if smartUnfolding.get (← getOptions) then match (← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name)) with | some fAuxInfo@(ConstantInfo.defnInfo _) => deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) fun e₁ => smartUnfoldingReduce? e₁ | _ => if (← getMatcherInfo? fInfo.name).isSome then -- Recall that `whnfCore` tries to reduce "matcher" applications. return none else unfoldDefault () else unfoldDefault () | Expr.const declName lvls _ => do if smartUnfolding.get (← getOptions) && (← getEnv).contains (mkSmartUnfoldingNameFor declName) then return none else let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? declName | pure none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => return none end def unfoldDefinition (e : Expr) : MetaM Expr := do let some e ← unfoldDefinition? e | throwError "failed to unfold definition{indentExpr e}" return e @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => return e else return e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => return !e.isAppOf declName) if e.isAppOf declName then return e else return none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none | _ => return none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool @[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ => if fName == `Lean.reduceBool then do return toExpr (← reduceBoolNative argName) else if fName == `Lean.reduceNat then do return toExpr (← reduceNatNative argName) else return none | _ => return none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ _ => k 0 | Expr.lit (Literal.natVal v) _ => k v | _ => return none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => return mkRawNatLit <| f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp] "{a} op {b}" return mkRawNatLit <| f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => return toExpr <| f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then return none else match e with | Expr.app (Expr.const fn _ _) a _ => if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a else return none | Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ => if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2 else return none | _ => return none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar then return false else match (← getConfig).transparency with | TransparencyMode.default => true | TransparencyMode.all => true | _ => false @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.whnfDefault.find? e | TransparencyMode.all => return (← get).cache.whnfAll.find? e | _ => unreachable! else return none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r } | TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r } | _ => unreachable! return r @[export lean_whnf] partial def whnfImp (e : Expr) : MetaM Expr := withIncRecDepth <| whnfEasyCases e fun e => do checkMaxHeartbeats "whnf" let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' /-- If `e` is a projection function that satisfies `p`, then reduce it -/ def reduceProjOf? (e : Expr) (p : Name → Bool) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name .. => do let env ← getEnv match env.getProjectionStructureName? name with | some structName => if p structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none builtin_initialize registerTraceClass `Meta.whnf end Lean.Meta
6844159ade579ac5e58ad928c85bb90482d0a565
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/lattice.lean
ff6bbe04e750df3757b3c8c9958cb6c3924431a8
[ "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,825
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, Floris van Doorn, Gabriel Ebner, Yury Kudryashov -/ import order.conditionally_complete_lattice.finset /-! # Conditionally complete linear order structure on `ℕ` In this file we * define a `conditionally_complete_linear_order_bot` structure on `ℕ`; * prove a few lemmas about `supr`/`infi`/`set.Union`/`set.Inter` and natural numbers. -/ open set namespace nat open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_def {s : set ℕ} (h : s.nonempty) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ lemma _root_.set.infinite.nat.Sup_eq_zero {s : set ℕ} (h : s.infinite) : Sup s = 0 := dif_neg $ λ ⟨n, hn⟩, let ⟨k, hks, hk⟩ := h.exists_nat_lt n in (hn k hks).not_lt hk @[simp] lemma Inf_eq_zero {s : set ℕ} : Inf s = 0 ↔ 0 ∈ s ∨ s = ∅ := begin cases eq_empty_or_nonempty s, { subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf, mem_empty_iff_false, exists_false, dif_neg, not_false_iff] }, { simp only [h.ne_empty, or_false, nat.Inf_def, h, nat.find_eq_zero] } end @[simp] lemma Inf_empty : Inf ∅ = 0 := by { rw Inf_eq_zero, right, refl } @[simp] lemma infi_of_empty {ι : Sort*} [is_empty ι] (f : ι → ℕ) : infi f = 0 := by rw [infi_of_empty', Inf_empty] lemma Inf_mem {s : set ℕ} (h : s.nonempty) : Inf s ∈ s := by { rw [nat.Inf_def h], exact nat.find_spec h } lemma not_mem_of_lt_Inf {s : set ℕ} {m : ℕ} (hm : m < Inf s) : m ∉ s := begin cases eq_empty_or_nonempty s, { subst h, apply not_mem_empty }, { rw [nat.Inf_def h] at hm, exact nat.find_min h hm } end protected lemma Inf_le {s : set ℕ} {m : ℕ} (hm : m ∈ s) : Inf s ≤ m := by { rw [nat.Inf_def ⟨m, hm⟩], exact nat.find_min' ⟨m, hm⟩ hm } lemma nonempty_of_pos_Inf {s : set ℕ} (h : 0 < Inf s) : s.nonempty := begin by_contradiction contra, rw set.not_nonempty_iff_eq_empty at contra, have h' : Inf s ≠ 0, { exact ne_of_gt h, }, apply h', rw nat.Inf_eq_zero, right, assumption, end lemma nonempty_of_Inf_eq_succ {s : set ℕ} {k : ℕ} (h : Inf s = k + 1) : s.nonempty := nonempty_of_pos_Inf (h.symm ▸ (succ_pos k) : Inf s > 0) lemma eq_Ici_of_nonempty_of_upward_closed {s : set ℕ} (hs : s.nonempty) (hs' : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s) : s = Ici (Inf s) := ext (λ n, ⟨λ H, nat.Inf_le H, λ H, hs' (Inf s) n H (Inf_mem hs)⟩) lemma Inf_upward_closed_eq_succ_iff {s : set ℕ} (hs : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s) (k : ℕ) : Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s := begin split, { intro H, rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_Inf_eq_succ H) hs, H, mem_Ici, mem_Ici], exact ⟨le_rfl, k.not_succ_le_self⟩, }, { rintro ⟨H, H'⟩, rw [Inf_def (⟨_, H⟩ : s.nonempty), find_eq_iff], exact ⟨H, λ n hnk hns, H' $ hs n k (lt_succ_iff.mp hnk) hns⟩, }, end /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := linear_order.to_lattice noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_def, set.mem_empty_iff_false, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (linear_order.to_lattice : lattice ℕ), .. (infer_instance : linear_order ℕ) } lemma Sup_mem {s : set ℕ} (h₁ : s.nonempty) (h₂ : bdd_above s) : Sup s ∈ s := let ⟨k, hk⟩ := h₂ in h₁.cSup_mem ((finite_le_nat k).subset hk) lemma Inf_add {n : ℕ} {p : ℕ → Prop} (hn : n ≤ Inf {m | p m}) : Inf {m | p (m + n)} + n = Inf {m | p m} := begin obtain h | ⟨m, hm⟩ := {m | p (m + n)}.eq_empty_or_nonempty, { rw [h, nat.Inf_empty, zero_add], obtain hnp | hnp := hn.eq_or_lt, { exact hnp }, suffices hp : p (Inf {m | p m} - n + n), { exact (h.subset hp).elim }, rw tsub_add_cancel_of_le hn, exact Inf_mem (nonempty_of_pos_Inf $ n.zero_le.trans_lt hnp) }, { have hp : ∃ n, n ∈ {m | p m} := ⟨_, hm⟩, rw [nat.Inf_def ⟨m, hm⟩, nat.Inf_def hp], rw [nat.Inf_def hp] at hn, exact find_add hn } end lemma Inf_add' {n : ℕ} {p : ℕ → Prop} (h : 0 < Inf {m | p m}) : Inf {m | p m} + n = Inf {m | p (m - n)} := begin convert Inf_add _, { simp_rw add_tsub_cancel_right }, obtain ⟨m, hm⟩ := nonempty_of_pos_Inf h, refine le_cInf ⟨m + n, _⟩ (λ b hb, le_of_not_lt $ λ hbn, ne_of_mem_of_not_mem _ (not_mem_of_lt_Inf h) (tsub_eq_zero_of_le hbn.le)), { dsimp, rwa add_tsub_cancel_right }, { exact hb } end section variables {α : Type*} [complete_lattice α] lemma supr_lt_succ (u : ℕ → α) (n : ℕ) : (⨆ k < n + 1, u k) = (⨆ k < n, u k) ⊔ u n := by simp [nat.lt_succ_iff_lt_or_eq, supr_or, supr_sup_eq] lemma supr_lt_succ' (u : ℕ → α) (n : ℕ) : (⨆ k < n + 1, u k) = u 0 ⊔ (⨆ k < n, u (k + 1)) := by { rw ← sup_supr_nat_succ, simp } lemma infi_lt_succ (u : ℕ → α) (n : ℕ) : (⨅ k < n + 1, u k) = (⨅ k < n, u k) ⊓ u n := @supr_lt_succ αᵒᵈ _ _ _ lemma infi_lt_succ' (u : ℕ → α) (n : ℕ) : (⨅ k < n + 1, u k) = u 0 ⊓ (⨅ k < n, u (k + 1)) := @supr_lt_succ' αᵒᵈ _ _ _ end end nat namespace set variable {α : Type*} lemma bUnion_lt_succ (u : ℕ → set α) (n : ℕ) : (⋃ k < n + 1, u k) = (⋃ k < n, u k) ∪ u n := nat.supr_lt_succ u n lemma bUnion_lt_succ' (u : ℕ → set α) (n : ℕ) : (⋃ k < n + 1, u k) = u 0 ∪ (⋃ k < n, u (k + 1)) := nat.supr_lt_succ' u n lemma bInter_lt_succ (u : ℕ → set α) (n : ℕ) : (⋂ k < n + 1, u k) = (⋂ k < n, u k) ∩ u n := nat.infi_lt_succ u n lemma bInter_lt_succ' (u : ℕ → set α) (n : ℕ) : (⋂ k < n + 1, u k) = u 0 ∩ (⋂ k < n, u (k + 1)) := nat.infi_lt_succ' u n end set
b6199ea6cdd45358295a454e18c6cba2f34eec4c
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Elab/Tactic/Induction.lean
de0e0de6e4e14fb3bcb9ce9ac2253f5f3126d439
[ "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
19,227
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, Sebastian Ullrich -/ import Lean.Util.CollectFVars import Lean.Parser.Term import Lean.Meta.RecursorInfo import Lean.Meta.CollectMVars import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeVars import Lean.Elab.App import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Generalize namespace Lean.Elab.Tactic open Meta /- Given an `inductionAlt` of the form ``` nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser ``` -/ private def getAltName (alt : Syntax) : Name := -- alt[1] is of the form (("@"? ident) <|> "_") if alt[1].hasArgs then alt[1][1].getId.eraseMacroScopes else `_ private def altHasExplicitModifier (alt : Syntax) : Bool := alt[1].hasArgs && !alt[1][0].isNone private def getAltVarNames (alt : Syntax) : Array Name := alt[2].getArgs.map getNameOfIdent' private def getAltRHS (alt : Syntax) : Syntax := alt[4] private def getAltDArrow (alt : Syntax) : Syntax := alt[3] -- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic def isHoleRHS (rhs : Syntax) : Bool := rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole def evalAlt (mvarId : MVarId) (alt : Syntax) (remainingGoals : Array MVarId) : TacticM (Array MVarId) := let rhs := getAltRHS alt withCaseRef (getAltDArrow alt) rhs do if isHoleRHS rhs then let gs' ← withMVarContext mvarId $ withRef rhs do let mvarDecl ← getMVarDecl mvarId let val ← elabTermEnsuringType rhs mvarDecl.type assignExprMVar mvarId val let gs' ← getMVarsNoDelayed val tagUntaggedGoals mvarDecl.userName `induction gs'.toList pure gs' return remainingGoals ++ gs' else setGoals [mvarId] closeUsingOrAdmit (withTacticInfoContext alt (evalTactic rhs)) return remainingGoals /- Helper method for creating an user-defined eliminator/recursor application. -/ namespace ElimApp structure Context where elimInfo : ElimInfo targets : Array Expr -- targets provided by the user structure State where argPos : Nat := 0 -- current argument position targetPos : Nat := 0 -- current target at targetsStx f : Expr fType : Expr alts : Array (Name × MVarId) := #[] insts : Array MVarId := #[] abbrev M := ReaderT Context $ StateRefT State TermElabM private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! private def getFType : M Expr := do let fType ← whnfForall (← get).fType modify fun s => { s with fType := fType } pure fType structure Result where elimApp : Expr alts : Array (Name × MVarId) := #[] others : Array MVarId := #[] /-- Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for the eliminator. For example, the indices of builtin recursors are considered implicit targets. Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets from the explicit ones. -/ partial def mkElimApp (elimName : Name) (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do let rec loop : M Unit := do match (← getFType) with | Expr.forallE binderName _ _ c => let ctx ← read let argPos := (← get).argPos if ctx.elimInfo.motivePos == argPos then let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque addNewArg motive else if ctx.elimInfo.targetsPos.contains argPos then let s ← get let ctx ← read unless s.targetPos < ctx.targets.size do throwError "insufficient number of targets for '{elimName}'" let target := ctx.targets[s.targetPos] let expectedType ← getArgExpectedType let target ← Term.ensureHasType expectedType target modify fun s => { s with targetPos := s.targetPos + 1 } addNewArg target else match c.binderInfo with | BinderInfo.implicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.strictImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.instImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName) modify fun s => { s with insts := s.insts.push arg.mvarId! } addNewArg arg | _ => let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName) let x ← getBindingName modify fun s => { s with alts := s.alts.push (x, arg.mvarId!) } addNewArg arg loop | _ => pure () let f ← Term.mkConst elimName let fType ← inferType f let (_, s) ← loop.run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType } let mut others := #[] for mvarId in s.insts do try unless (← Term.synthesizeInstMVarCore mvarId) do setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId catch _ => setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId return { elimApp := (← instantiateMVars s.f), alts := s.alts, others := others } /- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign `motiveArg := fun targets => C[targets]` -/ def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do let type ← inferType (mkMVar mvarId) let motive ← mkLambdaFVars (targets.map mkFVar) type let motiverInferredType ← inferType motive let motiveType ← inferType (mkMVar motiveArg) unless (← isDefEqGuarded motiverInferredType motiveType) do throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}" assignExprMVar motiveArg motive private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do for altInfo in elimInfo.altsInfo do if altInfo.name == altName then return altInfo.numFields throwError "unknown alternative name '{altName}'" private def checkAltNames (alts : Array (Name × MVarId)) (altsSyntax : Array Syntax) : TacticM Unit := for altStx in altsSyntax do let altName := getAltName altStx if altName != `_ then unless alts.any fun (n, _) => n == altName do throwErrorAt altStx "invalid alternative name '{altName}'" def evalAlts (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (optPreTac : Syntax) (altsSyntax : Array Syntax) (initialInfo : Info) (numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do checkAltNames alts altsSyntax let hasAlts := altsSyntax.size > 0 if hasAlts then -- default to initial state outside of alts withInfoContext go initialInfo else go where go := do let hasAlts := altsSyntax.size > 0 let mut usedWildcard := false let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here let mut altsSyntax := altsSyntax for (altName, altMVarId) in alts do let numFields ← getAltNumFields elimInfo altName let mut isWildcard := false let altStx? ← match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with | some idx => let altStx := altsSyntax[idx] altsSyntax := altsSyntax.eraseIdx idx pure (some altStx) | none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with | some idx => isWildcard := true pure (some altsSyntax[idx]) | none => pure none match altStx? with | none => let mut (_, altMVarId) ← introN altMVarId numFields match (← Cases.unifyEqs numEqs altMVarId {}) with | none => pure () -- alternative is not reachable | some (altMVarId', _) => (_, altMVarId) ← introNP altMVarId' numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if !hasAlts then -- User did not provide alternatives using `|` subgoals := subgoals ++ altMVarIds.toArray else if altMVarIds.isEmpty then pure () else logError m!"alternative '{altName}' has not been provided" altMVarIds.forM fun mvarId => admitGoal mvarId | some altStx => (subgoals, usedWildcard) ← withRef altStx do let unusedAlt := if isWildcard then pure (#[], usedWildcard) else throwError "alternative '{altName}' is not needed" let altVarNames := getAltVarNames altStx if altVarNames.size > numFields then logError m!"too many variable names provided at alternative '{altName}', #{altVarNames.size} provided, but #{numFields} expected" let mut (_, altMVarId) ← introN altMVarId numFields altVarNames.toList (useNamesForExplicitOnly := !altHasExplicitModifier altStx) match (← Cases.unifyEqs numEqs altMVarId {}) with | none => unusedAlt | some (altMVarId', _) => (_, altMVarId) ← introNP altMVarId' numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if altMVarIds.isEmpty then unusedAlt else let mut subgoals := subgoals for altMVarId' in altMVarIds do subgoals ← evalAlt altMVarId' altStx subgoals pure (subgoals, usedWildcard || isWildcard) if usedWildcard then altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_ unless altsSyntax.isEmpty do logErrorAt altsSyntax[0] "unused alternative" setGoals subgoals.toList applyPreTac (mvarId : MVarId) : TacticM (List MVarId) := if optPreTac.isNone then return [mvarId] else evalTacticAt optPreTac[0] mvarId end ElimApp /- Recall that ``` generalizingVars := optional (" generalizing " >> many1 ident) «induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts ``` `stx` is syntax for `induction`. -/ private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) := withRef stx do let generalizingStx := stx[3] if generalizingStx.isNone then pure #[] else trace[Elab.induction] "{generalizingStx}" let vars := generalizingStx[1].getArgs getFVarIds vars -- process `generalizingVars` subterm of induction Syntax `stx`. private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) := withMVarContext mvarId do let userFVarIds ← getUserGeneralizingFVarIds stx let forbidden ← mkGeneralizationForbiddenSet targets let mut s ← getFVarSetToGeneralize targets forbidden for userFVarId in userFVarIds do if forbidden.contains userFVarId then throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}" if s.contains userFVarId then throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically" s := s.insert userFVarId let fvarIds ← sortFVarIds s.toArray let (fvarIds, mvarId') ← Meta.revert mvarId fvarIds return (fvarIds.size, mvarId') -- syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax := inductionAlts[2].getArgs private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax := if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0] private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax := if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1] /- We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names. The idea is to make sure users do not write unstructured tactics. -/ private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit := unless optInductionAlts.isNone do let mut found := false for alt in getAltsOfInductionAlts optInductionAlts[0] do let n := getAltName alt if n == `_ then unless (getAltVarNames alt).isEmpty do throwErrorAt alt "wildcard alternative must not specify variable names" if found then throwErrorAt alt "more than one wildcard alternative '| _ => ...' used" found := true def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal := liftMetaMAtMain fun mvarId => do let majorType ← inferType major let majorType ← whnf majorType matchConstInduct majorType.getAppFn (fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}") (fun val _ => pure val) -- `optElimId` is of the form `("using" ident)?` private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM (Name × ElimInfo) := do if optElimId.isNone then unless targets.size == 1 do throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>')" let indVal ← getInductiveValFromMajor targets[0] if induction && indVal.all.length != 1 then throwError "'induction' tactic does not support mutually inductive types, the eliminator '{mkRecName indVal.name}' has multiple motives" let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name pure (elimName, ← getElimInfo elimName) else let elimId := optElimId[1] let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId pure (elimName, ← withRef elimId do getElimInfo elimName) private def generalizeTargets (exprs : Array Expr) : TacticM (Array Expr) := do if exprs.all (·.isFVar) then return exprs else liftMetaTacticAux fun mvarId => do let (fvarIds, mvarId) ← generalize mvarId (exprs.map fun expr => { expr }) return (fvarIds.map mkFVar, [mvarId]) @[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focus do let targets ← withMainContext <| stx[1].getSepArgs.mapM (elabTerm . none) let targets ← generalizeTargets targets let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := true) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets checkTargets targets let targetFVarIds := targets.map (·.fvarId!) let (n, mvarId) ← generalizeVars mvarId stx targets withMVarContext mvarId do let result ← withRef stx[1] do -- use target position as reference ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let motiveType ← inferType elimArgs[elimInfo.motivePos] ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetFVarIds let optInductionAlts := stx[4] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds) appendGoals result.others.toList where checkTargets (targets : Array Expr) : MetaM Unit := do let mut foundFVars : FVarIdSet := {} for target in targets do unless target.isFVar do throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}" if foundFVars.contains target.fvarId! then throwError "target (or one of its indices) occurs more than once{indentExpr target}" def elabCasesTargets (targets : Array Syntax) : TacticM (Array Expr) := withMainContext do let args ← targets.mapM fun target => do let hName? := if target[0].isNone then none else some target[0][0].getId let expr ← elabTerm target[1] none return { expr, hName? : GeneralizeArg } if args.all fun arg => arg.expr.isFVar && arg.hName?.isNone then return args.map (·.expr) else liftMetaTacticAux fun mvarId => do let (fvarIds, mvarId) ← generalize mvarId args return (fvarIds[:targets.size].toArray.map mkFVar, [mvarId]) builtin_initialize registerTraceClass `Elab.cases @[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focus do -- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts let targets ← elabCasesTargets stx[1].getSepArgs let optInductionAlts := stx[3] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts let targetRef := stx[1] let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := false) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets let result ← withRef targetRef <| ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i] let motiveType ← inferType elimArgs[elimInfo.motivePos] let mvarId ← generalizeTargetsEq mvarId motiveType targets let (targetsNew, mvarId) ← introN mvarId targets.size withMVarContext mvarId do ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetsNew assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew) end Lean.Elab.Tactic
004707a91dbd1483f34a937ac680bad6183f483c
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/OrDeMorgran.lean
f1a696079f921d6c3f100f250512cb027eb5e3df
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
10,919
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section OrDeMorgran structure OrDeMorgran (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) (prim : (A → A)) (orDeMorgan_plus_times_prim : (∀ {x y z : A} , (prim (plus x y)) = (times (prim x) (prim y)))) open OrDeMorgran structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) (primS : (AS → AS)) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (primP : ((Prod A A) → (Prod A A))) (orDeMorgan_plus_times_primP : (∀ {xP yP zP : (Prod A A)} , (primP (plusP xP yP)) = (timesP (primP xP) (primP yP)))) structure Hom {A1 : Type} {A2 : Type} (Or1 : (OrDeMorgran A1)) (Or2 : (OrDeMorgran A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Or1) x1 x2)) = ((times Or2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Or1) x1 x2)) = ((plus Or2) (hom x1) (hom x2)))) (pres_prim : (∀ {x1 : A1} , (hom ((prim Or1) x1)) = ((prim Or2) (hom x1)))) structure RelInterp {A1 : Type} {A2 : Type} (Or1 : (OrDeMorgran A1)) (Or2 : (OrDeMorgran A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Or1) x1 x2) ((times Or2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Or1) x1 x2) ((plus Or2) y1 y2)))))) (interp_prim : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((prim Or1) x1) ((prim Or2) y1))))) inductive OrDeMorgranTerm : Type | timesL : (OrDeMorgranTerm → (OrDeMorgranTerm → OrDeMorgranTerm)) | plusL : (OrDeMorgranTerm → (OrDeMorgranTerm → OrDeMorgranTerm)) | primL : (OrDeMorgranTerm → OrDeMorgranTerm) open OrDeMorgranTerm inductive ClOrDeMorgranTerm (A : Type) : Type | sing : (A → ClOrDeMorgranTerm) | timesCl : (ClOrDeMorgranTerm → (ClOrDeMorgranTerm → ClOrDeMorgranTerm)) | plusCl : (ClOrDeMorgranTerm → (ClOrDeMorgranTerm → ClOrDeMorgranTerm)) | primCl : (ClOrDeMorgranTerm → ClOrDeMorgranTerm) open ClOrDeMorgranTerm inductive OpOrDeMorgranTerm (n : ℕ) : Type | v : ((fin n) → OpOrDeMorgranTerm) | timesOL : (OpOrDeMorgranTerm → (OpOrDeMorgranTerm → OpOrDeMorgranTerm)) | plusOL : (OpOrDeMorgranTerm → (OpOrDeMorgranTerm → OpOrDeMorgranTerm)) | primOL : (OpOrDeMorgranTerm → OpOrDeMorgranTerm) open OpOrDeMorgranTerm inductive OpOrDeMorgranTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpOrDeMorgranTerm2) | sing2 : (A → OpOrDeMorgranTerm2) | timesOL2 : (OpOrDeMorgranTerm2 → (OpOrDeMorgranTerm2 → OpOrDeMorgranTerm2)) | plusOL2 : (OpOrDeMorgranTerm2 → (OpOrDeMorgranTerm2 → OpOrDeMorgranTerm2)) | primOL2 : (OpOrDeMorgranTerm2 → OpOrDeMorgranTerm2) open OpOrDeMorgranTerm2 def simplifyCl {A : Type} : ((ClOrDeMorgranTerm A) → (ClOrDeMorgranTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (primCl x1) := (primCl (simplifyCl x1)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpOrDeMorgranTerm n) → (OpOrDeMorgranTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (primOL x1) := (primOL (simplifyOpB x1)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpOrDeMorgranTerm2 n A) → (OpOrDeMorgranTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (primOL2 x1) := (primOL2 (simplifyOp x1)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((OrDeMorgran A) → (OrDeMorgranTerm → A)) | Or (timesL x1 x2) := ((times Or) (evalB Or x1) (evalB Or x2)) | Or (plusL x1 x2) := ((plus Or) (evalB Or x1) (evalB Or x2)) | Or (primL x1) := ((prim Or) (evalB Or x1)) def evalCl {A : Type} : ((OrDeMorgran A) → ((ClOrDeMorgranTerm A) → A)) | Or (sing x1) := x1 | Or (timesCl x1 x2) := ((times Or) (evalCl Or x1) (evalCl Or x2)) | Or (plusCl x1 x2) := ((plus Or) (evalCl Or x1) (evalCl Or x2)) | Or (primCl x1) := ((prim Or) (evalCl Or x1)) def evalOpB {A : Type} {n : ℕ} : ((OrDeMorgran A) → ((vector A n) → ((OpOrDeMorgranTerm n) → A))) | Or vars (v x1) := (nth vars x1) | Or vars (timesOL x1 x2) := ((times Or) (evalOpB Or vars x1) (evalOpB Or vars x2)) | Or vars (plusOL x1 x2) := ((plus Or) (evalOpB Or vars x1) (evalOpB Or vars x2)) | Or vars (primOL x1) := ((prim Or) (evalOpB Or vars x1)) def evalOp {A : Type} {n : ℕ} : ((OrDeMorgran A) → ((vector A n) → ((OpOrDeMorgranTerm2 n A) → A))) | Or vars (v2 x1) := (nth vars x1) | Or vars (sing2 x1) := x1 | Or vars (timesOL2 x1 x2) := ((times Or) (evalOp Or vars x1) (evalOp Or vars x2)) | Or vars (plusOL2 x1 x2) := ((plus Or) (evalOp Or vars x1) (evalOp Or vars x2)) | Or vars (primOL2 x1) := ((prim Or) (evalOp Or vars x1)) def inductionB {P : (OrDeMorgranTerm → Type)} : ((∀ (x1 x2 : OrDeMorgranTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : OrDeMorgranTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((∀ (x1 : OrDeMorgranTerm) , ((P x1) → (P (primL x1)))) → (∀ (x : OrDeMorgranTerm) , (P x))))) | ptimesl pplusl ppriml (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl ppriml x1) (inductionB ptimesl pplusl ppriml x2)) | ptimesl pplusl ppriml (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl ppriml x1) (inductionB ptimesl pplusl ppriml x2)) | ptimesl pplusl ppriml (primL x1) := (ppriml _ (inductionB ptimesl pplusl ppriml x1)) def inductionCl {A : Type} {P : ((ClOrDeMorgranTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClOrDeMorgranTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClOrDeMorgranTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((∀ (x1 : (ClOrDeMorgranTerm A)) , ((P x1) → (P (primCl x1)))) → (∀ (x : (ClOrDeMorgranTerm A)) , (P x)))))) | psing ptimescl ppluscl pprimcl (sing x1) := (psing x1) | psing ptimescl ppluscl pprimcl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl pprimcl x1) (inductionCl psing ptimescl ppluscl pprimcl x2)) | psing ptimescl ppluscl pprimcl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl pprimcl x1) (inductionCl psing ptimescl ppluscl pprimcl x2)) | psing ptimescl ppluscl pprimcl (primCl x1) := (pprimcl _ (inductionCl psing ptimescl ppluscl pprimcl x1)) def inductionOpB {n : ℕ} {P : ((OpOrDeMorgranTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpOrDeMorgranTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpOrDeMorgranTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((∀ (x1 : (OpOrDeMorgranTerm n)) , ((P x1) → (P (primOL x1)))) → (∀ (x : (OpOrDeMorgranTerm n)) , (P x)))))) | pv ptimesol pplusol pprimol (v x1) := (pv x1) | pv ptimesol pplusol pprimol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol pprimol x1) (inductionOpB pv ptimesol pplusol pprimol x2)) | pv ptimesol pplusol pprimol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol pprimol x1) (inductionOpB pv ptimesol pplusol pprimol x2)) | pv ptimesol pplusol pprimol (primOL x1) := (pprimol _ (inductionOpB pv ptimesol pplusol pprimol x1)) def inductionOp {n : ℕ} {A : Type} {P : ((OpOrDeMorgranTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpOrDeMorgranTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpOrDeMorgranTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((∀ (x1 : (OpOrDeMorgranTerm2 n A)) , ((P x1) → (P (primOL2 x1)))) → (∀ (x : (OpOrDeMorgranTerm2 n A)) , (P x))))))) | pv2 psing2 ptimesol2 pplusol2 pprimol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 pprimol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 pprimol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x2)) | pv2 psing2 ptimesol2 pplusol2 pprimol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x2)) | pv2 psing2 ptimesol2 pplusol2 pprimol2 (primOL2 x1) := (pprimol2 _ (inductionOp pv2 psing2 ptimesol2 pplusol2 pprimol2 x1)) def stageB : (OrDeMorgranTerm → (Staged OrDeMorgranTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) | (primL x1) := (stage1 primL (codeLift1 primL) (stageB x1)) def stageCl {A : Type} : ((ClOrDeMorgranTerm A) → (Staged (ClOrDeMorgranTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) | (primCl x1) := (stage1 primCl (codeLift1 primCl) (stageCl x1)) def stageOpB {n : ℕ} : ((OpOrDeMorgranTerm n) → (Staged (OpOrDeMorgranTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) | (primOL x1) := (stage1 primOL (codeLift1 primOL) (stageOpB x1)) def stageOp {n : ℕ} {A : Type} : ((OpOrDeMorgranTerm2 n A) → (Staged (OpOrDeMorgranTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) | (primOL2 x1) := (stage1 primOL2 (codeLift1 primOL2) (stageOp x1)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) (primT : ((Repr A) → (Repr A))) end OrDeMorgran
a56821d21ba9eb9d02d53a83420227cb6f7be6aa
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/arity.hlean
e611a6eb4433f8ab9415ab098e2a13463f957757
[ "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
11,068
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about functions with multiple arguments -/ variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} {F : Πa b c d, E a b c d → Type} {G : Πa b c d e, F a b c d e → Type} {H : Πa b c d e f, G a b c d e f → Type} variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} {e : E a b c d} {e' : E a' b' c' d'} {ff : F a b c d e} {f' : F a' b' c' d' e'} {g : G a b c d e ff} {g' : G a' b' c' d' e' f'} {h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'} namespace eq /- Naming convention: The theorem which states how to construct an path between two function applications is api₀i₁...iₙ. Here i₀, ... iₙ are digits, n is the arity of the function(s), and iⱼ specifies the dimension of the path between the jᵗʰ argument (i₀ specifies the dimension of the path between the functions). A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal The functions are non-dependent, except when the theorem name contains trailing zeroes (where the function is dependent only in the arguments where it doesn't result in any transports in the theorem statement). For the fully-dependent versions (except that the conclusion doesn't contain a transport) we write apdi₀i₁...iₙ. For versions where only some arguments depend on some other arguments, or for versions with transport in the conclusion (like apdt), we don't have a consistent naming scheme (yet). We don't prove each theorem systematically, but prove only the ones which we actually need. -/ definition homotopy2 [reducible] (f g : Πa b, C a b) : Type := Πa b, f a b = g a b definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type := Πa b c, f a b c = g a b c definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type := Πa b c d, f a b c d = g a b c d infix ` ~2 `:50 := homotopy2 infix ` ~3 `:50 := homotopy3 definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w') : f u v w = f u' v' w' := by cases Hu; congruence; repeat assumption definition ap01111 (f : U → V → W → X → Y) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') : f u v w x = f u' v' w' x' := by cases Hu; congruence; repeat assumption definition ap011111 (f : U → V → W → X → Y → Z) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') : f u v w x y = f u' v' w' x' y' := by cases Hu; congruence; repeat assumption definition ap0111111 (f : U → V → W → X → Y → Z → A) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z') : f u v w x y z = f u' v' w' x' y' z' := by cases Hu; congruence; repeat assumption definition ap010 (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' := by intros; cases Hx; reflexivity definition ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' := by intros; cases Hx; reflexivity definition ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' := by intros; cases Hx; reflexivity definition apd011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b') : f a b = f a' b' := by cases Ha; cases Hb; reflexivity definition apd0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') : f a b c = f a' b' c' := by cases Ha; cases Hb; cases Hc; reflexivity definition apd01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := by cases Ha; cases Hb; cases Hc; cases Hd; reflexivity definition apd011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') (He : cast (apd01111 E Ha Hb Hc Hd) e = e') : f a b c d e = f a' b' c' d' e' := by cases Ha; cases Hb; cases Hc; cases Hd; cases He; reflexivity definition apd0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') : f a b c d e ff = f a' b' c' d' e' f' := begin cases Ha, cases Hb, cases Hc, cases Hd, cases He, cases Hf, reflexivity end -- definition apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') -- : f a b c d e ff g = f a' b' c' d' e' f' g' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; reflexivity -- definition apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h') -- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; cases Hh; reflexivity definition apd100 [unfold 6] {f g : Πa b, C a b} (p : f = g) : f ~2 g := λa b, apd10 (apd10 p a) b definition apd1000 [unfold 7] {f g : Πa b c, D a b c} (p : f = g) : f ~3 g := λa b c, apd100 (apd10 p a) b c /- some properties of these variants of ap -/ -- we only prove what we currently need definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') : ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a := eq.rec_on q (eq.rec_on p idp) definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') : ap010 f (ap g p) a = ap010 (λy, f (g y)) p a := eq.rec_on p idp /- the following theorems are function extentionality for functions with multiple arguments -/ definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy (H a)) definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy2 (H a)) definition eq_of_homotopy2_id (f : Πa b, C a b) : eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f := begin transitivity eq_of_homotopy (λ a, idpath (f a)), {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy_idp}, apply eq_of_homotopy_idp end definition eq_of_homotopy3_id (f : Πa b c, D a b c) : eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f := begin transitivity _, {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy2_id}, apply eq_of_homotopy_idp end definition eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g) : eq_of_homotopy2 (λa b, (H a b)⁻¹) = (eq_of_homotopy2 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g) : eq_of_homotopy3 (λa b c, (H a b c)⁻¹) = (eq_of_homotopy3 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h) : eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_con)) ⬝ !eq_of_homotopy_con definition eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h) : eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_con)) ⬝ !eq_of_homotopy_con end eq open eq equiv is_equiv namespace funext definition is_equiv_apd100 [instance] (f g : Πa b, C a b) : is_equiv (@apd100 A B C f g) := adjointify _ eq_of_homotopy2 begin intro H, esimp [apd100, eq_of_homotopy2], apply eq_of_homotopy, intro a, apply concat, apply (ap (λx, apd10 (x a))), apply (right_inv apd10), apply (right_inv apd10) end begin intro p, cases p, apply eq_of_homotopy2_id end definition is_equiv_apd1000 [instance] (f g : Πa b c, D a b c) : is_equiv (@apd1000 A B C D f g) := adjointify _ eq_of_homotopy3 begin intro H, esimp, apply eq_of_homotopy, intro a, transitivity apd100 (eq_of_homotopy2 (H a)), {apply ap (λx, apd100 (x a)), apply right_inv apd10}, apply right_inv apd100 end begin intro p, cases p, apply eq_of_homotopy3_id end end funext attribute funext.is_equiv_apd100 funext.is_equiv_apd1000 [constructor] namespace eq open funext local attribute funext.is_equiv_apd100 [instance] protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type} (p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p := right_inv apd100 p ▸ H (eq_of_homotopy2 p) protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type} (p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p := right_inv apd1000 p ▸ H (eq_of_homotopy3 p) definition eq_equiv_homotopy2 [constructor] (f g : Πa b, C a b) : (f = g) ≃ (f ~2 g) := equiv.mk apd100 _ definition eq_equiv_homotopy3 [constructor] (f g : Πa b c, D a b c) : (f = g) ≃ (f ~3 g) := equiv.mk apd1000 _ definition apd10_ap (f : X → Πa, B a) (p : x = x') : apd10 (ap f p) = ap010 f p := eq.rec_on p idp definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x') : eq_of_homotopy (ap010 f p) = ap f p := inv_eq_of_eq !apd10_ap⁻¹ definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q) : ap f p = ap f q := calc ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010 ... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H ... = ap f q : eq_of_homotopy_ap010 end eq
290a69a364d1397e9d4e8b7eec0172e13dabe235
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Meta/Tactic/Subst.lean
715843dddc9a0238bd28504d6aeaf57882370cd8
[ "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
6,341
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.AppBuilder import Lean.Meta.MatchUtil 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 def substCore (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) : MetaM (FVarSubst × MVarId) := withMVarContext mvarId do let tag ← getMVarTag mvarId checkNotAssigned mvarId `subst let hFVarIdOriginal := hFVarId let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => throwTacticEx `subst mvarId "argument must be an equality proof" | some (α, lhs, rhs) => do let a := if symm then rhs else lhs let b := if symm then lhs else rhs let a ← whnf a match a with | Expr.fvar aFVarId _ => do let aFVarIdOriginal := aFVarId trace[Meta.Tactic.subst]! "substituting {a} (id: {aFVarId} with {b}" let mctx ← getMCtx if mctx.exprDependsOn b aFVarId then throwTacticEx `subst mvarId m!"'{a}' occurs at{indentExpr b}" let aLocalDecl ← getLocalDecl aFVarId let (vars, mvarId) ← revert mvarId #[aFVarId, hFVarId] true let (twoVars, mvarId) ← introNP mvarId 2 trace[Meta.Tactic.subst]! "reverted variables {vars}" let aFVarId := twoVars[0] let a := mkFVar aFVarId let hFVarId := twoVars[1] let h := mkFVar hFVarId withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId let type := mvarDecl.type let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | none => unreachable! | some (α, lhs, rhs) => do let b := if symm then lhs else rhs let mctx ← getMCtx let depElim := mctx.exprDependsOn mvarDecl.type hFVarId let cont (motive : Expr) (newType : Expr) : MetaM (FVarSubst × MVarId) := do let major ← if symm then pure h else mkEqSymm h let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let minor := newMVar let newVal ← if depElim then mkEqRec motive minor major else mkEqNDRec motive minor major assignExprMVar mvarId newVal let mvarId := newMVar.mvarId! let mvarId ← if clearH then let mvarId ← clear mvarId hFVarId clear mvarId aFVarId else pure mvarId let (newFVars, mvarId) ← introNP mvarId (vars.size - 2) let fvarSubst ← newFVars.size.foldM (init := fvarSubst) fun i (fvarSubst : FVarSubst) => let var := vars[i+2] let newFVar := newFVars[i] pure $ fvarSubst.insert var (mkFVar newFVar) let fvarSubst := fvarSubst.insert aFVarIdOriginal (if clearH then b else mkFVar aFVarId) let fvarSubst := fvarSubst.insert hFVarIdOriginal (mkFVar hFVarId) pure (fvarSubst, mvarId) if depElim then do let newType := type.replaceFVar a b let reflB ← mkEqRefl b let newType := newType.replaceFVar h reflB if symm then let motive ← mkLambdaFVars #[a, h] type cont motive newType else /- `type` depends on (h : a = b). So, we use the following trick to avoid a type incorrect motive. 1- Create a new local (hAux : b = a) 2- Create newType := type [hAux.symm / h] `newType` is type correct because `h` and `hAux.symm` are definitionally equal by proof irrelevance. 3- Create motive by abstracting `a` and `hAux` in `newType`. -/ let hAuxType ← mkEq b a let motive ← withLocalDeclD `_h hAuxType fun hAux => do let hAuxSymm ← mkEqSymm hAux /- replace h in type with hAuxSymm -/ let newType := type.replaceFVar h hAuxSymm mkLambdaFVars #[a, hAux] newType cont motive newType else let motive ← mkLambdaFVars #[a] type let newType := type.replaceFVar a b cont motive newType | _ => let eqMsg := if symm then "(t = x)" else "(x = t)" throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form {eqMsg}{indentExpr hLocalDecl.type}\nafter WHNF, variable expected, but obtained{indentExpr a}" def subst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := withMVarContext mvarId do let hLocalDecl ← getLocalDecl hFVarId match (← matchEq? hLocalDecl.type) with | some (α, lhs, rhs) => let rhs ← whnf rhs if rhs.isFVar then (·.2) <$> substCore mvarId hFVarId true else do let lhs ← whnf lhs if lhs.isFVar then (·.2) <$> substCore mvarId hFVarId else do throwTacticEx `subst mvarId m!"invalid equality proof, it is not of the form (x = t) or (t = x){indentExpr hLocalDecl.type}" | none => let mctx ← getMCtx let lctx ← getLCtx let some (fvarId, symm) ← lctx.findDeclM? fun localDecl => do if localDecl.isAuxDecl then pure none else match (← matchEq? localDecl.type) with | some (α, lhs, rhs) => if rhs.isFVar && rhs.fvarId! == hFVarId && !mctx.exprDependsOn lhs hFVarId then pure $ some (localDecl.fvarId, true) else if lhs.isFVar && lhs.fvarId! == hFVarId && !mctx.exprDependsOn rhs hFVarId then pure $ some (localDecl.fvarId, false) else pure none | _ => pure none | throwTacticEx `subst mvarId m!"did not find equation for eliminating '{mkFVar hFVarId}'" (·.2) <$> substCore mvarId fvarId symm builtin_initialize registerTraceClass `Meta.Tactic.subst end Meta end Lean
29087fb8760b87f76d6925ffec39e5d54a661303
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/local_notation_meta_bug.lean
813e98d1453cfd865e511ce3b9ed5d6b041af2c9
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
282
lean
local infix (name := plus1) ` + ` := nat.add @[class] local infix (name := plus2) ` + ` := nat.add noncomputable local infix (name := plus3) ` + ` := nat.add @[class] noncomputable local infix (name := plus4) ` + ` := nat.add /-- foo -/ local infix (name := plus5) ` + ` := nat.add
45c87b17e5540d3c1f96f0b716688a8b03a86c2e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/finset/nat_antidiagonal.lean
9dab27b0e5a29de30cc6a281283cfd143291241e
[ "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
3,609
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.finset.basic import data.multiset.nat_antidiagonal /-! # Antidiagonals in ℕ × ℕ as finsets This file defines the antidiagonals of ℕ × ℕ as finsets: the `n`-th antidiagonal is the finset of pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more generally for sums going from `0` to `n`. ## Notes This refines files `data.list.nat_antidiagonal` and `data.multiset.nat_antidiagonal`. -/ namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i, j)` such that `i + j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := ⟨multiset.nat.antidiagonal n, multiset.nat.nodup_antidiagonal n⟩ /-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_def, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n + 1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simp [antidiagonal] /-- The antidiagonal of `0` is the list `[(0, 0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl lemma antidiagonal_succ {n : ℕ} : antidiagonal (n + 1) = insert (0, n + 1) ((antidiagonal n).map (function.embedding.prod_map ⟨nat.succ, nat.succ_injective⟩ (function.embedding.refl _))) := begin apply eq_of_veq, rw [insert_val_of_not_mem, map_val], {apply multiset.nat.antidiagonal_succ}, { intro con, rcases mem_map.1 con with ⟨⟨a,b⟩, ⟨h1, h2⟩⟩, simp only [prod.mk.inj_iff, function.embedding.coe_prod_map, prod.map_mk] at h2, apply nat.succ_ne_zero a h2.1, } end lemma map_swap_antidiagonal {n : ℕ} : (antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = antidiagonal n := begin ext, simp only [exists_prop, mem_map, mem_antidiagonal, prod.exists], rw add_comm, split, { rintro ⟨b, c, ⟨rfl, rfl⟩⟩, simp }, { rintro rfl, use [a.snd, a.fst], simp } end /-- A point in the antidiagonal is determined by its first co-ordinate. -/ lemma antidiagonal_congr {n : ℕ} {p q : ℕ × ℕ} (hp : p ∈ antidiagonal n) (hq : q ∈ antidiagonal n) : p = q ↔ p.fst = q.fst := begin refine ⟨congr_arg prod.fst, (λ h, prod.ext h ((add_right_inj q.fst).mp _))⟩, rw mem_antidiagonal at hp hq, rw [hq, ← h, hp], end lemma antidiagonal.fst_le {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.1 ≤ n := begin rw le_iff_exists_add, use kl.2, rwa [mem_antidiagonal, eq_comm] at hlk end lemma antidiagonal.snd_le {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) : kl.2 ≤ n := begin rw le_iff_exists_add, use kl.1, rwa [mem_antidiagonal, eq_comm, add_comm] at hlk end section equiv_prod /-- The disjoint union of antidiagonals `Σ (n : ℕ), antidiagonal n` is equivalent to the product `ℕ × ℕ`. This is such an equivalence, obtained by mapping `(n, (k, l))` to `(k, l)`. -/ @[simps] def sigma_antidiagonal_equiv_prod : (Σ (n : ℕ), antidiagonal n) ≃ ℕ × ℕ := { to_fun := λ x, x.2, inv_fun := λ x, ⟨x.1 + x.2, x, mem_antidiagonal.mpr rfl⟩, left_inv := begin rintros ⟨n, ⟨k, l⟩, h⟩, rw mem_antidiagonal at h, exact sigma.subtype_ext h rfl, end, right_inv := λ x, rfl } end equiv_prod end nat end finset
0018cea6d4d0f61d5fac8639147a12d04cb60417
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Module/epi_mono.lean
fb24e19c6092d406102b7aa1f362e393c1fde2e4
[ "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
2,400
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 linear_algebra.quotient import algebra.category.Module.basic /-! # Monomorphisms in `Module R` This file shows that an `R`-linear map is a monomorphism in the category of `R`-modules if and only if it is injective, and similarly an epimorphism if and only if it is surjective. -/ universes v u open category_theory open Module open_locale Module namespace Module variables {R : Type u} [ring R] {X Y : Module.{v} R} (f : X ⟶ Y) variables {M : Type v} [add_comm_group M] [module R M] lemma ker_eq_bot_of_mono [mono f] : f.ker = ⊥ := linear_map.ker_eq_bot_of_cancel $ λ u v, (@cancel_mono _ _ _ _ _ f _ ↟u ↟v).1 lemma range_eq_top_of_epi [epi f] : f.range = ⊤ := linear_map.range_eq_top_of_cancel $ λ u v, (@cancel_epi _ _ _ _ _ f _ ↟u ↟v).1 lemma mono_iff_ker_eq_bot : mono f ↔ f.ker = ⊥ := ⟨λ hf, by exactI ker_eq_bot_of_mono _, λ hf, concrete_category.mono_of_injective _ $ linear_map.ker_eq_bot.1 hf⟩ lemma mono_iff_injective : mono f ↔ function.injective f := by rw [mono_iff_ker_eq_bot, linear_map.ker_eq_bot] lemma epi_iff_range_eq_top : epi f ↔ f.range = ⊤ := ⟨λ hf, by exactI range_eq_top_of_epi _, λ hf, concrete_category.epi_of_surjective _ $ linear_map.range_eq_top.1 hf⟩ lemma epi_iff_surjective : epi f ↔ function.surjective f := by rw [epi_iff_range_eq_top, linear_map.range_eq_top] /-- If the zero morphism is an epi then the codomain is trivial. -/ def unique_of_epi_zero (X) [h : epi (0 : X ⟶ of R M)] : unique M := unique_of_surjective_zero X ((Module.epi_iff_surjective _).mp h) instance mono_as_hom'_subtype (U : submodule R X) : mono ↾U.subtype := (mono_iff_ker_eq_bot _).mpr (submodule.ker_subtype U) instance epi_as_hom''_mkq (U : submodule R X) : epi ↿U.mkq := (epi_iff_range_eq_top _).mpr $ submodule.range_mkq _ instance forget_preserves_epimorphisms : (forget (Module.{v} R)).preserves_epimorphisms := { preserves := λ X Y f hf, by rwa [forget_map_eq_coe, category_theory.epi_iff_surjective, ← epi_iff_surjective] } instance forget_preserves_monomorphisms : (forget (Module.{v} R)).preserves_monomorphisms := { preserves := λ X Y f hf, by rwa [forget_map_eq_coe, category_theory.mono_iff_injective, ← mono_iff_injective] } end Module
f2aa6dbdbcbd70d2c2bb0bd74dd38addd62a3e36
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/IR/GlobalVariableRef.lean
21c3939f59ae607fdbdf8c94e75ad3f83b9e9c07
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,202
lean
import Papyrus.Context import Papyrus.IR.GlobalRefs import Papyrus.IR.AddressSpace import Papyrus.IR.ConstantRef import Papyrus.IR.ConstantRefs import Papyrus.IR.TypeRef namespace Papyrus /-- A reference to an external LLVM [GlobalVariable](https://llvm.org/doxygen/classllvm_1_1GlobalVariable.html). -/ structure GlobalVariableRef extends GlobalObjectRef where is_global_variable : toValueRef.valueKind = ValueKind.globalVariable instance : Coe GlobalVariableRef GlobalObjectRef := ⟨(·.toGlobalObjectRef)⟩ namespace GlobalVariableRef /-- Cast a general `ValueRef` to a `GlobalVariableRef` given proof it is one. -/ def cast (val : ValueRef) (h : val.valueKind = ValueKind.globalVariable) : GlobalVariableRef := {toValueRef := val, is_global_variable := h} /-- Create a new unlinked global variable. -/ @[extern "papyrus_global_variable_new"] constant new (type : @& TypeRef) (isConstant := false) (linkage := Linkage.external) (name : @& String := "") (tlm := ThreadLocalMode.notLocal) (addrSpace := AddressSpace.default) (isExternallyInitialized := false) : IO GlobalVariableRef /-- Create a new unlinked global variable with an initializer. -/ @[extern "papyrus_global_variable_new_with_init"] constant newWithInit (type : @& TypeRef) (isConstant := false) (linkage := Linkage.external) (init : @& ConstantRef) (name : @& String := "") (tlm := ThreadLocalMode.notLocal) (addrSpace := AddressSpace.default) (isExternallyInitialized := false) : IO GlobalVariableRef /-- Create a new unlinked global constant with the given value. -/ def ofConstant (init : ConstantRef) (isConstant := true) (linkage := Linkage.external) (name := "") (tlm := ThreadLocalMode.notLocal) (addrSpace := AddressSpace.default) : IO GlobalVariableRef := do newWithInit (← init.getType) true linkage init name tlm addrSpace false /-- Create a new unlinked global string constant with the given value. If `withNull` is true, the string will be null terminated. Such constants have private linkage, single byte alignment, are not thread local, and their addresses are insignificant. -/ def ofString (value : String) (addrSpace := AddressSpace.default) (withNull := true) (name := "") : LlvmM GlobalVariableRef := do let var ← ofConstant (← ConstantDataArrayRef.ofString value withNull) true Linkage.private name ThreadLocalMode.notLocal addrSpace var.setAddressSignificance AddressSignificance.none var.setRawAlignment 1 var /-- Get whether the this global variable is constant (i.e., its value does not change at runtime). -/ @[extern "papyrus_global_variable_is_constant"] constant isConstant (self : @& GlobalValueRef) : IO Bool /-- Set whether the this global variable is constant (i.e., its value does not change at runtime). -/ @[extern "papyrus_global_variable_set_constant"] constant setConstant (isConstant : Bool) (self : @& GlobalVariableRef) : IO PUnit /-- Get whether the this global variable has an initializer. -/ @[extern "papyrus_global_variable_has_initializer"] constant hasInitializer (self : @& GlobalVariableRef) : IO Bool /-- Get the initializer of this global variable. Only call this if it is know to have one (i.e., `hasInitializer` returned true). -/ @[extern "papyrus_global_variable_get_initializer"] constant getInitializer (self : @& GlobalVariableRef) : IO ConstantRef /-- Set the initializer of this global variable. -/ @[extern "papyrus_global_variable_set_initializer"] constant setInitializer (init : @& ConstantRef) (self : @& GlobalVariableRef) : IO PUnit /-- Remove the initializer of this global variable. -/ @[extern "papyrus_global_variable_remove_initializer"] constant removeInitializer (self : @& GlobalVariableRef) : IO PUnit /-- Get whether the this global variable is externally initialized. -/ @[extern "papyrus_global_variable_is_externally_initialized"] constant isExternallyInitialized (self : @& GlobalVariableRef) : IO Bool /-- Set whether the this global variable is externally initialized. -/ @[extern "papyrus_global_variable_set_externally_initialized"] constant setExternallyInitialized (externallyInitialized : Bool) (self : @& GlobalVariableRef) : IO Bool end GlobalVariableRef
90f0f96ea1b2b04ba217570df2fcd01b8981801b
626e312b5c1cb2d88fca108f5933076012633192
/src/measure_theory/function/conditional_expectation.lean
363b3275943ff6b85976dab15c4a408b81b2f318
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,203
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.function.l2_space import measure_theory.function.ae_eq_of_integral /-! # Conditional expectation The conditional expectation will be defined for functions in `L²` by an orthogonal projection into a complete subspace of `L²`. It will then be extended to `L¹`. For now, this file contains only the definition of the subspace of `Lᵖ` containing functions which are measurable with respect to a sub-σ-algebra, as well as a proof that it is complete. -/ noncomputable theory open topological_space measure_theory.Lp filter open_locale nnreal ennreal topological_space big_operators measure_theory namespace measure_theory /-- A function `f` verifies `ae_measurable' m f μ` if it is `μ`-a.e. equal to an `m`-measurable function. This is similar to `ae_measurable`, but the `measurable_space` structures used for the measurability statement and for the measure are different. -/ def ae_measurable' {α β} [measurable_space β] (m : measurable_space α) {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g : α → β, @measurable α β m _ g ∧ f =ᵐ[μ] g namespace ae_measurable' variables {α β 𝕜 : Type*} {m m0 : measurable_space α} {μ : measure α} [measurable_space β] [measurable_space 𝕜] {f g : α → β} lemma congr (hf : ae_measurable' m f μ) (hfg : f =ᵐ[μ] g) : ae_measurable' m g μ := by { obtain ⟨f', hf'_meas, hff'⟩ := hf, exact ⟨f', hf'_meas, hfg.symm.trans hff'⟩, } lemma add [has_add β] [has_measurable_add₂ β] (hf : ae_measurable' m f μ) (hg : ae_measurable' m g μ) : ae_measurable' m (f+g) μ := begin rcases hf with ⟨f', h_f'_meas, hff'⟩, rcases hg with ⟨g', h_g'_meas, hgg'⟩, exact ⟨f' + g', @measurable.add _ _ _ _ m _ f' g' h_f'_meas h_g'_meas, hff'.add hgg'⟩, end lemma neg [has_neg β] [has_measurable_neg β] {f : α → β} (hfm : ae_measurable' m f μ) : ae_measurable' m (-f) μ := begin rcases hfm with ⟨f', hf'_meas, hf_ae⟩, refine ⟨-f', @measurable.neg _ _ _ _ _ m _ hf'_meas, hf_ae.mono (λ x hx, _)⟩, simp_rw pi.neg_apply, rw hx, end lemma sub [has_sub β] [has_measurable_sub₂ β] {f g : α → β} (hfm : ae_measurable' m f μ) (hgm : ae_measurable' m g μ) : ae_measurable' m (f - g) μ := begin rcases hfm with ⟨f', hf'_meas, hf_ae⟩, rcases hgm with ⟨g', hg'_meas, hg_ae⟩, refine ⟨f'-g', @measurable.sub _ _ _ _ m _ _ _ hf'_meas hg'_meas, hf_ae.mp (hg_ae.mono (λ x hx1 hx2, _))⟩, simp_rw pi.sub_apply, rw [hx1, hx2], end lemma const_smul [has_scalar 𝕜 β] [has_measurable_smul 𝕜 β] (c : 𝕜) (hf : ae_measurable' m f μ) : ae_measurable' m (c • f) μ := begin rcases hf with ⟨f', h_f'_meas, hff'⟩, refine ⟨c • f', @measurable.const_smul _ _ _ _ _ _ m _ f' h_f'_meas c, _⟩, exact eventually_eq.fun_comp hff' (λ x, c • x), end /-- A m-measurable function almost everywhere equal to `f`. -/ def mk (f : α → β) (hfm : ae_measurable' m f μ) : α → β := hfm.some lemma measurable_mk {f : α → β} (hfm : ae_measurable' m f μ) : @measurable _ _ m _ (hfm.mk f) := hfm.some_spec.1 lemma ae_eq_mk {f : α → β} (hfm : ae_measurable' m f μ) : f =ᵐ[μ] hfm.mk f := hfm.some_spec.2 end ae_measurable' lemma ae_measurable'_of_ae_measurable'_trim {α β} {m m0 m0' : measurable_space α} [measurable_space β] (hm0 : m0 ≤ m0') {μ : measure α} {f : α → β} (hf : ae_measurable' m f (μ.trim hm0)) : ae_measurable' m f μ := by { obtain ⟨g, hg_meas, hfg⟩ := hf, exact ⟨g, hg_meas, ae_eq_of_ae_eq_trim hfg⟩, } lemma measurable.ae_measurable' {α β} {m m0 : measurable_space α} [measurable_space β] {μ : measure α} {f : α → β} (hf : @measurable _ _ m _ f) : ae_measurable' m f μ := ⟨f, hf, ae_eq_refl _⟩ lemma ae_eq_trim_iff_of_ae_measurable' {α β} [add_group β] [measurable_space β] [measurable_singleton_class β] [has_measurable_sub₂ β] {m m0 : measurable_space α} {μ : measure α} {f g : α → β} (hm : m ≤ m0) (hfm : ae_measurable' m f μ) (hgm : ae_measurable' m g μ) : hfm.mk f =ᵐ[μ.trim hm] hgm.mk g ↔ f =ᵐ[μ] g := (ae_eq_trim_iff hm hfm.measurable_mk hgm.measurable_mk).trans ⟨λ h, hfm.ae_eq_mk.trans (h.trans hgm.ae_eq_mk.symm), λ h, hfm.ae_eq_mk.symm.trans (h.trans hgm.ae_eq_mk)⟩ variables {α β γ E E' F F' G G' H 𝕜 : Type*} {p : ℝ≥0∞} [is_R_or_C 𝕜] [measurable_space 𝕜] -- 𝕜 for ℝ or ℂ, together with a measurable_space [measurable_space β] -- β for a generic measurable space -- E for an inner product space [inner_product_space 𝕜 E] [measurable_space E] [borel_space E] [second_countable_topology E] -- E' for an inner product space on which we compute integrals [inner_product_space 𝕜 E'] [measurable_space E'] [borel_space E'] [second_countable_topology E'] [complete_space E'] [normed_space ℝ E'] -- F for a Lp submodule [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] [second_countable_topology F] -- F' for integrals on a Lp submodule [normed_group F'] [normed_space 𝕜 F'] [measurable_space F'] [borel_space F'] [second_countable_topology F'] [normed_space ℝ F'] [complete_space F'] -- G for a Lp add_subgroup [normed_group G] [measurable_space G] [borel_space G] [second_countable_topology G] -- G' for integrals on a Lp add_subgroup [normed_group G'] [measurable_space G'] [borel_space G'] [second_countable_topology G'] [normed_space ℝ G'] [complete_space G'] -- H for measurable space and normed group (hypotheses of mem_ℒp) [measurable_space H] [normed_group H] section Lp_meas variables (F 𝕜) /-- `Lp_meas F 𝕜 m p μ` is the subspace of `Lp F p μ` containing functions `f` verifying `ae_measurable' m f μ`, i.e. functions which are `μ`-a.e. equal to an `m`-measurable function. -/ def Lp_meas [opens_measurable_space 𝕜] (m : measurable_space α) [measurable_space α] (p : ℝ≥0∞) (μ : measure α) : submodule 𝕜 (Lp F p μ) := { carrier := {f : (Lp F p μ) | ae_measurable' m f μ} , zero_mem' := ⟨(0 : α → F), @measurable_zero _ α _ m _, Lp.coe_fn_zero _ _ _⟩, add_mem' := λ f g hf hg, (hf.add hg).congr (Lp.coe_fn_add f g).symm, smul_mem' := λ c f hf, (hf.const_smul c).congr (Lp.coe_fn_smul c f).symm, } variables {F 𝕜} variables [opens_measurable_space 𝕜] lemma mem_Lp_meas_iff_ae_measurable' {m m0 : measurable_space α} {μ : measure α} {f : Lp F p μ} : f ∈ Lp_meas F 𝕜 m p μ ↔ ae_measurable' m f μ := by simp_rw [← set_like.mem_coe, ← submodule.mem_carrier, Lp_meas, set.mem_set_of_eq] lemma Lp_meas.ae_measurable' {m m0 : measurable_space α} {μ : measure α} (f : Lp_meas F 𝕜 m p μ) : ae_measurable' m f μ := mem_Lp_meas_iff_ae_measurable'.mp f.mem lemma mem_Lp_meas_self {m0 : measurable_space α} (μ : measure α) (f : Lp F p μ) : f ∈ Lp_meas F 𝕜 m0 p μ := mem_Lp_meas_iff_ae_measurable'.mpr (Lp.ae_measurable f) lemma Lp_meas_coe {m m0 : measurable_space α} {μ : measure α} {f : Lp_meas F 𝕜 m p μ} : ⇑f = (f : Lp F p μ) := coe_fn_coe_base f lemma mem_Lp_meas_indicator_const_Lp {m m0 : measurable_space α} (hm : m ≤ m0) {μ : measure α} {s : set α} (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) {c : F} : indicator_const_Lp p (hm s hs) hμs c ∈ Lp_meas F 𝕜 m p μ := ⟨s.indicator (λ x : α, c), @measurable.indicator α _ m _ _ s (λ x, c) (@measurable_const _ α _ m _) hs, indicator_const_Lp_coe_fn⟩ section complete_subspace /-! ## The subspace `Lp_meas` is complete. We define a `linear_isometry_equiv` between `Lp_meas` and the `Lp` space corresponding to the measure `μ.trim hm`. As a consequence, the completeness of `Lp` implies completeness of `Lp_meas`. -/ variables {ι : Type*} {m m0 : measurable_space α} {μ : measure α} /-- If `f` belongs to `Lp_meas F 𝕜 m p μ`, then the measurable function it is almost everywhere equal to (given by `ae_measurable.mk`) belongs to `ℒp` for the measure `μ.trim hm`. -/ lemma mem_ℒp_trim_of_mem_Lp_meas (hm : m ≤ m0) (f : Lp F p μ) (hf_meas : f ∈ Lp_meas F 𝕜 m p μ) : mem_ℒp (mem_Lp_meas_iff_ae_measurable'.mp hf_meas).some p (μ.trim hm) := begin have hf : ae_measurable' m f μ, from (mem_Lp_meas_iff_ae_measurable'.mp hf_meas), let g := hf.some, obtain ⟨hg, hfg⟩ := hf.some_spec, change mem_ℒp g p (μ.trim hm), refine ⟨hg.ae_measurable, _⟩, have h_snorm_fg : snorm g p (μ.trim hm) = snorm f p μ, by { rw snorm_trim hm hg, exact snorm_congr_ae hfg.symm, }, rw h_snorm_fg, exact Lp.snorm_lt_top f, end /-- If `f` belongs to `Lp` for the measure `μ.trim hm`, then it belongs to the subspace `Lp_meas F 𝕜 m p μ`. -/ lemma mem_Lp_meas_to_Lp_of_trim (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : (mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f)).to_Lp f ∈ Lp_meas F 𝕜 m p μ := begin let hf_mem_ℒp := mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f), rw mem_Lp_meas_iff_ae_measurable', refine ae_measurable'.congr _ (mem_ℒp.coe_fn_to_Lp hf_mem_ℒp).symm, refine ae_measurable'_of_ae_measurable'_trim hm _, exact (Lp.ae_measurable f), end variables (F 𝕜 p μ) /-- Map from `Lp_meas` to `Lp F p (μ.trim hm)`. -/ def Lp_meas_to_Lp_trim (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) : Lp F p (μ.trim hm) := mem_ℒp.to_Lp (mem_Lp_meas_iff_ae_measurable'.mp f.mem).some (mem_ℒp_trim_of_mem_Lp_meas hm f f.mem) /-- Map from `Lp F p (μ.trim hm)` to `Lp_meas`, inverse of `Lp_meas_to_Lp_trim`. -/ def Lp_trim_to_Lp_meas (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : Lp_meas F 𝕜 m p μ := ⟨(mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f)).to_Lp f, mem_Lp_meas_to_Lp_of_trim hm f⟩ variables {F 𝕜 p μ} lemma Lp_meas_to_Lp_trim_ae_eq (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) : Lp_meas_to_Lp_trim F 𝕜 p μ hm f =ᵐ[μ] f := (ae_eq_of_ae_eq_trim (mem_ℒp.coe_fn_to_Lp (mem_ℒp_trim_of_mem_Lp_meas hm ↑f f.mem))).trans (mem_Lp_meas_iff_ae_measurable'.mp f.mem).some_spec.2.symm lemma Lp_trim_to_Lp_meas_ae_eq (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : Lp_trim_to_Lp_meas F 𝕜 p μ hm f =ᵐ[μ] f := mem_ℒp.coe_fn_to_Lp _ /-- `Lp_trim_to_Lp_meas` is a right inverse of `Lp_meas_to_Lp_trim`. -/ lemma Lp_meas_to_Lp_trim_right_inv (hm : m ≤ m0) : function.right_inverse (Lp_trim_to_Lp_meas F 𝕜 p μ hm) (Lp_meas_to_Lp_trim F 𝕜 p μ hm) := begin intro f, ext1, refine ae_eq_trim_of_measurable hm (Lp.measurable _) (Lp.measurable _) _, exact (Lp_meas_to_Lp_trim_ae_eq hm _).trans (Lp_trim_to_Lp_meas_ae_eq hm _), end /-- `Lp_trim_to_Lp_meas` is a left inverse of `Lp_meas_to_Lp_trim`. -/ lemma Lp_meas_to_Lp_trim_left_inv (hm : m ≤ m0) : function.left_inverse (Lp_trim_to_Lp_meas F 𝕜 p μ hm) (Lp_meas_to_Lp_trim F 𝕜 p μ hm) := begin intro f, ext1, ext1, rw ← Lp_meas_coe, exact (Lp_trim_to_Lp_meas_ae_eq hm _).trans (Lp_meas_to_Lp_trim_ae_eq hm _), end lemma Lp_meas_to_Lp_trim_add (hm : m ≤ m0) (f g : Lp_meas F 𝕜 m p μ) : Lp_meas_to_Lp_trim F 𝕜 p μ hm (f + g) = Lp_meas_to_Lp_trim F 𝕜 p μ hm f + Lp_meas_to_Lp_trim F 𝕜 p μ hm g := begin ext1, refine eventually_eq.trans _ (Lp.coe_fn_add _ _).symm, refine ae_eq_trim_of_measurable hm (Lp.measurable _) _ _, { exact @measurable.add _ _ _ _ m _ _ _ (Lp.measurable _) (Lp.measurable _), }, refine (Lp_meas_to_Lp_trim_ae_eq hm _).trans _, refine eventually_eq.trans _ (eventually_eq.add (Lp_meas_to_Lp_trim_ae_eq hm f).symm (Lp_meas_to_Lp_trim_ae_eq hm g).symm), refine (Lp.coe_fn_add _ _).trans _, simp_rw Lp_meas_coe, exact eventually_of_forall (λ x, by refl), end lemma Lp_meas_to_Lp_trim_smul (hm : m ≤ m0) (c : 𝕜) (f : Lp_meas F 𝕜 m p μ) : Lp_meas_to_Lp_trim F 𝕜 p μ hm (c • f) = c • Lp_meas_to_Lp_trim F 𝕜 p μ hm f := begin ext1, refine eventually_eq.trans _ (Lp.coe_fn_smul _ _).symm, refine ae_eq_trim_of_measurable hm (Lp.measurable _) _ _, { exact @measurable.const_smul _ _ _ _ _ _ m _ _ (Lp.measurable _) c, }, refine (Lp_meas_to_Lp_trim_ae_eq hm _).trans _, refine (Lp.coe_fn_smul c _).trans _, refine (Lp_meas_to_Lp_trim_ae_eq hm f).mono (λ x hx, _), rw [pi.smul_apply, pi.smul_apply, hx, Lp_meas_coe], refl, end /-- `Lp_meas_to_Lp_trim` preserves the norm. -/ lemma Lp_meas_to_Lp_trim_norm_map [hp : fact (1 ≤ p)] (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) : ∥Lp_meas_to_Lp_trim F 𝕜 p μ hm f∥ = ∥f∥ := begin rw [norm_def, snorm_trim hm (Lp.measurable _)], swap, { apply_instance, }, rw [snorm_congr_ae (Lp_meas_to_Lp_trim_ae_eq hm _), Lp_meas_coe, ← norm_def], congr, end variables (F 𝕜 p μ) /-- A linear isometry equivalence between `Lp_meas` and `Lp F p (μ.trim hm)`. -/ def Lp_meas_to_Lp_trim_lie [hp : fact (1 ≤ p)] (hm : m ≤ m0) : Lp_meas F 𝕜 m p μ ≃ₗᵢ[𝕜] Lp F p (μ.trim hm) := { to_fun := Lp_meas_to_Lp_trim F 𝕜 p μ hm, map_add' := Lp_meas_to_Lp_trim_add hm, map_smul' := Lp_meas_to_Lp_trim_smul hm, inv_fun := Lp_trim_to_Lp_meas F 𝕜 p μ hm, left_inv := Lp_meas_to_Lp_trim_left_inv hm, right_inv := Lp_meas_to_Lp_trim_right_inv hm, norm_map' := Lp_meas_to_Lp_trim_norm_map hm, } variables {F 𝕜 p μ} instance [hm : fact (m ≤ m0)] [complete_space F] [hp : fact (1 ≤ p)] : complete_space (Lp_meas F 𝕜 m p μ) := by { rw (Lp_meas_to_Lp_trim_lie F 𝕜 p μ hm.elim).to_isometric.complete_space_iff, apply_instance, } end complete_subspace section strongly_measurable variables {m m0 : measurable_space α} {μ : measure α} /-- We do not get `ae_fin_strongly_measurable f (μ.trim hm)`, since we don't have `f =ᵐ[μ.trim hm] Lp_meas_to_Lp_trim F 𝕜 p μ hm f` but only the weaker `f =ᵐ[μ] Lp_meas_to_Lp_trim F 𝕜 p μ hm f`. -/ lemma Lp_meas.ae_fin_strongly_measurable' (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : ∃ g, fin_strongly_measurable g (μ.trim hm) ∧ f =ᵐ[μ] g := ⟨Lp_meas_to_Lp_trim F 𝕜 p μ hm f, Lp.fin_strongly_measurable _ hp_ne_zero hp_ne_top, (Lp_meas_to_Lp_trim_ae_eq hm f).symm⟩ end strongly_measurable end Lp_meas section uniqueness_of_conditional_expectation /-! ## Uniqueness of the conditional expectation -/ variables {m m0 : measurable_space α} {μ : measure α} [borel_space 𝕜] lemma Lp_meas.ae_eq_zero_of_forall_set_integral_eq_zero (hm : m ≤ m0) (f : Lp_meas E' 𝕜 m p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hf_zero : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) : f =ᵐ[μ] 0 := begin obtain ⟨g, hg_sm, hfg⟩ := Lp_meas.ae_fin_strongly_measurable' hm f hp_ne_zero hp_ne_top, refine hfg.trans _, refine ae_eq_zero_of_forall_set_integral_eq_of_fin_strongly_measurable_trim hm _ _ hg_sm, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] g, from ae_restrict_of_ae hfg, rw [integrable_on, integrable_congr hfg_restrict.symm], exact hf_int_finite s hs hμs, }, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] g, from ae_restrict_of_ae hfg, rw integral_congr_ae hfg_restrict.symm, exact hf_zero s hs hμs, }, end include 𝕜 lemma Lp.ae_eq_zero_of_forall_set_integral_eq_zero' (hm : m ≤ m0) (f : Lp E' p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hf_zero : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) (hf_meas : ae_measurable' m f μ) : f =ᵐ[μ] 0 := begin let f_meas : Lp_meas E' 𝕜 m p μ := ⟨f, hf_meas⟩, have hf_f_meas : f =ᵐ[μ] f_meas, by simp only [coe_fn_coe_base, subtype.coe_mk], refine hf_f_meas.trans _, refine Lp_meas.ae_eq_zero_of_forall_set_integral_eq_zero hm f_meas hp_ne_zero hp_ne_top _ _, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] f_meas, from ae_restrict_of_ae hf_f_meas, rw [integrable_on, integrable_congr hfg_restrict.symm], exact hf_int_finite s hs hμs, }, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] f_meas, from ae_restrict_of_ae hf_f_meas, rw integral_congr_ae hfg_restrict.symm, exact hf_zero s hs hμs, }, end /-- **Uniqueness of the conditional expectation** -/ lemma Lp.ae_eq_of_forall_set_integral_eq' (hm : m ≤ m0) (f g : Lp E' p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hg_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on g s μ) (hfg : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) (hf_meas : ae_measurable' m f μ) (hg_meas : ae_measurable' m g μ) : f =ᵐ[μ] g := begin suffices h_sub : ⇑(f-g) =ᵐ[μ] 0, by { rw ← sub_ae_eq_zero, exact (Lp.coe_fn_sub f g).symm.trans h_sub, }, have hfg' : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, (f - g) x ∂μ = 0, { intros s hs hμs, rw integral_congr_ae (ae_restrict_of_ae (Lp.coe_fn_sub f g)), rw integral_sub' (hf_int_finite s hs hμs) (hg_int_finite s hs hμs), exact sub_eq_zero.mpr (hfg s hs hμs), }, have hfg_int : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on ⇑(f-g) s μ, { intros s hs hμs, rw [integrable_on, integrable_congr (ae_restrict_of_ae (Lp.coe_fn_sub f g))], exact (hf_int_finite s hs hμs).sub (hg_int_finite s hs hμs), }, have hfg_meas : ae_measurable' m ⇑(f - g) μ, from ae_measurable'.congr (hf_meas.sub hg_meas) (Lp.coe_fn_sub f g).symm, exact Lp.ae_eq_zero_of_forall_set_integral_eq_zero' hm (f-g) hp_ne_zero hp_ne_top hfg_int hfg' hfg_meas, end omit 𝕜 lemma ae_eq_of_forall_set_integral_eq_of_sigma_finite' (hm : m ≤ m0) [sigma_finite (μ.trim hm)] {f g : α → F'} (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hg_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on g s μ) (hfg_eq : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) (hfm : ae_measurable' m f μ) (hgm : ae_measurable' m g μ) : f =ᵐ[μ] g := begin rw ← ae_eq_trim_iff_of_ae_measurable' hm hfm hgm, have hf_mk_int_finite : ∀ s, measurable_set[m] s → μ.trim hm s < ∞ → @integrable_on _ _ m _ _ (hfm.mk f) s (μ.trim hm), { intros s hs hμs, rw trim_measurable_set_eq hm hs at hμs, rw [integrable_on, restrict_trim hm _ hs], refine integrable.trim hm _ hfm.measurable_mk, exact integrable.congr (hf_int_finite s hs hμs) (ae_restrict_of_ae hfm.ae_eq_mk), }, have hg_mk_int_finite : ∀ s, measurable_set[m] s → μ.trim hm s < ∞ → @integrable_on _ _ m _ _ (hgm.mk g) s (μ.trim hm), { intros s hs hμs, rw trim_measurable_set_eq hm hs at hμs, rw [integrable_on, restrict_trim hm _ hs], refine integrable.trim hm _ hgm.measurable_mk, exact integrable.congr (hg_int_finite s hs hμs) (ae_restrict_of_ae hgm.ae_eq_mk), }, have hfg_mk_eq : ∀ s : set α, measurable_set[m] s → μ.trim hm s < ∞ → ∫ x in s, (hfm.mk f x) ∂(μ.trim hm) = ∫ x in s, (hgm.mk g x) ∂(μ.trim hm), { intros s hs hμs, rw trim_measurable_set_eq hm hs at hμs, rw [restrict_trim hm _ hs, ← integral_trim hm hfm.measurable_mk, ← integral_trim hm hgm.measurable_mk, integral_congr_ae (ae_restrict_of_ae hfm.ae_eq_mk.symm), integral_congr_ae (ae_restrict_of_ae hgm.ae_eq_mk.symm)], exact hfg_eq s hs hμs, }, exact ae_eq_of_forall_set_integral_eq_of_sigma_finite hf_mk_int_finite hg_mk_int_finite hfg_mk_eq, end end uniqueness_of_conditional_expectation section integral_norm_le variables {m m0 : measurable_space α} {μ : measure α} {s : set α} /-- Let `m` be a sub-σ-algebra of `m0`, `f` a `m0`-measurable function and `g` a `m`-measurable function, such that their integrals coincide on `m`-measurable sets with finite measure. Then `∫ x in s, ∥g x∥ ∂μ ≤ ∫ x in s, ∥f x∥ ∂μ` on all `m`-measurable sets with finite measure. -/ lemma integral_norm_le_of_forall_fin_meas_integral_eq (hm : m ≤ m0) {f g : α → ℝ} (hf : measurable f) (hfi : integrable_on f s μ) (hg : measurable[m] g) (hgi : integrable_on g s μ) (hgf : ∀ t, measurable_set[m] t → μ t < ∞ → ∫ x in t, g x ∂μ = ∫ x in t, f x ∂μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, ∥g x∥ ∂μ ≤ ∫ x in s, ∥f x∥ ∂μ := begin rw [integral_norm_eq_pos_sub_neg (hg.mono hm le_rfl) hgi, integral_norm_eq_pos_sub_neg hf hfi], have h_meas_nonneg_g : measurable_set[m] {x | 0 ≤ g x}, from @measurable_set_le _ α _ _ _ m _ _ _ _ g (@measurable_const _ α _ m _) hg, have h_meas_nonneg_f : measurable_set {x | 0 ≤ f x}, from measurable_set_le measurable_const hf, have h_meas_nonpos_g : measurable_set[m] {x | g x ≤ 0}, from @measurable_set_le _ α _ _ _ m _ _ _ g _ hg (@measurable_const _ α _ m _), have h_meas_nonpos_f : measurable_set {x | f x ≤ 0}, from measurable_set_le hf measurable_const, refine sub_le_sub _ _, { rw [measure.restrict_restrict (hm _ h_meas_nonneg_g), measure.restrict_restrict h_meas_nonneg_f, hgf _ (@measurable_set.inter α m _ _ h_meas_nonneg_g hs) ((measure_mono (set.inter_subset_right _ _)).trans_lt (lt_top_iff_ne_top.mpr hμs)), ← measure.restrict_restrict (hm _ h_meas_nonneg_g), ← measure.restrict_restrict h_meas_nonneg_f], exact set_integral_le_nonneg (hm _ h_meas_nonneg_g) hf hfi, }, { rw [measure.restrict_restrict (hm _ h_meas_nonpos_g), measure.restrict_restrict h_meas_nonpos_f, hgf _ (@measurable_set.inter α m _ _ h_meas_nonpos_g hs) ((measure_mono (set.inter_subset_right _ _)).trans_lt (lt_top_iff_ne_top.mpr hμs)), ← measure.restrict_restrict (hm _ h_meas_nonpos_g), ← measure.restrict_restrict h_meas_nonpos_f], exact set_integral_nonpos_le (hm _ h_meas_nonpos_g) hf hfi, }, end /-- Let `m` be a sub-σ-algebra of `m0`, `f` a `m0`-measurable function and `g` a `m`-measurable function, such that their integrals coincide on `m`-measurable sets with finite measure. Then `∫⁻ x in s, ∥g x∥₊ ∂μ ≤ ∫⁻ x in s, ∥f x∥₊ ∂μ` on all `m`-measurable sets with finite measure. -/ lemma lintegral_nnnorm_le_of_forall_fin_meas_integral_eq (hm : m ≤ m0) {f g : α → ℝ} (hf : measurable f) (hfi : integrable_on f s μ) (hg : measurable[m] g) (hgi : integrable_on g s μ) (hgf : ∀ t, measurable_set[m] t → μ t < ∞ → ∫ x in t, g x ∂μ = ∫ x in t, f x ∂μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫⁻ x in s, ∥g x∥₊ ∂μ ≤ ∫⁻ x in s, ∥f x∥₊ ∂μ := begin rw [← of_real_integral_norm_eq_lintegral_nnnorm hfi, ← of_real_integral_norm_eq_lintegral_nnnorm hgi, ennreal.of_real_le_of_real_iff], { exact integral_norm_le_of_forall_fin_meas_integral_eq hm hf hfi hg hgi hgf hs hμs, }, { exact integral_nonneg (λ x, norm_nonneg _), }, end end integral_norm_le /-! ## Conditional expectation in L2 We define a conditional expectation in `L2`: it is the orthogonal projection on the subspace `Lp_meas`. -/ section condexp_L2 local attribute [instance] fact_one_le_two_ennreal variables [complete_space E] [borel_space 𝕜] {m m0 : measurable_space α} {μ : measure α} {s t : set α} local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local notation `⟪`x`, `y`⟫₂` := @inner 𝕜 (α →₂[μ] E) _ x y variables (𝕜) /-- Conditional expectation of a function in L2 with respect to a sigma-algebra -/ def condexp_L2 (hm : m ≤ m0) : (α →₂[μ] E) →L[𝕜] (Lp_meas E 𝕜 m 2 μ) := @orthogonal_projection 𝕜 (α →₂[μ] E) _ _ (Lp_meas E 𝕜 m 2 μ) (by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact infer_instance, }) variables {𝕜} lemma integrable_on_condexp_L2_of_measure_ne_top (hm : m ≤ m0) (hμs : μ s ≠ ∞) (f : α →₂[μ] E) : integrable_on (condexp_L2 𝕜 hm f) s μ := integrable_on_Lp_of_measure_ne_top ((condexp_L2 𝕜 hm f) : α →₂[μ] E) fact_one_le_two_ennreal.elim hμs lemma integrable_condexp_L2_of_is_finite_measure (hm : m ≤ m0) [is_finite_measure μ] {f : α →₂[μ] E} : integrable (condexp_L2 𝕜 hm f) μ := integrable_on_univ.mp $ integrable_on_condexp_L2_of_measure_ne_top hm (measure_ne_top _ _) f lemma norm_condexp_L2_le_one (hm : m ≤ m0) : ∥@condexp_L2 α E 𝕜 _ _ _ _ _ _ _ _ _ _ μ hm∥ ≤ 1 := by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact orthogonal_projection_norm_le _, } lemma norm_condexp_L2_le (hm : m ≤ m0) (f : α →₂[μ] E) : ∥condexp_L2 𝕜 hm f∥ ≤ ∥f∥ := ((@condexp_L2 _ E 𝕜 _ _ _ _ _ _ _ _ _ _ μ hm).le_op_norm f).trans (mul_le_of_le_one_left (norm_nonneg _) (norm_condexp_L2_le_one hm)) lemma snorm_condexp_L2_le (hm : m ≤ m0) (f : α →₂[μ] E) : snorm (condexp_L2 𝕜 hm f) 2 μ ≤ snorm f 2 μ := begin rw [Lp_meas_coe, ← ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _), ← norm_def, ← norm_def, submodule.norm_coe], exact norm_condexp_L2_le hm f, end lemma norm_condexp_L2_coe_le (hm : m ≤ m0) (f : α →₂[μ] E) : ∥(condexp_L2 𝕜 hm f : α →₂[μ] E)∥ ≤ ∥f∥ := begin rw [norm_def, norm_def, ← Lp_meas_coe], refine (ennreal.to_real_le_to_real _ (Lp.snorm_ne_top _)).mpr (snorm_condexp_L2_le hm f), exact Lp.snorm_ne_top _, end lemma inner_condexp_L2_left_eq_right (hm : m ≤ m0) {f g : α →₂[μ] E} : ⟪(condexp_L2 𝕜 hm f : α →₂[μ] E), g⟫₂ = ⟪f, (condexp_L2 𝕜 hm g : α →₂[μ] E)⟫₂ := by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact inner_orthogonal_projection_left_eq_right _ f g, } lemma condexp_L2_indicator_of_measurable (hm : m ≤ m0) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) (c : E) : (condexp_L2 𝕜 hm (indicator_const_Lp 2 (hm s hs) hμs c) : α →₂[μ] E) = indicator_const_Lp 2 (hm s hs) hμs c := begin rw condexp_L2, haveI : fact (m ≤ m0) := ⟨hm⟩, have h_mem : indicator_const_Lp 2 (hm s hs) hμs c ∈ Lp_meas E 𝕜 m 2 μ, from mem_Lp_meas_indicator_const_Lp hm hs hμs, let ind := (⟨indicator_const_Lp 2 (hm s hs) hμs c, h_mem⟩ : Lp_meas E 𝕜 m 2 μ), have h_coe_ind : (ind : α →₂[μ] E) = indicator_const_Lp 2 (hm s hs) hμs c, by refl, have h_orth_mem := orthogonal_projection_mem_subspace_eq_self ind, rw [← h_coe_ind, h_orth_mem], end lemma inner_condexp_L2_eq_inner_fun (hm : m ≤ m0) (f g : α →₂[μ] E) (hg : ae_measurable' m g μ) : ⟪(condexp_L2 𝕜 hm f : α →₂[μ] E), g⟫₂ = ⟪f, g⟫₂ := begin symmetry, rw [← sub_eq_zero, ← inner_sub_left, condexp_L2], simp only [mem_Lp_meas_iff_ae_measurable'.mpr hg, orthogonal_projection_inner_eq_zero], end end condexp_L2 end measure_theory
d1c65f6658cd586ff7af6976f90c59a43d77d370
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/init/default.hlean
a0c9b5e7458a761e92fcc7e82ca4e58cd225528f
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
524
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jakob von Raumer -/ prelude import init.datatypes init.reserved_notation init.tactic init.logic import init.bool init.num init.priority init.relation init.wf import init.types.sigma init.types.prod init.types.empty import init.trunc init.path init.equiv init.util import init.axioms.ua init.axioms.funext init.axioms.funext_from_ua import init.hedberg init.nat
d00783aee0d0ff0570c524d4ccd7cd762a3b4392
d406927ab5617694ec9ea7001f101b7c9e3d9702
/counterexamples/homogeneous_prime_not_prime.lean
8b9f1a9328952179eeb8960fdf7acacb70e9c59f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,645
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Eric Wieser, Jujian Zhang -/ import ring_theory.graded_algebra.homogeneous_ideal import data.zmod.basic import tactic.derive_fintype /-! # A homogeneous prime that is homogeneously prime but not prime In `src/ring_theory/graded_algebra/radical.lean`, we assumed that the underline grading is indexed by a `linear_ordered_cancel_add_comm_monoid` to prove that a homogeneous ideal is prime if and only if it is homogeneously prime. This file is aimed to show that even if this assumption isn't strictly necessary, the assumption of "being cancellative" is. We construct a counterexample where the underlying indexing set is a `linear_ordered_add_comm_monoid` but is not cancellative and the statement is false. We achieve this by considering the ring `R=ℤ/4ℤ`. We first give the two element set `ι = {0, 1}` a structure of linear ordered additive commutative monoid by setting `0 + 0 = 0` and `_ + _ = 1` and `0 < 1`. Then we use `ι` to grade `R²` by setting `{(a, a) | a ∈ R}` to have grade `0`; and `{(0, b) | b ∈ R}` to have grade 1. Then the ideal `I = span {(0, 2)} ⊆ ℤ/4ℤ` is homogeneous and not prime. But it is homogeneously prime, i.e. if `(a, b), (c, d)` are two homogeneous elements then `(a, b) * (c, d) ∈ I` implies either `(a, b) ∈ I` or `(c, d) ∈ I`. ## Tags homogeneous, prime -/ namespace counterexample_not_prime_but_homogeneous_prime open direct_sum local attribute [reducible] with_zero abbreviation two := with_zero unit instance : linear_ordered_add_comm_monoid two := { add_le_add_left := by delta two with_zero; dec_trivial, ..(_ : linear_order two), ..(_ : add_comm_monoid two)} section variables (R : Type*) [comm_ring R] /-- The grade 0 part of `R²` is `{(a, a) | a ∈ R}`. -/ def submodule_z : submodule R (R × R) := { carrier := { zz | zz.1 = zz.2 }, zero_mem' := rfl, add_mem' := λ a b ha hb, congr_arg2 (+) ha hb, smul_mem' := λ a b hb, congr_arg ((*) a) hb } /-- The grade 1 part of `R²` is `{(0, b) | b ∈ R}`. -/ def submodule_o : submodule R (R × R) := (linear_map.fst R R R).ker /-- Given the above grading (see `submodule_z` and `submodule_o`), we turn `R²` into a graded ring. -/ def grading : two → submodule R (R × R) | 0 := submodule_z R | 1 := submodule_o R lemma grading.one_mem : (1 : (R × R)) ∈ grading R 0 := eq.refl (1, 1).fst lemma grading.mul_mem : ∀ ⦃i j : two⦄ {a b : (R × R)} (ha : a ∈ grading R i) (hb : b ∈ grading R j), a * b ∈ grading R (i + j) | 0 0 a b (ha : a.1 = a.2) (hb : b.1 = b.2) := show a.1 * b.1 = a.2 * b.2, by rw [ha, hb] | 0 1 a b (ha : a.1 = a.2) (hb : b.1 = 0) := show a.1 * b.1 = 0, by rw [hb, mul_zero] | 1 0 a b (ha : a.1 = 0) hb := show a.1 * b.1 = 0, by rw [ha, zero_mul] | 1 1 a b (ha : a.1 = 0) hb := show a.1 * b.1 = 0, by rw [ha, zero_mul] end notation `R` := zmod 4 /-- `R² ≅ {(a, a) | a ∈ R} ⨁ {(0, b) | b ∈ R}` by `(x, y) ↦ (x, x) + (0, y - x)`. -/ def grading.decompose : (R × R) →+ direct_sum two (λ i, grading R i) := { to_fun := λ zz, of (λ i, grading R i) 0 ⟨(zz.1, zz.1), rfl⟩ + of (λ i, grading R i) 1 ⟨(0, zz.2 - zz.1), rfl⟩, map_zero' := by { ext1 (_|⟨⟨⟩⟩); refl }, map_add' := begin rintros ⟨a1, b1⟩ ⟨a2, b2⟩, rw [add_add_add_comm, ←map_add, ←map_add], dsimp only [prod.mk_add_mk], simp_rw [add_sub_add_comm], congr, end } lemma grading.right_inv : function.right_inverse (coe_linear_map (grading R)) grading.decompose := λ zz, begin induction zz using direct_sum.induction_on with i zz d1 d2 ih1 ih2, { simp only [map_zero],}, { rcases i with (_|⟨⟨⟩⟩); rcases zz with ⟨⟨a, b⟩, (hab : _ = _)⟩; dsimp at hab; cases hab; dec_trivial! }, { simp only [map_add, ih1, ih2], }, end lemma grading.left_inv : function.left_inverse (coe_linear_map (grading R)) grading.decompose := λ zz, begin cases zz with a b, unfold grading.decompose, simp only [add_monoid_hom.coe_mk, map_add, coe_linear_map_of, subtype.coe_mk, prod.mk_add_mk, add_zero, add_sub_cancel'_right], end instance : graded_algebra (grading R) := { one_mem := grading.one_mem R, mul_mem := grading.mul_mem R, decompose' := grading.decompose, left_inv := by { convert grading.left_inv, }, right_inv := by { convert grading.right_inv, } } /-- The counterexample is the ideal `I = span {(2, 2)}`. -/ def I : ideal (R × R) := ideal.span {((2, 2) : (R × R))}. set_option class.instance_max_depth 34 lemma I_not_prime : ¬ I.is_prime := begin rintro ⟨rid1, rid2⟩, apply rid1, clear rid1, revert rid2, simp only [I, ideal.mem_span_singleton, ideal.eq_top_iff_one], dec_trivial, -- this is what we change the max instance depth for, it's only 2 above the default end set_option class.instance_max_depth 32 lemma I_is_homogeneous : I.is_homogeneous (grading R) := begin rw ideal.is_homogeneous.iff_exists, refine ⟨{⟨(2, 2), ⟨0, rfl⟩⟩}, _⟩, rw set.image_singleton, refl, end lemma homogeneous_mem_or_mem {x y : (R × R)} (hx : set_like.is_homogeneous (grading R) x) (hy : set_like.is_homogeneous (grading R) y) (hxy : x * y ∈ I) : x ∈ I ∨ y ∈ I := begin simp only [I, ideal.mem_span_singleton] at hxy ⊢, cases x, cases y, obtain ⟨(_|⟨⟨⟩⟩), hx : _ = _⟩ := hx; obtain ⟨(_|⟨⟨⟩⟩), hy : _ = _⟩ := hy; dsimp at hx hy; cases hx; cases hy; clear hx hy; dec_trivial!, end end counterexample_not_prime_but_homogeneous_prime
c9a0b7f8b1594b082624aa1e9e5c6ae0e0ba11f9
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/bug6.lean
4cf3109ddc07823f5c5869033db61a40b8d463be
[ "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
318
lean
open eq section variable {A : Type} theorem T {a b : A} (H : a = b) : b = a := symm H variables x y : A variable H : x = y check T H check T end section variable {A : Type} theorem T2 ⦃a b : A⦄ (H : a = b) : b = a := symm H variables x y : A variable H : x = y check T2 H check T2 end
1cc073de6e86ed250c8ee075cd652867a4941f82
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/lint/default.lean
fb3b1ebc76443a5979243017673db742547e3d33
[]
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
434
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.lint.frontend import Mathlib.tactic.lint.simp import Mathlib.tactic.lint.type_classes import Mathlib.tactic.lint.misc import Mathlib.PostPort namespace Mathlib