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
127c4e93b8a12effdeb13559e352ccd21f27d500
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Std/Data/RBMap.lean
571c2bd8747f320b4c7fbcee8a72967f3454c795
[ "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
12,644
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 -/ namespace Std universes u v w w' inductive Rbcolor := | red | black inductive RBNode (α : Type u) (β : α → Type v) := | leaf : RBNode α β | node (color : Rbcolor) (lchild : RBNode α β) (key : α) (val : β key) (rchild : RBNode α β) : RBNode α β namespace RBNode variables {α : Type u} {β : α → Type v} {σ : Type w} open Std.Rbcolor Nat def depth (f : Nat → Nat → Nat) : RBNode α β → Nat | leaf => 0 | node _ l _ _ r => succ (f (depth f l) (depth f r)) protected def min : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ leaf k v _ => some ⟨k, v⟩ | node _ l k v _ => RBNode.min l protected def max : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ _ k v leaf => some ⟨k, v⟩ | node _ _ k v r => RBNode.max r @[specialize] def fold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => fold f (f (fold f b l) k v) r @[specialize] def foldM {m : Type w → Type w'} [Monad m] (f : σ → (k : α) → β k → m σ) : (init : σ) → RBNode α β → m σ | b, leaf => pure b | b, node _ l k v r => do let b ← foldM f b l let b ← f b k v foldM f b r @[specialize] def revFold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => revFold f (f (revFold f b r) k v) l @[specialize] def all (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => true | node _ l k v r => p k v && all p l && all p r @[specialize] def any (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => false | node _ l k v r => p k v || any p l || any p r def singleton (k : α) (v : β k) : RBNode α β := node red leaf k v leaf @[inline] def balance1 : (a : α) → β a → RBNode α β → RBNode α β → RBNode α β | kv, vv, t, node _ (node red l kx vx r₁) ky vy r₂ => node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t) | kv, vv, t, node _ l₁ ky vy (node red l₂ kx vx r) => node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t) | kv, vv, t, node _ l ky vy r => node black (node red l ky vy r) kv vv t | _, _, _, _ => leaf -- unreachable @[inline] def balance2 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β | t, kv, vv, node _ (node red l kx₁ vx₁ r₁) ky vy r₂ => node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂) | t, kv, vv, node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂) => node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂) | t, kv, vv, node _ l ky vy r => node black t kv vv (node red l ky vy r) | _, _, _, _ => leaf -- unreachable def isRed : RBNode α β → Bool | node red .. => true | _ => false def isBlack : RBNode α β → Bool | node black .. => true | _ => false section Insert variables (lt : α → α → Bool) @[specialize] def ins : RBNode α β → (k : α) → β k → RBNode α β | leaf, kx, vx => node red leaf kx vx leaf | node red a ky vy b, kx, vx => if lt kx ky then node red (ins a kx vx) ky vy b else if lt ky kx then node red a ky vy (ins b kx vx) else node red a kx vx b | node black a ky vy b, kx, vx => if lt kx ky then if isRed a then balance1 ky vy b (ins a kx vx) else node black (ins a kx vx) ky vy b else if lt ky kx then if isRed b then balance2 a ky vy (ins b kx vx) else node black a ky vy (ins b kx vx) else node black a kx vx b def setBlack : RBNode α β → RBNode α β | node _ l k v r => node black l k v r | e => e @[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β := if isRed t then setBlack (ins lt t k v) else ins lt t k v end Insert def balance₃ (a : RBNode α β) (k : α) (v : β k) (d : RBNode α β) : RBNode α β := match a with | node red (node red a kx vx b) ky vy c => node red (node black a kx vx b) ky vy (node black c k v d) | node red a kx vx (node red b ky vy c) => node red (node black a kx vx b) ky vy (node black c k v d) | a => match d with | node red b ky vy (node red c kz vz d) => node red (node black a k v b) ky vy (node black c kz vz d) | node red (node red b ky vy c) kz vz d => node red (node black a k v b) ky vy (node black c kz vz d) | _ => node black a k v d def setRed : RBNode α β → RBNode α β | node _ a k v b => node red a k v b | e => e def balLeft : RBNode α β → (k : α) → β k → RBNode α β → RBNode α β | node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r | l, k, v, node black a ky vy b => balance₃ l k v (node red a ky vy b) | l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance₃ b kz vz (setRed c)) | l, k, v, r => node red l k v r -- unreachable def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β := match r with | (node red b ky vy c) => node red l k v (node black b ky vy c) | _ => match l with | node black a kx vx b => balance₃ (node red a kx vx b) k v r | node red a kx vx (node black b ky vy c) => node red (balance₃ (setRed a) kx vx b) ky vy (node black c k v r) | _ => node red l k v r -- unreachable -- TODO: use wellfounded recursion partial def appendTrees : RBNode α β → RBNode α β → RBNode α β | leaf, x => x | x, leaf => x | node red a kx vx b, node red c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d) | bc => node red a kx vx (node red bc ky vy d) | node black a kx vx b, node black c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d) | bc => balLeft a kx vx (node black bc ky vy d) | a, node red b kx vx c => node red (appendTrees a b) kx vx c | node red a kx vx b, c => node red a kx vx (appendTrees b c) section Erase variables (lt : α → α → Bool) @[specialize] def del (x : α) : RBNode α β → RBNode α β | leaf => leaf | node _ a y v b => if lt x y then if a.isBlack then balLeft (del x a) y v b else node red (del x a) y v b else if lt y x then if b.isBlack then balRight a y v (del x b) else node red a y v (del x b) else appendTrees a b @[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β := let t := del lt x t; t.setBlack end Erase section Membership variable (lt : α → α → Bool) @[specialize] def findCore : RBNode α β → (k : α) → Option (Sigma (fun k => β k)) | leaf, x => none | node _ a ky vy b, x => if lt x ky then findCore a x else if lt ky x then findCore b x else some ⟨ky, vy⟩ @[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β | leaf, x => none | node _ a ky vy b, x => if lt x ky then find a x else if lt ky x then find b x else some vy @[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, lb => lb | node _ a ky vy b, x, lb => if lt x ky then lowerBound a x lb else if lt ky x then lowerBound b x (some ⟨ky, vy⟩) else some ⟨ky, vy⟩ end Membership inductive WellFormed (lt : α → α → Bool) : RBNode α β → Prop := | leafWff : WellFormed lt leaf | insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed lt n → n' = insert lt n k v → WellFormed lt n' | eraseWff {n n' : RBNode α β} {k : α} : WellFormed lt n → n' = erase lt k n → WellFormed lt n' end RBNode open Std.RBNode /- TODO(Leo): define dRBMap -/ def RBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) := {t : RBNode α (fun _ => β) // t.WellFormed lt } @[inline] def mkRBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : RBMap α β lt := ⟨leaf, WellFormed.leafWff⟩ @[inline] def RBMap.empty {α : Type u} {β : Type v} {lt : α → α → Bool} : RBMap α β lt := mkRBMap .. instance (α : Type u) (β : Type v) (lt : α → α → Bool) : EmptyCollection (RBMap α β lt) := ⟨RBMap.empty⟩ namespace RBMap variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Bool} def depth (f : Nat → Nat → Nat) (t : RBMap α β lt) : Nat := t.val.depth f @[inline] def fold (f : σ → α → β → σ) : (init : σ) → RBMap α β lt → σ | b, ⟨t, _⟩ => t.fold f b @[inline] def revFold (f : σ → α → β → σ) : (init : σ) → RBMap α β lt → σ | b, ⟨t, _⟩ => t.revFold f b @[inline] def foldM {m : Type w → Type w'} [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β lt → m σ | b, ⟨t, _⟩ => t.foldM f b @[inline] def forM {m : Type w → Type w'} [Monad m] (f : α → β → m PUnit) (t : RBMap α β lt) : m PUnit := t.foldM (fun _ k v => f k v) ⟨⟩ @[inline] def isEmpty : RBMap α β lt → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : RBMap α β lt → List (α × β) | ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) [] @[inline] protected def min : RBMap α β lt → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : RBMap α β lt → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [Repr α] [Repr β] : Repr (RBMap α β lt) := ⟨fun t => "rbmapOf " ++ repr t.toList⟩ @[inline] def insert : RBMap α β lt → α → β → RBMap α β lt | ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩ @[inline] def erase : RBMap α β lt → α → RBMap α β lt | ⟨t, w⟩, k => ⟨t.erase lt k, WellFormed.eraseWff w rfl⟩ @[specialize] def ofList : List (α × β) → RBMap α β lt | [] => mkRBMap .. | ⟨k,v⟩::xs => (ofList xs).insert k v @[inline] def findCore? : RBMap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.findCore lt x @[inline] def find? : RBMap α β lt → α → Option β | ⟨t, _⟩, x => t.find lt x @[inline] def findD (t : RBMap α β lt) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound : RBMap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.lowerBound lt x none @[inline] def contains (t : RBMap α β lt) (a : α) : Bool := (t.find? a).isSome @[inline] def fromList (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt := l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β lt) @[inline] def all : RBMap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : RBMap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p def size (m : RBMap α β lt) : Nat := m.fold (fun sz _ _ => sz+1) 0 def maxDepth (t : RBMap α β lt) : Nat := t.val.depth Nat.max @[inline] def min! [Inhabited α] [Inhabited β] (t : RBMap α β lt) : α × β := match t.min with | some p => p | none => panic! "map is empty" @[inline] def max! [Inhabited α] [Inhabited β] (t : RBMap α β lt) : α × β := match t.max with | some p => p | none => panic! "map is empty" @[inline] def find! [Inhabited β] (t : RBMap α β lt) (k : α) : β := match t.find? k with | some b => b | none => panic! "key is not in the map" end RBMap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt := RBMap.fromList l lt end Std
fb4e4235d765ea7fa68a0aefa08c7691c31efe7a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/sigma/order.lean
bf30be59b47ed640a9c8766b96b24677fbc1c54a
[ "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
6,632
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.sigma.lex import order.bounded_order import order.lexicographic /-! # Orders on a sigma type This file defines two orders on a sigma type: * The disjoint sum of orders. `a` is less `b` iff `a` and `b` are in the same summand and `a` is less than `b` there. * The lexicographical order. `a` is less than `b` if its summand is strictly less than the summand of `b` or they are in the same summand and `a` is less than `b` there. We make the disjoint sum of orders the default set of instances. The lexicographic order goes on a type synonym. ## Notation * `Σₗ i, α i`: Sigma type equipped with the lexicographic order. Type synonym of `Σ i, α i`. ## See also Related files are: * `data.finset.colex`: Colexicographic order on finite sets. * `data.list.lex`: Lexicographic order on lists. * `data.psigma.order`: Lexicographic order on `Σₗ' i, α i`. Basically a twin of this file. * `order.lexicographic`: Lexicographic order on `α × β`. ## TODO Prove that a sigma type is a `no_max_order`, `no_min_order`, `densely_ordered` when its summands are. Upgrade `equiv.sigma_congr_left`, `equiv.sigma_congr`, `equiv.sigma_assoc`, `equiv.sigma_prod_of_equiv`, `equiv.sigma_equiv_prod`, ... to order isomorphisms. -/ namespace sigma variables {ι : Type*} {α : ι → Type*} /-! ### Disjoint sum of orders on `sigma` -/ /-- Disjoint sum of orders. `⟨i, a⟩ ≤ ⟨j, b⟩` iff `i = j` and `a ≤ b`. -/ inductive le [Π i, has_le (α i)] : Π a b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a ≤ b → le ⟨i, a⟩ ⟨i, b⟩ /-- Disjoint sum of orders. `⟨i, a⟩ < ⟨j, b⟩` iff `i = j` and `a < b`. -/ inductive lt [Π i, has_lt (α i)] : Π a b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a < b → lt ⟨i, a⟩ ⟨i, b⟩ instance [Π i, has_le (α i)] : has_le (Σ i, α i) := ⟨le⟩ instance [Π i, has_lt (α i)] : has_lt (Σ i, α i) := ⟨lt⟩ @[simp] lemma mk_le_mk_iff [Π i, has_le (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : sigma α) ≤ ⟨i, b⟩ ↔ a ≤ b := ⟨λ ⟨_, _, _, h⟩, h, le.fiber _ _ _⟩ @[simp] lemma mk_lt_mk_iff [Π i, has_lt (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : sigma α) < ⟨i, b⟩ ↔ a < b := ⟨λ ⟨_, _, _, h⟩, h, lt.fiber _ _ _⟩ lemma le_def [Π i, has_le (α i)] {a b : Σ i, α i} : a ≤ b ↔ ∃ h : a.1 = b.1, h.rec a.2 ≤ b.2 := begin split, { rintro ⟨i, a, b, h⟩, exact ⟨rfl, h⟩ }, { obtain ⟨i, a⟩ := a, obtain ⟨j, b⟩ := b, rintro ⟨(rfl : i = j), h⟩, exact le.fiber _ _ _ h } end lemma lt_def [Π i, has_lt (α i)] {a b : Σ i, α i} : a < b ↔ ∃ h : a.1 = b.1, h.rec a.2 < b.2 := begin split, { rintro ⟨i, a, b, h⟩, exact ⟨rfl, h⟩ }, { obtain ⟨i, a⟩ := a, obtain ⟨j, b⟩ := b, rintro ⟨(rfl : i = j), h⟩, exact lt.fiber _ _ _ h } end instance [Π i, preorder (α i)] : preorder (Σ i, α i) := { le_refl := λ ⟨i, a⟩, le.fiber i a a le_rfl, le_trans := begin rintro _ _ _ ⟨i, a, b, hab⟩ ⟨_, _, c, hbc⟩, exact le.fiber i a c (hab.trans hbc), end, lt_iff_le_not_le := λ _ _, begin split, { rintro ⟨i, a, b, hab⟩, rwa [mk_le_mk_iff, mk_le_mk_iff, ←lt_iff_le_not_le] }, { rintro ⟨⟨i, a, b, hab⟩, h⟩, rw mk_le_mk_iff at h, exact mk_lt_mk_iff.2 (hab.lt_of_not_le h) } end, .. sigma.has_le, .. sigma.has_lt } instance [Π i, partial_order (α i)] : partial_order (Σ i, α i) := { le_antisymm := begin rintro _ _ ⟨i, a, b, hab⟩ ⟨_, _, _, hba⟩, exact ext rfl (heq_of_eq $ hab.antisymm hba), end, .. sigma.preorder } /-! ### Lexicographical order on `sigma` -/ namespace lex notation `Σₗ` binders `, ` r:(scoped p, _root_.lex (sigma p)) := r /-- The lexicographical `≤` on a sigma type. -/ instance has_le [has_lt ι] [Π i, has_le (α i)] : has_le (Σₗ i, α i) := ⟨lex (<) (λ i, (≤))⟩ /-- The lexicographical `<` on a sigma type. -/ instance has_lt [has_lt ι] [Π i, has_lt (α i)] : has_lt (Σₗ i, α i) := ⟨lex (<) (λ i, (<))⟩ /-- The lexicographical preorder on a sigma type. -/ instance preorder [preorder ι] [Π i, preorder (α i)] : preorder (Σₗ i, α i) := { le_refl := λ ⟨i, a⟩, lex.right a a le_rfl, le_trans := λ _ _ _, trans_of (lex (<) $ λ _, (≤)), lt_iff_le_not_le := begin refine λ a b, ⟨λ hab, ⟨hab.mono_right (λ i a b, le_of_lt), _⟩, _⟩, { rintro (⟨j, i, b, a, hji⟩ | ⟨i, b, a, hba⟩); obtain (⟨_, _, _, _, hij⟩ | ⟨_, _, _, hab⟩) := hab, { exact hij.not_lt hji }, { exact lt_irrefl _ hji }, { exact lt_irrefl _ hij }, { exact hab.not_le hba } }, { rintro ⟨⟨i, j, a, b, hij⟩ |⟨i, a, b, hab⟩, hba⟩, { exact lex.left _ _ hij }, { exact lex.right _ _ (hab.lt_of_not_le $ λ h, hba $ lex.right _ _ h) } } end, .. lex.has_le, .. lex.has_lt } /-- The lexicographical partial order on a sigma type. -/ instance partial_order [preorder ι] [Π i, partial_order (α i)] : partial_order (Σₗ i, α i) := { le_antisymm := λ _ _, antisymm_of (lex (<) $ λ _, (≤)), .. lex.preorder } /-- The lexicographical linear order on a sigma type. -/ instance linear_order [linear_order ι] [Π i, linear_order (α i)] : linear_order (Σₗ i, α i) := { le_total := total_of (lex (<) $ λ _, (≤)), decidable_eq := sigma.decidable_eq, decidable_le := lex.decidable _ _, .. lex.partial_order } /-- The lexicographical linear order on a sigma type. -/ instance order_bot [partial_order ι] [order_bot ι] [Π i, preorder (α i)] [order_bot (α ⊥)] : order_bot (Σₗ i, α i) := { bot := ⟨⊥, ⊥⟩, bot_le := λ ⟨a, b⟩, begin obtain rfl | ha := eq_bot_or_bot_lt a, { exact lex.right _ _ bot_le }, { exact lex.left _ _ ha } end } /-- The lexicographical linear order on a sigma type. -/ instance order_top [partial_order ι] [order_top ι] [Π i, preorder (α i)] [order_top (α ⊤)] : order_top (Σₗ i, α i) := { top := ⟨⊤, ⊤⟩, le_top := λ ⟨a, b⟩, begin obtain rfl | ha := eq_top_or_lt_top a, { exact lex.right _ _ le_top }, { exact lex.left _ _ ha } end } /-- The lexicographical linear order on a sigma type. -/ instance bounded_order [partial_order ι] [bounded_order ι] [Π i, preorder (α i)] [order_bot (α ⊥)] [order_top (α ⊤)] : bounded_order (Σₗ i, α i) := { .. lex.order_bot, .. lex.order_top } end lex end sigma
18e1a17d99e91745ec43e74d0da6123086d56600
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/free_module/basic.lean
705aebe40706117baedee2bbcd18c58b3cb1a06c
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
5,945
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import linear_algebra.direct_sum.finsupp import logic.small import linear_algebra.std_basis /-! # Free modules We introduce a class `module.free R M`, for `R` a `semiring` and `M` an `R`-module and we provide several basic instances for this class. Use `finsupp.total_id_surjective` to prove that any module is the quotient of a free module. ## Main definition * `module.free R M` : the class of free `R`-modules. -/ universes u v w z variables (R : Type u) (M : Type v) (N : Type z) open_locale tensor_product direct_sum big_operators section basic variables [semiring R] [add_comm_monoid M] [module R M] /-- `module.free R M` is the statement that the `R`-module `M` is free.-/ class module.free : Prop := (exists_basis [] : nonempty (Σ (I : Type v), basis I R M)) /- If `M` fits in universe `w`, then freeness is equivalent to existence of a basis in that universe. Note that if `M` does not fit in `w`, the reverse direction of this implication is still true as `module.free.of_basis`. -/ lemma module.free_def [small.{w} M] : module.free R M ↔ ∃ (I : Type w), nonempty (basis I R M) := ⟨ λ h, ⟨shrink (set.range h.exists_basis.some.2), ⟨(basis.reindex_range h.exists_basis.some.2).reindex (equiv_shrink _)⟩⟩, λ h, ⟨(nonempty_sigma.2 h).map $ λ ⟨i, b⟩, ⟨set.range b, b.reindex_range⟩⟩⟩ lemma module.free_iff_set : module.free R M ↔ ∃ (S : set M), nonempty (basis S R M) := ⟨λ h, ⟨set.range h.exists_basis.some.2, ⟨basis.reindex_range h.exists_basis.some.2⟩⟩, λ ⟨S, hS⟩, ⟨nonempty_sigma.2 ⟨S, hS⟩⟩⟩ variables {R M} lemma module.free.of_basis {ι : Type w} (b : basis ι R M) : module.free R M := (module.free_def R M).2 ⟨set.range b, ⟨b.reindex_range⟩⟩ end basic namespace module.free section semiring variables (R M) [semiring R] [add_comm_monoid M] [module R M] [module.free R M] variables [add_comm_monoid N] [module R N] /-- If `[finite_free R M]` then `choose_basis_index R M` is the `ι` which indexes the basis `ι → M`. -/ @[nolint has_inhabited_instance] def choose_basis_index := (exists_basis R M).some.1 /-- If `[finite_free R M]` then `choose_basis : ι → M` is the basis. Here `ι = choose_basis_index R M`. -/ noncomputable def choose_basis : basis (choose_basis_index R M) R M := (exists_basis R M).some.2 /-- The isomorphism `M ≃ₗ[R] (choose_basis_index R M →₀ R)`. -/ noncomputable def repr : M ≃ₗ[R] (choose_basis_index R M →₀ R) := (choose_basis R M).repr /-- The universal property of free modules: giving a functon `(choose_basis_index R M) → N`, for `N` an `R`-module, is the same as giving an `R`-linear map `M →ₗ[R] N`. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ noncomputable def constr {S : Type z} [semiring S] [module S N] [smul_comm_class R S N] : ((choose_basis_index R M) → N) ≃ₗ[S] M →ₗ[R] N := basis.constr (choose_basis R M) S @[priority 100] instance no_zero_smul_divisors [no_zero_divisors R] : no_zero_smul_divisors R M := let ⟨⟨_, b⟩⟩ := exists_basis R M in b.no_zero_smul_divisors /-- The product of finitely many free modules is free. -/ instance pi {ι : Type*} [fintype ι] {M : ι → Type*} [Π (i : ι), add_comm_group (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π i, M i) := of_basis $ pi.basis $ λ i, choose_basis R (M i) /-- The module of finite matrices is free. -/ instance matrix {n : Type*} [fintype n] {m : Type*} [fintype m] : module.free R (matrix n m R) := of_basis $ matrix.std_basis R n m variables {R M N} lemma of_equiv (e : M ≃ₗ[R] N) : module.free R N := of_basis $ (choose_basis R M).map e /-- A variation of `of_equiv`: the assumption `module.free R P` here is explicit rather than an instance. -/ lemma of_equiv' {P : Type v} [add_comm_monoid P] [module R P] (h : module.free R P) (e : P ≃ₗ[R] N) : module.free R N := of_equiv e variables (R M N) instance {ι : Type v} : module.free R (ι →₀ R) := of_basis (basis.of_repr (linear_equiv.refl _ _)) instance {ι : Type v} [fintype ι] : module.free R (ι → R) := of_equiv (basis.of_repr $ linear_equiv.refl _ _).equiv_fun instance prod [module.free R N] : module.free R (M × N) := of_basis $ (choose_basis R M).prod (choose_basis R N) instance self : module.free R R := of_basis $ basis.singleton unit R @[priority 100] instance of_subsingleton [subsingleton N] : module.free R N := of_basis (basis.empty N : basis pempty R N) instance dfinsupp {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (Π₀ i, M i) := of_basis $ dfinsupp.basis $ λ i, choose_basis R (M i) instance direct_sum {ι : Type*} (M : ι → Type*) [Π (i : ι), add_comm_monoid (M i)] [Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] : module.free R (⨁ i, M i) := module.free.dfinsupp R M end semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M] variables [add_comm_group N] [module R N] [module.free R N] instance tensor : module.free R (M ⊗[R] N) := of_equiv' (of_equiv' (finsupp.free R) (finsupp_tensor_finsupp' R _ _).symm) (tensor_product.congr (choose_basis R M).repr (choose_basis R N).repr).symm end comm_ring section division_ring variables [division_ring R] [add_comm_group M] [module R M] @[priority 100] instance of_division_ring : module.free R M := of_basis (basis.of_vector_space R M) end division_ring end module.free
5be7f93dd0d5447e18549b4b689d43dde0acc4c8
ac2987d8c7832fb4a87edb6bee26141facbb6fa0
/Mathlib/Tactic/OpenPrivate.lean
9e2aa5e5e83827f53ed003ad3c2ee70ac2f96dff
[ "Apache-2.0" ]
permissive
AurelienSaue/mathlib4
52204b9bd9d207c922fe0cf3397166728bb6c2e2
84271fe0875bafdaa88ac41f1b5a7c18151bd0d5
refs/heads/master
1,689,156,096,545
1,629,378,840,000
1,629,378,840,000
389,648,603
0
0
Apache-2.0
1,627,307,284,000
1,627,307,284,000
null
UTF-8
Lean
false
false
4,734
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Lean.Elab.Command import Lean.Util.FoldConsts open Lean Parser.Tactic Elab Command namespace Lean def Meta.collectPrivateIn [Monad m] [MonadEnv m] [MonadError m] (n : Name) (set := NameSet.empty) : m NameSet := do let c ← getConstInfo n pure $ Expr.foldConsts c.value! set fun c a => if isPrivateName c then a.insert c else a def Environment.moduleIdxForModule? (env : Environment) (mod : Name) : Option ModuleIdx := (env.allImportedModuleNames.indexOf? mod).map fun idx => idx.val instance : DecidableEq ModuleIdx := instDecidableEqNat def Environment.declsInModuleIdx (env : Environment) (idx : ModuleIdx) : List Name := env.const2ModIdx.fold (fun acc n i => if i = idx then n :: acc else acc) [] namespace Elab.Command def elabOpenPrivateLike (ids : Array Syntax) (tgts mods : Option (Array Syntax)) (f : (priv full user : Name) → CommandElabM Name) : CommandElabM Unit := do let mut names := NameSet.empty for tgt in tgts.getD #[] do let n ← resolveGlobalConstNoOverload tgt names ← Meta.collectPrivateIn n names for mod in mods.getD #[] do let some modIdx ← (← getEnv).moduleIdxForModule? mod.getId | throwError "unknown module {mod}" for declName in (← getEnv).declsInModuleIdx modIdx do if isPrivateName declName then names := names.insert declName let appendNames (msg : String) : String := do let mut msg := msg for c in names do if let some name := privateToUserName? c then msg := msg ++ s!"{name}\n" msg if ids.isEmpty && !names.isEmpty then logInfo (appendNames "found private declarations:\n") let mut decls := #[] for n in ids do let n := n.getId let mut found := [] for c in names do if n.isSuffixOf c then found := c::found match found with | [] => throwError (appendNames s!"'{n}' not found in the provided declarations:\n") | [c] => if let some name := privateToUserName? c then let new ← f c name n decls := decls.push (OpenDecl.explicit n new) else unreachable! | _ => throwError s!"provided name is ambiguous: found {found.map privateToUserName?}" modifyScope fun scope => do let mut openDecls := scope.openDecls for decl in decls do openDecls := decl::openDecls { scope with openDecls := openDecls } syntax (name := openPrivate) "open private" ident* ("in" ident*)? ("from" ident*)? : command /-- The command `open private a b c in foo bar` will look for private definitions named `a`, `b`, `c` in declarations `foo` and `bar` and open them in the current scope. This does not make the definitions public, but rather makes them accessible in the current section by the short name `a` instead of the (unnameable) internal name for the private declaration, something like `_private.Other.Module.0.Other.Namespace.foo.a`, which cannot be typed directly because of the `0` name component. It is also possible to specify the module instead with `open private a b c from Other.Module`. -/ @[commandElab openPrivate] def elabOpenPrivate : CommandElab | `(open private $ids* $[in $tgts*]? $[from $mods*]?) => elabOpenPrivateLike ids tgts mods fun c _ _ => c | _ => throwUnsupportedSyntax syntax (name := exportPrivate) "export private" ident* ("in" ident*)? ("from" ident*)? : command /-- The command `export private a b c in foo bar` is similar to `open private`, but instead of opening them in the current scope it will create public aliases to the private definition. The definition will exist at exactly the original location and name, as if the `private` keyword was not used originally. It will also open the newly created alias definition under the provided short name, like `open private`. It is also possible to specify the module instead with `export private a b c from Other.Module`. -/ @[commandElab exportPrivate] def elabExportPrivate : CommandElab | `(export private $ids* $[in $tgts*]? $[from $mods*]?) => elabOpenPrivateLike ids tgts mods fun c name _ => do let cinfo ← getConstInfo c if (← getEnv).contains name then throwError s!"'{name}' has already been declared" let decl := Declaration.defnDecl { name := name, levelParams := cinfo.levelParams, type := cinfo.type, value := mkConst c (cinfo.levelParams.map mkLevelParam), hints := ReducibilityHints.abbrev, safety := if cinfo.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } addDecl decl compileDecl decl name | _ => throwUnsupportedSyntax end Elab.Command end Lean
a677852b52925f12cf9efa63f9fc8177f049ed84
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/prover.lean
80d17b0bd46d451fe7f59c0040ca236e6125905a
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
7,653
lean
import super.prover_state super.selection super.inferences.distinct super.inferences.resolution super.inferences.clausify super.inferences.empty_clause super.inferences.subsumption super.inferences.superposition super.inferences.factoring super.inferences.inhabited super.inferences.demod super.eqn_lemmas namespace super open native tactic meta def default_preprocessing_rules : list preprocessing_rule := [ preprocessing.empty_clause, preprocessing.clausify, preprocessing.distinct, preprocessing.inhabited, preprocessing.pos_refl, preprocessing.neg_refl, preprocessing.flip_eq, preprocessing.distinct, preprocessing.subsumption_interreduction -- preprocessing.forward_subsumption, ] meta def default_simplification_rules : list simplification_rule := [ simplification.forward_demod, simplification.pos_refl, simplification.neg_refl, simplification.forward_subsumption ] meta def default_inference_rules : list inference_rule := [ inference.backward_subsumption, inference.backward_demod, inference.resolution, inference.factoring, inference.forward_superposition, inference.backward_superposition, inference.unify_eq ] meta structure options := (literal_selection : literal_selection_strategy := selection21) (clause_selection : clause_selection_strategy := age_weight_clause_selection 3 4) (simpl_rules : list simplification_rule := default_simplification_rules) (inf_rules : list inference_rule := default_inference_rules) (preproc_rules : list preprocessing_rule := default_preprocessing_rules) meta def do_simplification (opts : options) (given : derived_clause) : prover (option derived_clause) := do cls : option clause ← opts.simpl_rules.mfoldl (λ cls sr, match (cls : option clause) with | some cls := sr cls | none := pure none end) (some given.cls), pure $ cls.map $ λ cls, { cls := cls, ..given } meta def do_preprocessing (opts : options) : list clause → prover (list clause) | newly_derived := do newly_derived ← opts.preproc_rules.mfoldl (λ cls pr, pr cls) newly_derived, if ¬ newly_derived.existsb (λ c : clause, c.ty.literals = []) then pure newly_derived else do newly_derived ← preprocessing.empty_clause newly_derived, if ¬ newly_derived.existsb (λ c : clause, c.ty.literals = []) then do_preprocessing newly_derived else pure newly_derived declare_trace super meta def main_loop (opts : options) : list clause → ℕ → prover (option expr) | newly_derived n := do newly_derived ← do_preprocessing opts newly_derived, let derived_empty_clauses := newly_derived.filter (λ c, c.ty.literals = []), match derived_empty_clauses with | (c::_) := do c ← c.instantiate_mvars, c.check, prf ← unfold_defs c.prf, type_check prf, state_t.lift $ infer_type prf >>= is_def_eq `(false), pure prf | _ := do newly_derived.mmap' (add_passive opts.literal_selection), passive_size ← rb_map.size <$> get_passive, if passive_size = 0 then do act ← get_active, tactic.trace act.values, pure none -- saturation else do given_id ← opts.clause_selection n, given ← consume_passive given_id, given ← do_simplification opts given, match given with | none := main_loop [] (n+1) | some given := do if given.cls.literals = [] then main_loop [given.cls] (n+1) else do when (is_trace_enabled_for `super) (do act ← get_active, given ← pp given, trace $ "[a=" ++ to_string act.size ++ ",p=" ++ to_string passive_size ++ "] " ++ to_string given), given.cls.check, given ← intern_derived given, add_active given, given' ← given.clone, newly_derived ← list.join <$> opts.inf_rules.mmap (λ ir, ir given'), main_loop newly_derived (n+1) end end meta def main (opts : options) (initial : list clause) : tactic (option expr) := do initial ← initial.mmap clause.clone, -- work around local context restriction prod.fst <$> state_t.run (main_loop opts initial 0) prover_state.initial meta def with_ground_mvars {α} (tac : tactic α) : tactic α := do reverted_goal ← tactic.retrieve (unfreeze_local_instances >> revert_all >> target), reverted_goal ← instantiate_mvars reverted_goal, mvars ← reverted_goal.sorted_mvars, lcs ← mk_locals_core mvars, let univ_mvars := (reverted_goal.mk_app lcs).univ_meta_vars.to_list, ups ← univ_mvars.mmap (λ _, mk_fresh_name), (goal::goals) ← get_goals, (res, proof) ← tactic.retrieve (do (mvars.zip lcs).mmap' (λ ⟨m, lc⟩, unify m lc), (univ_mvars.zip ups).mmap (λ ⟨m, up⟩, unify_level (level.mvar m) (level.param up)), set_goals [goal], instantiate_mvars_in_target, res ← tac, done, proof ← instantiate_mvars goal, pure (res, proof)), let proof := (proof.abstract_locals (lcs.map expr.local_uniq_name)).instantiate_vars mvars, let proof := proof.instantiate_univ_params ((ups.zip univ_mvars).map (λ ⟨up, m⟩, (up, level.mvar m))), exact proof, pure res meta def solve (opts : options) (initial : list clause) : tactic unit := do some empty_clause ← main opts initial | fail "saturation", (target >>= is_def_eq `(false)) <|> exfalso, exact empty_clause meta def intros' : tactic (list expr) := (do x ← intro_core `_, xs ← intros', pure (x::xs)) <|> pure [] noncomputable lemma {u} super_contradiction {α : Sort u} (h : (α → false) → false) : α := match classical.type_decidable α with | psum.inl a := a | psum.inr nota := @false.rec _ (h nota) end meta def better_contradiction : tactic expr := tactic.by_contradiction `h <|> (applyc ``super_contradiction >> intro1) meta def solve_with_goal (opts : options) (initial : list clause) : tactic unit := do classical, hs ← intros', tgt ← target, hs ← if tgt = `(false) then pure hs else (::) <$> better_contradiction <*> pure hs, initial ← (++ initial) <$> hs.mmap clause.of_proof, -- FIXME: happens e.g. with eq.mpr initial ← initial.mfilter (λ c, do is_ok ← succeeds c.check, if is_ok then pure tt else do trace "discarding clause, invalid type", pure ff), some empty_clause ← main opts initial | fail "saturation", exact empty_clause meta def aux_lemma_clauses_of_pexpr_name (n : name) : tactic (list clause) := do p ← resolve_name n, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | expr.const n _ := get_aux_lemma_clauses n | _ := pure [] end meta def aux_lemma_clauses_of_pexpr : pexpr → tactic (list clause) | (expr.const n _) := aux_lemma_clauses_of_pexpr_name n | (expr.local_const n _ _ _) := aux_lemma_clauses_of_pexpr_name n | _ := pure [] meta def clauses_of_simp_arg_type : simp_arg_type → tactic (list clause) | simp_arg_type.all_hyps := do lctx ← local_context, lctx.mmap clause.of_proof | (simp_arg_type.except _) := fail "super [-foo] not supported" | (simp_arg_type.symm_expr e) := clauses_of_simp_arg_type (simp_arg_type.expr e) | (simp_arg_type.expr e) := do eqn_lems ← aux_lemma_clauses_of_pexpr e, cls ← tactic.retrieve (to_expr e >>= clause.of_proof >>= clause.pack) >>= packed_clause.unpack, pure (cls :: eqn_lems) meta def clauses_of_simp_arg_type_list (simp_args : list simp_arg_type) : tactic (list clause) := list.join <$> simp_args.mmap clauses_of_simp_arg_type end super namespace tactic.interactive open lean.parser open interactive open interactive.types open tactic -- TODO: show unused arguments meta def super (args : parse simp_arg_list) (opts : super.options := {}) : tactic unit := _root_.super.with_ground_mvars $ do cs ← _root_.super.clauses_of_simp_arg_type_list args, _root_.super.solve_with_goal opts cs end tactic.interactive
213fbf26ef78fb8efb04e8289503817efddc43f6
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/control/conditional.lean
206cdad08f8e85529a744459bc59b94dc96de93e
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
1,077
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.control.monad init.data.option.basic universes u v class HasToBool (α : Type u) := (toBool : α → Bool) export HasToBool (toBool) instance : HasToBool Bool := ⟨id⟩ instance {α} : HasToBool (Option α) := ⟨Option.toBool⟩ @[macroInline] def bool {β : Type u} {α : Type v} [HasToBool β] (f t : α) (b : β) : α := match toBool b with | true => t | false => f @[macroInline] def orM {m : Type u → Type v} {β : Type u} [Monad m] [HasToBool β] (x y : m β) : m β := do b ← x; match toBool b with | true => pure b | false => y @[macroInline] def andM {m : Type u → Type v} {β : Type u} [Monad m] [HasToBool β] (x y : m β) : m β := do b ← x; match toBool b with | true => y | false => pure b infixl ` <||> `:30 := orM infixl ` <&&> `:35 := andM @[macroInline] def notM {m : Type → Type v} [Applicative m] (x : m Bool) : m Bool := not <$> x
5c7630745625444e9fba9b406bfb26a7161af867
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/data/equiv/ring.lean
7b4b91ad819ceb00402b4d30b32b8c51e04ecc29
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
12,055
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, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /-- An equivalence between two (semi)rings that preserves the algebraic structure. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv /-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_equiv /-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_add_equiv /-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_mul_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe_fun (f : R ≃+* S) : f.to_fun = f := rfl /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ @[norm_cast] lemma coe_mul_equiv (f : R ≃+* S) (a : R) : (f : R ≃* S) a = f a := rfl @[norm_cast] lemma coe_add_equiv (f : R ≃+* S) (a : R) : (f : R ≃+ S) a = f a := rfl variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩ variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } @[simp] lemma trans_apply {A B C : Type*} [semiring A] [semiring B] [semiring C] (e : A ≃+* B) (f : B ≃+* C) (a : A) : e.trans f a = f (e a) := rfl protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring section semiring variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] [semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ @[norm_cast] lemma coe_ring_hom (f : R ≃+* S) (a : R) : (f : R →+* S) a = f a := rfl lemma coe_ring_hom_inj_iff {R S : Type*} [semiring R] [semiring S] (f g : R ≃+* S) : f = g ↔ (f : R →+* S) = g := ⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩ /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl /-- Construct an equivalence of rings from homomorphisms in both directions, which are inverses. -/ def of_hom_inv (hom : R →+* S) (inv : S →+* R) (hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) : R ≃+* S := { inv_fun := inv, left_inv := λ x, ring_hom.congr_fun hom_inv_id x, right_inv := λ x, ring_hom.congr_fun inv_hom_id x, ..hom } @[simp] lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) : (of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl @[simp] lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) : (of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] @[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx) (λ hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by λ g h, ring_equiv.trans h g. This means that multiplication agrees with composition, (g*h)(x) = g (h x) . -/ instance : group (ring_aut R) := by refine_struct { mul := λ g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R →* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R →* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R →* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut namespace equiv variables (K : Type*) [division_ring K] /-- In a division ring `K`, the unit group `units K` is equivalent to the subtype of nonzero elements. -/ -- TODO: this might already exist elsewhere for `group_with_zero` -- deduplicate or generalize def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} := ⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
b0404b47f0bca761c4829bbda884c00b3318b0c4
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/linear_algebra/finsupp.lean
a5b054ded5d5356397a305588b3dc3a88fe02f63
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
15,713
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `α →₀ M`. -/ import data.finsupp linear_algebra.basic noncomputable theory local attribute [instance, priority 10] classical.prop_decidable open lattice set linear_map submodule namespace finsupp variables {α : Type*} {M : Type*} {R : Type*} variables [ring R] [add_comm_group M] [module R M] def lsingle (a : α) : M →ₗ[R] (α →₀ M) := ⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩ def lapply (a : α) : (α →₀ M) →ₗ[R] M := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩ section lsubtype_domain variables (s : set α) def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot.2 (injective_single a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem _ a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint_mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl s) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl t) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (set.singleton_subset_iff.2 h) lemma supported_eq_span_single [has_one M] (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), add := λ l₁ l₂, filter_add, smul := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section set_option class.instance_max_depth 50 @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l, apply subtype.coe_ext.2, simp, ext a, by_cases a ∈ s, { simp [h] }, { rw [filter_apply_neg (λ x, x ∈ s) _ h], exact ((mem_supported' R l.1).1 l.2 a h).symm } end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := begin have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s), rw [restrict_dom_comp_subtype, linear_map.range_id] at this, exact eq_top_mono (submodule.map_mono le_top) this.symm end theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, rw mem_coe, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, haveI := classical.dec_pred (λ x, ∃ i, x ∈ s i), by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) }, { rw filter_single_of_neg, { simp }, { exact h } } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := begin refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _, simp [le_def, infi_coe, set.subset_def], exact λ l, set.subset_Inter end section set_option class.instance_max_depth 37 def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := (restrict_support_equiv s).to_linear_equiv begin show is_linear_map R ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))), exact linear_map.is_linear _ end end def lsum (f : α → R →ₗ[R] M) : (α →₀ R) →ₗ[R] M := ⟨λ d, d.sum (λ i, f i), assume d₁ d₂, by simp [sum_add_index], assume a d, by simp [sum_smul_index, smul_sum, -smul_eq_mul, smul_eq_mul.symm]⟩ @[simp] theorem lsum_apply (f : α → R →ₗ[R] M) (l : α →₀ R) : (finsupp.lsum f : (α →₀ R) →ₗ M) l = l.sum (λ b, f b) := rfl section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [inhabited α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_group M'] [module R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), { exact λ i hi, submodule.smul _ _ (subset_span (mem_range_self i)) }, apply_instance }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M}: x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _) theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := begin ext l, simp [total_apply], rw sum_map_domain_index; simp [add_smul], end lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl end total protected def dom_lcongr {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e).to_linear_equiv begin change is_linear_map R (lmap_domain M R e : (α₁ →₀ M) →ₗ[R] (α₂ →₀ M)), exact linear_map.is_linear _ end noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end end finsupp
ea99a17423546e2ad822ec47c3b523d5f9ecf72c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/cancel_leads.lean
e3c969d48bda85f4c913d4e97cccc2e89b3fc4eb
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,079
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.degree.definitions import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Cancel the leading terms of two polynomials ## Definition * `cancel_leads p q`: the polynomial formed by multiplying `p` and `q` by monomials so that they have the same leading term, and then subtracting. ## Main Results The degree of `cancel_leads` is less than that of the larger of the two polynomials being cancelled. Thus it is useful for induction or minimal-degree arguments. -/ namespace polynomial /-- `cancel_leads p q` is formed by multiplying `p` and `q` by monomials so that they have the same leading term, and then subtracting. -/ def cancel_leads {R : Type u_1} [comm_ring R] (p : polynomial R) (q : polynomial R) : polynomial R := coe_fn C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q - coe_fn C (leading_coeff q) * X ^ (nat_degree q - nat_degree p) * p @[simp] theorem neg_cancel_leads {R : Type u_1} [comm_ring R] {p : polynomial R} {q : polynomial R} : -cancel_leads p q = cancel_leads q p := neg_sub (coe_fn C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) (coe_fn C (leading_coeff q) * X ^ (nat_degree q - nat_degree p) * p) theorem dvd_cancel_leads_of_dvd_of_dvd {R : Type u_1} [comm_ring R] {p : polynomial R} {q : polynomial R} {r : polynomial R} (pq : p ∣ q) (pr : p ∣ r) : p ∣ cancel_leads q r := dvd_sub (dvd.trans pr (dvd.intro_left (coe_fn C (leading_coeff q) * X ^ (nat_degree q - nat_degree r)) rfl)) (dvd.trans pq (dvd.intro_left (coe_fn C (leading_coeff r) * X ^ (nat_degree r - nat_degree q)) rfl)) theorem nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree {R : Type u_1} [integral_domain R] {p : polynomial R} {q : polynomial R} (h : nat_degree p ≤ nat_degree q) (hq : 0 < nat_degree q) : nat_degree (cancel_leads p q) < nat_degree q := sorry
330e421d8bd0aeefcd10406376c6f922d48a3952
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Elab/Deriving/BEq.lean
58105bb064cf501e13c423d5fcb6959dfa1bda72
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,448
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.Transform import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util namespace Lean.Elab.Deriving.BEq open Lean.Parser.Term open Meta def mkBEqHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do mkHeader ctx `BEq 2 indVal def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkElseAlt : TermElabM Syntax := do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) patterns := patterns.push (← `(_)) patterns := patterns.push (← `(_)) let altRhs ← `(false) `(matchAltExpr| | $[$patterns:term],* => $altRhs:term) mkAlts : TermElabM (Array Syntax) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs1 := #[] let mut ctorArgs2 := #[] let mut rhs ← `(true) -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.numParams] do ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] if type.containsFVar x.fvarId! then -- If resulting type depends on this field, we don't need to compare ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) else let a := mkIdent (← mkFreshUserName `a) let b := mkIdent (← mkFreshUserName `b) ctorArgs1 := ctorArgs1.push a ctorArgs2 := ctorArgs2.push b if (← inferType x).isAppOf indVal.name then rhs ← `($rhs && $(mkIdent auxFunName):ident $a:ident $b:ident) else rhs ← `($rhs && $a:ident == $b:ident) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs1:term*)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs2:term*)) `(matchAltExpr| | $[$patterns:term],* => $rhs:term) alts := alts.push alt alts := alts.push (← mkElseAlt) return alts def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do let auxFunName ← ctx.auxFunNames[i] let indVal ← ctx.typeInfos[i] let header ← mkBEqHeader ctx indVal let mut body ← mkMatch ctx header indVal auxFunName if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx `BEq header.argNames body ← mkLet letDecls body let binders := header.binders if ctx.usePartial then `(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : Bool := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : Bool := $body:term) def mkMutualBlock (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual set_option match.ignoreUnusedAlts true $auxDefs:command* end) private def mkBEqInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "beq" declNames[0] let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `BEq declNames) trace[Elab.Deriving.beq]! "\n{cmds}" return cmds open Command def mkBEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) && declNames.size > 0 then let cmds ← liftTermElabM none <| mkBEqInstanceCmds declNames cmds.forM elabCommand return true else return false builtin_initialize registerBuiltinDerivingHandler `BEq mkBEqInstanceHandler registerTraceClass `Elab.Deriving.beq end Lean.Elab.Deriving.BEq
ec7b77673f634cc899abcf87ecbded1bb3436822
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/algebra/classes.lean
378cca49f35e518a915e77c1fd0eb90e2a830e4c
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
13,152
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.logic init.data.ordering.basic universes u v @[algebra] class is_symm_op (α : Type u) (β : out_param (Type v)) (op : α → α → β) : Prop := (symm_op : ∀ a b, op a b = op b a) @[algebra] class is_commutative (α : Type u) (op : α → α → α) : Prop := (comm : ∀ a b, op a b = op b a) instance is_symm_op_of_is_commutative (α : Type u) (op : α → α → α) [is_commutative α op] : is_symm_op α α op := {symm_op := is_commutative.comm} @[algebra] class is_associative (α : Type u) (op : α → α → α) : Prop := (assoc : ∀ a b c, op (op a b) c = op a (op b c)) @[algebra] class is_left_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_id : ∀ a, op o a = a) @[algebra] class is_right_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_id : ∀ a, op a o = a) @[algebra] class is_left_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_null : ∀ a, op o a = o) @[algebra] class is_right_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_null : ∀ a, op a o = o) @[algebra] class is_left_cancel (α : Type u) (op : α → α → α) : Prop := (left_cancel : ∀ a b c, op a b = op a c → b = c) @[algebra] class is_right_cancel (α : Type u) (op : α → α → α) : Prop := (right_cancel : ∀ a b c, op a b = op c b → a = c) @[algebra] class is_idempotent (α : Type u) (op : α → α → α) : Prop := (idempotent : ∀ a, op a a = a) @[algebra] class is_left_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (left_distrib : ∀ a b c, op₁ a (op₂ b c) = op₂ (op₁ a b) (op₁ a c)) @[algebra] class is_right_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (right_distrib : ∀ a b c, op₁ (op₂ a b) c = op₂ (op₁ a c) (op₁ b c)) @[algebra] class is_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop := (left_inv : ∀ a, op (inv a) a = o) @[algebra] class is_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop := (right_inv : ∀ a, op a (inv a) = o) @[algebra] class is_cond_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop := (left_inv : ∀ a, p a → op (inv a) a = o) @[algebra] class is_cond_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop := (right_inv : ∀ a, p a → op a (inv a) = o) @[algebra] class is_distinct (α : Type u) (a : α) (b : α) : Prop := (distinct : a ≠ b) /- -- The following type class doesn't seem very useful, a regular simp lemma should work for this. class is_inv (α : Type u) (β : Type v) (f : α → β) (g : out β → α) : Prop := (inv : ∀ a, g (f a) = a) -- The following one can also be handled using a regular simp lemma class is_idempotent (α : Type u) (f : α → α) : Prop := (idempotent : ∀ a, f (f a) = f a) -/ /-- `is_irrefl X r` means the binary relation `r` on `X` is irreflexive (that is, `r x x` never holds). -/ @[algebra] class is_irrefl (α : Type u) (r : α → α → Prop) : Prop := (irrefl : ∀ a, ¬ r a a) /-- `is_refl X r` means the binary relation `r` on `X` is reflexive. -/ @[algebra] class is_refl (α : Type u) (r : α → α → Prop) : Prop := (refl : ∀ a, r a a) /-- `is_symm X r` means the binary relation `r` on `X` is symmetric. -/ @[algebra] class is_symm (α : Type u) (r : α → α → Prop) : Prop := (symm : ∀ a b, r a b → r b a) /-- The opposite of a symmetric relation is symmetric. -/ instance is_symm_op_of_is_symm (α : Type u) (r : α → α → Prop) [is_symm α r] : is_symm_op α Prop r := {symm_op := λ a b, propext $ iff.intro (is_symm.symm a b) (is_symm.symm b a)} /-- `is_asymm X r` means that the binary relation `r` on `X` is asymmetric, that is, `r a b → ¬ r b a`. -/ @[algebra] class is_asymm (α : Type u) (r : α → α → Prop) : Prop := (asymm : ∀ a b, r a b → ¬ r b a) /-- `is_antisymm X r` means the binary relation `r` on `X` is antisymmetric. -/ @[algebra] class is_antisymm (α : Type u) (r : α → α → Prop) : Prop := (antisymm : ∀ a b, r a b → r b a → a = b) /-- `is_trans X r` means the binary relation `r` on `X` is transitive. -/ @[algebra] class is_trans (α : Type u) (r : α → α → Prop) : Prop := (trans : ∀ a b c, r a b → r b c → r a c) /-- `is_total X r` means that the binary relation `r` on `X` is total, that is, that for any `x y : X` we have `r x y` or `r y x`.-/ @[algebra] class is_total (α : Type u) (r : α → α → Prop) : Prop := (total : ∀ a b, r a b ∨ r b a) /-- `is_preorder X r` means that the binary relation `r` on `X` is a pre-order, that is, reflexive and transitive. -/ @[algebra] class is_preorder (α : Type u) (r : α → α → Prop) extends is_refl α r, is_trans α r : Prop. /-- `is_total_preorder X r` means that the binary relation `r` on `X` is total and a preorder. -/ @[algebra] class is_total_preorder (α : Type u) (r : α → α → Prop) extends is_trans α r, is_total α r : Prop. /-- Every total pre-order is a pre-order. -/ instance is_total_preorder_is_preorder (α : Type u) (r : α → α → Prop) [s : is_total_preorder α r] : is_preorder α r := {trans := s.trans, refl := λ a, or.elim (@is_total.total _ r _ a a) id id} @[algebra] class is_partial_order (α : Type u) (r : α → α → Prop) extends is_preorder α r, is_antisymm α r : Prop. @[algebra] class is_linear_order (α : Type u) (r : α → α → Prop) extends is_partial_order α r, is_total α r : Prop. @[algebra] class is_equiv (α : Type u) (r : α → α → Prop) extends is_preorder α r, is_symm α r : Prop. @[algebra] class is_per (α : Type u) (r : α → α → Prop) extends is_symm α r, is_trans α r : Prop. @[algebra] class is_strict_order (α : Type u) (r : α → α → Prop) extends is_irrefl α r, is_trans α r : Prop. @[algebra] class is_incomp_trans (α : Type u) (lt : α → α → Prop) : Prop := (incomp_trans : ∀ a b c, (¬ lt a b ∧ ¬ lt b a) → (¬ lt b c ∧ ¬ lt c b) → (¬ lt a c ∧ ¬ lt c a)) @[algebra] class is_strict_weak_order (α : Type u) (lt : α → α → Prop) extends is_strict_order α lt, is_incomp_trans α lt : Prop. @[algebra] class is_trichotomous (α : Type u) (lt : α → α → Prop) : Prop := (trichotomous : ∀ a b, lt a b ∨ a = b ∨ lt b a) @[algebra] class is_strict_total_order (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_weak_order α lt : Prop. instance eq_is_equiv (α : Type u) : is_equiv α (=) := {symm := @eq.symm _, trans := @eq.trans _, refl := eq.refl} section variables {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r lemma irrefl [is_irrefl α r] (a : α) : ¬ a ≺ a := is_irrefl.irrefl a lemma refl [is_refl α r] (a : α) : a ≺ a := is_refl.refl a lemma trans [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := is_trans.trans _ _ _ lemma symm [is_symm α r] {a b : α} : a ≺ b → b ≺ a := is_symm.symm _ _ lemma antisymm [is_antisymm α r] {a b : α} : a ≺ b → b ≺ a → a = b := is_antisymm.antisymm _ _ lemma asymm [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := is_asymm.asymm _ _ lemma trichotomous [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := is_trichotomous.trichotomous lemma incomp_trans [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := is_incomp_trans.incomp_trans _ _ _ instance is_asymm_of_is_trans_of_is_irrefl [is_trans α r] [is_irrefl α r] : is_asymm α r := ⟨λ a b h₁ h₂, absurd (trans h₁ h₂) (irrefl a)⟩ section explicit_relation_variants variable (r) @[elab_simple] lemma irrefl_of [is_irrefl α r] (a : α) : ¬ a ≺ a := irrefl a @[elab_simple] lemma refl_of [is_refl α r] (a : α) : a ≺ a := refl a @[elab_simple] lemma trans_of [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := trans @[elab_simple] lemma symm_of [is_symm α r] {a b : α} : a ≺ b → b ≺ a := symm @[elab_simple] lemma asymm_of [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := asymm @[elab_simple] lemma total_of [is_total α r] (a b : α) : a ≺ b ∨ b ≺ a := is_total.total _ _ @[elab_simple] lemma trichotomous_of [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := trichotomous @[elab_simple] lemma incomp_trans_of [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := incomp_trans end explicit_relation_variants end namespace strict_weak_order section parameters {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r def equiv (a b : α) : Prop := ¬ a ≺ b ∧ ¬ b ≺ a parameter [is_strict_weak_order α r] local infix ` ≈ `:50 := equiv lemma erefl (a : α) : a ≈ a := ⟨irrefl a, irrefl a⟩ lemma esymm {a b : α} : a ≈ b → b ≈ a := λ ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ lemma etrans {a b c : α} : a ≈ b → b ≈ c → a ≈ c := incomp_trans lemma not_lt_of_equiv {a b : α} : a ≈ b → ¬ a ≺ b := λ h, h.1 lemma not_lt_of_equiv' {a b : α} : a ≈ b → ¬ b ≺ a := λ h, h.2 instance : is_equiv α equiv := {refl := erefl, trans := @etrans, symm := @esymm} end /- Notation for the equivalence relation induced by lt -/ notation a ` ≈[`:50 lt `]` b:50 := @equiv _ lt a b end strict_weak_order lemma is_strict_weak_order_of_is_total_preorder {α : Type u} {le : α → α → Prop} {lt : α → α → Prop} [decidable_rel le] [s : is_total_preorder α le] (h : ∀ a b, lt a b ↔ ¬ le b a) : is_strict_weak_order α lt := { trans := λ a b c hab hbc, have nba : ¬ le b a, from iff.mp (h _ _) hab, have ncb : ¬ le c b, from iff.mp (h _ _) hbc, have hab : le a b, from or.resolve_left (total_of le b a) nba, have nca : ¬ le c a, from λ hca : le c a, have hcb : le c b, from trans_of le hca hab, absurd hcb ncb, iff.mpr (h _ _) nca, irrefl := λ a hlt, absurd (refl_of le a) (iff.mp (h _ _) hlt), incomp_trans := λ a b c ⟨nab, nba⟩ ⟨nbc, ncb⟩, have hba : le b a, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nab), have hab : le a b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nba), have hcb : le c b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nbc), have hbc : le b c, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) ncb), have hac : le a c, from trans_of le hab hbc, have hca : le c a, from trans_of le hcb hba, and.intro (λ n, absurd hca (iff.mp (h _ _) n)) (λ n, absurd hac (iff.mp (h _ _) n)) } lemma lt_of_lt_of_incomp {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt] : ∀ {a b c}, lt a b → (¬ lt b c ∧ ¬ lt c b) → lt a c := λ a b c hab ⟨nbc, ncb⟩, have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hca hab) ncb, decidable.by_contradiction $ λ nac : ¬ lt a c, have ¬ lt a b ∧ ¬ lt b a, from incomp_trans_of lt ⟨nac, nca⟩ ⟨ncb, nbc⟩, absurd hab this.1 lemma lt_of_incomp_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt] : ∀ {a b c}, (¬ lt a b ∧ ¬ lt b a) → lt b c → lt a c := λ a b c ⟨nab, nba⟩ hbc, have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hbc hca) nba, decidable.by_contradiction $ λ nac : ¬ lt a c, have ¬ lt b c ∧ ¬ lt c b, from incomp_trans_of lt ⟨nba, nab⟩ ⟨nac, nca⟩, absurd hbc this.1 lemma eq_of_incomp {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : (¬ lt a b ∧ ¬ lt b a) → a = b := λ ⟨nab, nba⟩, match trichotomous_of lt a b with | or.inl hab := absurd hab nab | or.inr (or.inl hab) := hab | or.inr (or.inr hba) := absurd hba nba end lemma eq_of_eqv_lt {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : a ≈[lt] b → a = b := eq_of_incomp lemma incomp_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : (¬ lt a b ∧ ¬ lt b a) ↔ a = b := iff.intro eq_of_incomp (λ hab, eq.subst hab (and.intro (irrefl_of lt a) (irrefl_of lt a))) lemma eqv_lt_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : a ≈[lt] b ↔ a = b := incomp_iff_eq a b lemma not_lt_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_order α lt] {a b} : lt a b → ¬ lt b a := λ h₁ h₂, absurd (trans_of lt h₁ h₂) (irrefl_of lt _)
adb0aea5443f1c7f16dca72bedb0541060f0d172
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/ordered_ring.lean
26c0f43dd94ceae521f376a9e8234f06096cce39
[ "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
43,960
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.ordered_group set_option old_structure_cmd true universe u variable {α : Type u} /-- An `ordered_semiring α` is a semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (zero_le_one : 0 ≤ (1 : α)) (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} lemma zero_le_one : 0 ≤ (1:α) := ordered_semiring.zero_le_one lemma zero_le_two : 0 ≤ (2:α) := add_nonneg zero_le_one zero_le_one section nontrivial variables [nontrivial α] lemma zero_lt_one : 0 < (1 : α) := lt_of_le_of_ne zero_le_one zero_ne_one lemma zero_lt_two : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma one_le_two : 1 ≤ (2:α) := one_lt_two.le lemma zero_lt_three : 0 < (3:α) := add_pos zero_lt_two zero_lt_one lemma zero_lt_four : 0 < (4:α) := add_pos zero_lt_two zero_lt_two end nontrivial lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ lemma mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin cases classical.em (b ≤ a), { simp [h.antisymm h₁] }, cases classical.em (c ≤ 0), { simp [h_1.antisymm h₂] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1)).le, end lemma mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin cases classical.em (b ≤ a), { simp [h.antisymm h₁] }, cases classical.em (c ≤ 0), { simp [h_1.antisymm h₂] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1)).le, end -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_lt_mul'' (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (λ b0, mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma le_mul_of_one_le_right (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_left (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb section variable [nontrivial α] lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } end lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := begin nontriviality, exact bit1_pos h.le, end lemma one_lt_mul (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, exact (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma mul_le_one (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma one_lt_mul_of_le_of_lt (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) end lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := begin nontriviality, calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le end lemma mul_le_of_le_one_right (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_left (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : mul_le_of_le_one_left hb0 ha ... < 1 : hb end ordered_semiring /-- A `linear_ordered_semiring α` is a nontrivial semiring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ -- It's not entirely clear we should assume `nontrivial` at this point; -- it would be reasonable to explore changing this, -- but be warned that the instances involving `domain` may cause -- typeclass search loops. @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α, nontrivial α section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} -- `norm_num` expects the lemma stating `0 < 1` to have a single typeclass argument -- (see `norm_num.prove_pos_nat`). -- Rather than working out how to relax that assumption, -- we provide a synonym for `zero_lt_one` (which needs both `ordered_semiring α` and `nontrivial α`) -- with only a `linear_ordered_semiring` typeclass argument. lemma zero_lt_one' : 0 < (1 : α) := zero_lt_one lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, _⟩, contrapose! hab, exact mul_nonpos_of_nonneg_of_nonpos ha.le hab }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, _⟩, contrapose! hab, exact mul_nonpos_of_nonpos_of_nonneg ha.le hab } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≤ a * b) : (0 ≤ a ∧ 0 ≤ b) ∨ (a ≤ 0 ∧ b ≤ 0) := begin contrapose! hab, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (hab.1 ha.le), ((hab.1 le_rfl).asymm (hab.2 le_rfl)).elim, mul_neg_of_neg_of_pos ha (hab.2 ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≤ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≤ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ λ h, h.2.not_le hb).1 lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume h2 : b ≥ 0, (mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume h2 : a ≥ 0, (mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' h.le, λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' h.le, λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } section variables [nontrivial α] @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left (zero_lt_two : 0 < (2:α))] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left (zero_lt_two : 0 < (2:α))] end lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_one_lt_right (hb : 0 < b) : 1 < a → b < b * a := (lt_mul_iff_one_lt_right hb).2 theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this h.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := lt_of_not_ge (λ ha, absurd h (mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := lt_of_not_ge (λ hb, absurd h (mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) lemma exists_lt_mul_self (a : α) : ∃ x : α, a < x * x := begin by_cases ha : 0 ≤ a, { use (a + 1), calc a = a * 1 : by rw mul_one ... < (a + 1) * (a + 1) : mul_lt_mul (lt_add_one _) (le_add_of_nonneg_left ha) zero_lt_one (add_nonneg ha zero_le_one) }, { rw not_le at ha, use 1, calc a < 0 : ha ... < 1 * 1 : by simpa only [mul_one] using zero_lt_one' } end lemma exists_le_mul_self (a : α) : ∃ x : α, a ≤ x * x := let ⟨x, hx⟩ := exists_lt_mul_self a in ⟨x, le_of_lt hx⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c : α} @[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h @[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h lemma mul_max_of_nonneg (b c : α) (ha : 0 ≤ a) : a * max b c = max (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_max lemma mul_min_of_nonneg (b c : α) (ha : 0 ≤ a) : a * min b c = min (a * b) (a * c) := (monotone_mul_left_of_nonneg ha).map_min lemma max_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : max a b * c = max (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_max lemma min_mul_of_nonneg (a b : α) (hc : 0 ≤ c) : min a b * c = min (a * c) (b * c) := (monotone_mul_right_of_nonneg hc).map_min end linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (zero_le_one : 0 ≤ (1 : α)) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) section ordered_ring variables [ordered_ring α] {a b c : α} lemma ordered_ring.mul_nonneg (a b : α) (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin cases classical.em (a ≤ 0), { simp [le_antisymm h h₁] }, cases classical.em (b ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le h) (h₂.lt_of_not_le h_1))).left, end lemma ordered_ring.mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply lt_of_sub_pos this end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply lt_of_sub_pos this end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this end ordered_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α, nontrivial α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_add_comm_group [s : linear_ordered_ring α] : linear_ordered_add_comm_group α := { .. s } section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, contrapose! hab, cases (lt_or_gt_of_ne hab.1) with ha ha; cases (lt_or_gt_of_ne hab.2) with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. ‹linear_ordered_ring α› } @[simp] lemma abs_one : abs (1 : α) = 1 := abs_of_pos zero_lt_one @[simp] lemma abs_two : abs (2 : α) = 2 := abs_of_pos zero_lt_two lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := begin rw [abs_eq (mul_nonneg (abs_nonneg a) (abs_nonneg b))], cases le_total a 0 with ha ha; cases le_total b 0 with hb hb; simp [abs_of_nonpos, abs_of_nonneg, *] end /-- `abs` as a `monoid_hom`. -/ def abs_hom : α →* α := ⟨abs, abs_one, abs_mul⟩ lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, λ h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≤ a * b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, λ h, h.elim (and_imp.2 mul_nonneg) (and_imp.2 mul_nonneg_of_nonpos_of_nonpos)⟩ lemma mul_nonpos_iff : a * b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : α) : 0 ≤ a * a := or.elim (le_total 0 a) (assume h : a ≥ 0, mul_nonneg h h) (assume h : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos h h) lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := begin have this := neg_lt_neg (@zero_lt_one α _ _), rwa neg_zero at this end lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_squares_le {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := le_of_not_gt (λhab, (mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := ⟨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff $ mul_self_le_mul_self_iff h2 h1) $ iff.symm (lt_iff_not_ge _ _) lemma mul_self_inj {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a * a = b * b ↔ a = b := ⟨λ h3, le_antisymm ((nonneg_le_nonneg_of_squares_le h2) h3.le) $ (nonneg_le_nonneg_of_squares_le h1) h3.symm.le, λ h3, le_antisymm ((mul_self_le_mul_self h1) h3.le) $ (mul_self_le_mul_self h2) h3.symm.le⟩ @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin cases le_total 0 x, { exact mul_self_le_mul_self h h₁ }, { rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) h₂ } end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := lt_of_not_ge (λ ha, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := lt_of_not_ge (λ hb, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /-- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split; intro h, swap, { rcases h with ⟨rfl, rfl⟩, simp }, have : y * y ≤ 0, { rw [← h], apply le_add_of_nonneg_left (mul_self_nonneg x) }, have : y * y = 0 := le_antisymm this (mul_self_nonneg y), have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h }, rw mul_self_eq_zero at this, split; assumption end lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... ≥ b - c : sub_le_self _ $ (abs_nonneg _).trans h) else have habs : b - a ≤ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b ≤ c + a, from le_add_of_sub_right_le habs, sub_left_le_of_le_add habs' lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... > b - c : sub_lt_self _ ((abs_nonneg _).trans_lt h)) else have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b < c + a, from lt_add_of_sub_right_lt habs, sub_left_lt_of_lt_add habs' lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h) lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := (mul_self_add_mul_self_eq_zero.mp h).left lemma abs_eq_iff_mul_self_eq : abs a = abs b ↔ a * a = b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact (mul_self_inj (abs_nonneg a) (abs_nonneg b)).symm, end lemma abs_lt_iff_mul_self_lt : abs a < abs b ↔ a * a < b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_lt_mul_self_iff (abs_nonneg a) (abs_nonneg b) end lemma abs_le_iff_mul_self_le : abs a ≤ abs b ↔ a * a ≤ b * b := begin rw [← abs_mul_abs_self, ← abs_mul_abs_self b], exact mul_self_le_mul_self_iff (abs_nonneg a) (abs_nonneg b) end end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_comm_ring [s : linear_ordered_comm_ring α] : comm_ring α := { ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s : linear_ordered_comm_ring α] : integral_domain α := { ..linear_ordered_ring.to_domain, ..s } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_linear_ordered_semiring [d : linear_ordered_comm_ring α] : linear_ordered_semiring α := let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } section linear_ordered_comm_ring variables [linear_ordered_comm_ring α] {a b c d : α} lemma max_mul_mul_le_max_mul_max (b c : α) (ha : 0 ≤ a) (hd: 0 ≤ d) : max (a * b) (d * c) ≤ max a c * max d b := have ba : b * a ≤ max d b * max c a, from mul_le_mul (le_max_right d b) (le_max_right c a) ha (le_trans hd (le_max_left d b)), have cd : c * d ≤ max a c * max b d, from mul_le_mul (le_max_right a c) (le_max_right b d) hd (le_trans ha (le_max_left a c)), max_le (by simpa [mul_comm, max_comm] using ba) (by simpa [mul_comm, max_comm] using cd) lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg], end end linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α := (one_nonneg : nonneg 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (one_pos : pos 1) (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring [nontrivial α] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { one_pos := (pos_iff 1).mpr ⟨one_nonneg, λ h, zero_ne_one (nonneg_antisymm one_nonneg h).symm⟩, nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, classical.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, classical.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nontrivial α›, ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { one_nonneg := ((pos_iff _).mp one_pos).1, mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } /-- Construct `linear_order` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_order [decidable_pred (nonneg : α → Prop)] : linear_order α := { le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α) } /-- Construct `linear_ordered_ring` from `linear_nonneg_ring`. This is not an instance because we don't use it in `mathlib`. -/ local attribute [instance] def to_linear_ordered_ring [decidable_pred (nonneg : α → Prop)] : linear_ordered_ring α := { mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_le_one := le_of_lt $ lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α›, ..(infer_instance : ordered_add_comm_group α), ..(infer_instance : linear_order α) } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `linear_ordered_comm_ring` -/ def to_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : linear_ordered_comm_ring α := { mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) namespace canonically_ordered_semiring variables [canonically_ordered_comm_semiring α] {a b : α} open canonically_ordered_add_monoid (le_iff_exists_add) @[priority 100] -- see Note [lower instance priority] instance canonically_ordered_comm_semiring.to_no_zero_divisors : no_zero_divisors α := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ lemma mul_le_mul {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, _root_.add_assoc], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end lemma mul_le_mul_left' {b c : α} (h : b ≤ c) (a : α) : a * b ≤ a * c := mul_le_mul (le_refl a) h lemma mul_le_mul_right' {b c : α} (h : b ≤ c) (a : α) : b * a ≤ c * a := mul_le_mul h (le_refl a) /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one [nontrivial α] : (0:α) < 1 := (zero_le 1).lt_of_ne zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_semiring namespace with_top instance [nonempty α] : nontrivial (with_top α) := option.nontrivial variable [decidable_eq α] section has_mul variables [has_zero α] [has_mul α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class α] @[norm_cast] lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊤ * (b : with_top α) = ⊤ ↔ b ≠ 0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top α) * ⊤ = ⊤ ↔ a ≠ 0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end end mul_zero_class section no_zero_divisors variables [mul_zero_class α] [no_zero_divisors α] instance : no_zero_divisors (with_top α) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ end no_zero_divisors variables [canonically_ordered_comm_semiring α] private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end -- `nontrivial α` is needed here as otherwise -- we have `1 * ⊤ = ⊤` but also `= 0 * ⊤ = 0`. private lemma one_mul' [nontrivial α] : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_top.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_top.coe_one] instance [nontrivial α] : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, .. with_top.nontrivial } end with_top
391ed863f0124143daea1c6c61410c06b069c808
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/internal/functor_category.lean
8e39949a504efc9c6a072a6e8533f0e46f690dda
[ "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
7,243
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.CommMon_ import category_theory.monoidal.functor_category /-! # `Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. When `D` is a monoidal category, monoid objects in `C ⥤ D` are the same thing as functors from `C` into the monoid objects of `D`. This is formalised as: * `Mon_functor_category_equivalence : Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D` The intended application is that as `Ring ≌ Mon_ Ab` (not yet constructed!), we have `presheaf Ring X ≌ presheaf (Mon_ Ab) X ≌ Mon_ (presheaf Ab X)`, and we can model a module over a presheaf of rings as a module object in `presheaf Ab X`. ## Future work Presumably this statement is not specific to monoids, and could be generalised to any internal algebraic objects, if the appropriate framework was available. -/ universes v₁ v₂ u₁ u₂ open category_theory open category_theory.monoidal_category namespace category_theory.monoidal variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] [monoidal_category.{v₂} D] namespace Mon_functor_category_equivalence variables {C D} /-- Functor translating a monoid object in a functor category to a functor into the category of monoid objects. -/ @[simps] def functor : Mon_ (C ⥤ D) ⥤ (C ⥤ Mon_ D) := { obj := λ A, { obj := λ X, { X := A.X.obj X, one := A.one.app X, mul := A.mul.app X, one_mul' := congr_app A.one_mul X, mul_one' := congr_app A.mul_one X, mul_assoc' := congr_app A.mul_assoc X, }, map := λ X Y f, { hom := A.X.map f, one_hom' := by { rw [←A.one.naturality, tensor_unit_map], dsimp, rw [category.id_comp], }, mul_hom' := by { dsimp, rw [←A.mul.naturality, tensor_obj_map], }, }, map_id' := λ X, by { ext, dsimp, rw [category_theory.functor.map_id], }, map_comp' := λ X Y Z f g, by { ext, dsimp, rw [functor.map_comp], }, }, map := λ A B f, { app := λ X, { hom := f.hom.app X, one_hom' := congr_app f.one_hom X, mul_hom' := congr_app f.mul_hom X, }, }, } /-- Functor translating a functor into the category of monoid objects to a monoid object in the functor category -/ @[simps] def inverse : (C ⥤ Mon_ D) ⥤ Mon_ (C ⥤ D) := { obj := λ F, { X := F ⋙ Mon_.forget D, one := { app := λ X, (F.obj X).one, }, mul := { app := λ X, (F.obj X).mul, }, one_mul' := by { ext X, exact (F.obj X).one_mul, }, mul_one' := by { ext X, exact (F.obj X).mul_one, }, mul_assoc' := by { ext X, exact (F.obj X).mul_assoc, }, }, map := λ F G α, { hom := { app := λ X, (α.app X).hom, naturality' := λ X Y f, congr_arg Mon_.hom.hom (α.naturality f), }, one_hom' := by { ext x, dsimp, rw [(α.app x).one_hom], }, mul_hom' := by { ext x, dsimp, rw [(α.app x).mul_hom], }, }, } /-- The unit for the equivalence `Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D`. -/ @[simps] def unit_iso : 𝟭 (Mon_ (C ⥤ D)) ≅ functor ⋙ inverse := nat_iso.of_components (λ A, { hom := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, inv := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, }) (λ A B f, begin ext X, simp only [functor.id_map, functor.comp_map, functor_map_app_hom, Mon_.comp_hom', category.id_comp, category.comp_id, inverse_map_hom_app, nat_trans.comp_app], end) /-- The counit for the equivalence `Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D`. -/ @[simps] def counit_iso : inverse ⋙ functor ≅ 𝟭 (C ⥤ Mon_ D) := nat_iso.of_components (λ A, nat_iso.of_components (λ X, { hom := { hom := 𝟙 _ }, inv := { hom := 𝟙 _ } }) (by tidy)) (by tidy) end Mon_functor_category_equivalence open Mon_functor_category_equivalence /-- When `D` is a monoidal category, monoid objects in `C ⥤ D` are the same thing as functors from `C` into the monoid objects of `D`. -/ @[simps] def Mon_functor_category_equivalence : Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D := { functor := functor, inverse := inverse, unit_iso := unit_iso, counit_iso := counit_iso, } variables [braided_category.{v₂} D] namespace CommMon_functor_category_equivalence variables {C D} /-- Functor translating a commutative monoid object in a functor category to a functor into the category of commutative monoid objects. -/ @[simps] def functor : CommMon_ (C ⥤ D) ⥤ (C ⥤ CommMon_ D) := { obj := λ A, { obj := λ X, { mul_comm' := congr_app A.mul_comm X, ..((Mon_functor_category_equivalence C D).functor.obj A.to_Mon_).obj X, }, ..((Mon_functor_category_equivalence C D).functor.obj A.to_Mon_) }, map := λ A B f, { app := λ X, ((Mon_functor_category_equivalence C D).functor.map f).app X, }, } /-- Functor translating a functor into the category of commutative monoid objects to a commutative monoid object in the functor category -/ @[simps] def inverse : (C ⥤ CommMon_ D) ⥤ CommMon_ (C ⥤ D) := { obj := λ F, { mul_comm' := by { ext X, exact (F.obj X).mul_comm, }, ..(Mon_functor_category_equivalence C D).inverse.obj (F ⋙ CommMon_.forget₂_Mon_ D), }, map := λ F G α, (Mon_functor_category_equivalence C D).inverse.map (whisker_right α _), } /-- The unit for the equivalence `CommMon_ (C ⥤ D) ≌ C ⥤ CommMon_ D`. -/ @[simps] def unit_iso : 𝟭 (CommMon_ (C ⥤ D)) ≅ functor ⋙ inverse := nat_iso.of_components (λ A, { hom := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, inv := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, }) (λ A B f, begin ext X, dsimp, simp only [category.id_comp, category.comp_id], end) /-- The counit for the equivalence `CommMon_ (C ⥤ D) ≌ C ⥤ CommMon_ D`. -/ @[simps] def counit_iso : inverse ⋙ functor ≅ 𝟭 (C ⥤ CommMon_ D) := nat_iso.of_components (λ A, nat_iso.of_components (λ X, { hom := { hom := 𝟙 _ }, inv := { hom := 𝟙 _ } }) (by tidy)) (by tidy) end CommMon_functor_category_equivalence open CommMon_functor_category_equivalence /-- When `D` is a braided monoidal category, commutative monoid objects in `C ⥤ D` are the same thing as functors from `C` into the commutative monoid objects of `D`. -/ @[simps] def CommMon_functor_category_equivalence : CommMon_ (C ⥤ D) ≌ C ⥤ CommMon_ D := { functor := functor, inverse := inverse, unit_iso := unit_iso, counit_iso := counit_iso, } end category_theory.monoidal
d84f7a28ef22c7cdb583275405f7fead77af15bc
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_2204.lean
3c36b1f02a4cfe422716dce35986134e92ed96a5
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
847
lean
variables {p q : Prop} -- BEGIN theorem not_or_of_not_and_not : ¬p ∧ ¬q → ¬(p ∨ q) := begin assume h₁ : ¬p ∧ ¬q, -- Assume `h₁ : ¬p ∧ ¬q`. By implication introduction, it suffices to prove `¬(p ∨ q)`. cases h₁ with h₃ h₄, -- We have `h₃ : ¬p` and `h₄ : ¬q` by left and right `∧` elim. on `h₁`. assume h₅ : p ∨ q, -- Assume `h₅ : p ∨ q`. By negation introduction, it suffices to prove `false`. -- By or elimination on `h₅`, it suffices to 1. assume `h₆ : p` and derive `false` and 2. assume `h₇ : q` and derive `false`. cases h₅ with h₆ h₇, { exact h₃ h₆, }, -- The goal in the first case is closed by false introduction on `h₃` and `h₆`. { exact h₄ h₇, }, -- The goal in the second case is closed by false introduction on `h₄` and `h₇`. end -- END
d431a2dbb14026f032ddb4f50d3528810b440ae8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/ideal/basic.lean
6aa9e1cb02cdbd79e8dc019de89ceea7cd33dc63
[ "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
30,528
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.quotient import order.zorn import order.atoms import order.compactly_generated /-! # Ideals over a ring This file defines `ideal R`, the type of ideals over a commutative ring `R`. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support one-sided ideals, and ideals over non-commutative rings. See `algebra.ring_quot` for quotients of non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators pointwise /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem variables (a) lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s @[simp] lemma submodule_span_eq {s : set α} : submodule.span α s = ideal.span s := rfl lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set α) = ⊤ := by rw [←set.singleton_one, span_singleton_one] /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal α) : Prop := (ne_top' : I ≠ ⊤) (mem_or_mem' : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal α} : is_prime I ↔ I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ theorem is_prime.ne_top {I : ideal α} (hI : I.is_prime) : I ≠ ⊤ := hI.1 theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem lemma bot_prime {R : Type*} [comm_ring R] [integral_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal α) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal α} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal α} (h : I.is_maximal) : I ≠ ⊤ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal α) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (α) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) bot_ne_top in ⟨I, hI⟩ variables {α} instance [nontrivial α] : nontrivial (ideal α) := begin rcases @exists_maximal α _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊤ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [comm_semiring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, ∃ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Type*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Type*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, I.zero_mem, add_mem' := λ a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := λ a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl end pi end ideal end semiring section comm_semiring variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring α] (I : ideal α) @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [comm_ring α] [integral_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin let J : ideal α := submodule.span α (insert x ↑I), have IJ : I ≤ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a • x + b)) := congr_arg (λ g : α, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [comm_ring β] [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [comm_ring β] [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : ℕ) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (λ m hm, (pow_succ a m).symm ▸ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := λ x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (λ hr, I.pow_mem_of_mem hr n hn)⟩ end ideal end comm_semiring section ring namespace ideal variables [ring α] (I : ideal α) {a b : α} lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end lemma eq_bot_of_prime [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (⊥ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal theorem mul_sub_mul_mem {R : Type*} [comm_ring R] (I : ideal R) {a b c d : R} (h1 : a - b ∈ I) (h2 : c - d ∈ I) : a * c - b * d ∈ I := begin rw (show a * c - b * d = (a - b) * c + b * (c - d), by {rw [sub_mul, mul_sub], abel}), exact I.add_mem (I.mul_mem_right _ h1) (I.mul_mem_left _ h2), end variables [comm_ring α] (I : ideal α) {a b : α} /-- The quotient `R/I` of a ring `R` by an ideal `I`. The ideal quotient of `I` is defined to equal the quotient of `I` as an `R`-submodule of `R`. This definition is marked `reducible` so that typeclass instances can be shared between `ideal.quotient I` and `submodule.quotient I`. -/ -- Note that at present `ideal` means a left-ideal, -- so this quotient is only useful in a commutative ring. -- We should develop quotients by two-sided ideals as well. @[reducible] def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} instance (I : ideal α) : has_one I.quotient := ⟨submodule.quotient.mk 1⟩ instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin have F := I.add_mem (I.mul_mem_left a₂ h₁) (I.mul_mem_right b₁ h₂), have : a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁, { rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] }, rw ← this at F, change _ ∈ _, convert F, end⟩ instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg submodule.quotient.mk (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/ def mk (I : ideal α) : α →+* I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ /- Two `ring_homs`s from the quotient by an ideal are equal if their compositions with `ideal.quotient.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext [non_assoc_semiring β] ⦃f g : I.quotient →+* β⦄ (h : f.comp (mk I) = g.comp (mk I)) : f = g := ring_hom.ext $ λ x, quotient.induction_on' x $ (ring_hom.congr_fun h : _) instance : inhabited (quotient I) := ⟨mk I 37⟩ protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I @[simp] theorem mk_eq_mk (x : α) : (submodule.quotient.mk x : quotient I) = mk I x := rfl lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nontrivial {I : ideal α} (hI : I ≠ ⊤) : nontrivial I.quotient := ⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩ lemma mk_surjective : function.surjective (mk I) := λ y, quotient.induction_on' y (λ x, exists.intro x rfl) /-- If `I` is an ideal of a commutative ring `R`, if `q : R → R/I` is the quotient map, and if `s ⊆ R` is a subset, then `q⁻¹(q(s)) = ⋃ᵢ(i + s)`, the union running over all `i ∈ I`. -/ lemma quotient_ring_saturate (I : ideal α) (s : set α) : mk I ⁻¹' (mk I '' s) = (⋃ x : I, (λ y, x.1 + y) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq], exact ⟨λ ⟨a, a_in, h⟩, ⟨⟨_, I.neg_mem h⟩, a, a_in, by simp⟩, λ ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact I.neg_mem hi⟩⟩ end instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), .. quotient.nontrivial hI.1 } lemma is_integral_domain_iff_prime (I : ideal α) : is_integral_domain I.quotient ↔ I.is_prime := ⟨ λ ⟨h1, h2, h3⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h1⟩, λ x y h, by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h3 _ _ h}⟩, λ h, by exactI integral_domain.to_is_integral_domain I.quotient⟩ lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, rcases hI.exists_inv (mt eq_zero_iff_mem.2 h) with ⟨b, c, hc, abc⟩, rw [mul_comm] at abc, refine ⟨mk _ b, quot.sound _⟩, --quot.sound hb rw ← eq_sub_iff_add_eq' at abc, rw [abc, ← neg_mem_iff, neg_sub] at hc, convert hc, end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications. See note [reducible non-instances]. -/ @[reducible] protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.comm_ring I, ..quotient.integral_domain I } /-- If the quotient by an ideal is a field, then the ideal is maximal. -/ theorem maximal_of_is_field (I : ideal α) (hqf : is_field I.quotient) : I.is_maximal := begin apply ideal.is_maximal_iff.2, split, { intro h, rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩, exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left _ h)) }, { intros J x hIJ hxnI hxJ, rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩, rw [← zero_add (1 : α), ← sub_self (x * y), sub_add], refine J.sub_mem (J.mul_mem_right _ hxJ) (hIJ (ideal.quotient.eq.1 hy)) } end /-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/ theorem maximal_ideal_iff_is_field_quotient (I : ideal α) : I.is_maximal ↔ is_field I.quotient := ⟨λ h, @field.to_is_field I.quotient (@ideal.quotient.field _ _ I h), λ h, maximal_of_is_field I h⟩ variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl /-- The ring homomorphism from the quotient by a smaller ideal to the quotient by a larger ideal. This is the `ideal.quotient` version of `quot.factor` -/ def factor (S T : ideal α) (H : S ≤ T) : S.quotient →+* T.quotient := ideal.quotient.lift S (T^.quotient.mk) (λ x hx, eq_zero_iff_mem.2 (H hx)) @[simp] lemma factor_mk (S T : ideal α) (H : S ≤ T) (x : α) : factor S T H (mk S x) = mk T x := rfl @[simp] lemma factor_comp_mk (S T : ideal α) (H : S ≤ T) : (factor S T H).comp (mk S) = mk T := by { ext x, rw [ring_hom.comp_apply, factor_mk] } end quotient /-- Quotienting by equal ideals gives equivalent rings. See also `submodule.quot_equiv_of_eq`. -/ def quot_equiv_of_eq {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) : I.quotient ≃+* J.quotient := { map_mul' := by { rintro ⟨x⟩ ⟨y⟩, refl }, .. submodule.quot_equiv_of_eq I J h } @[simp] lemma quot_equiv_of_eq_mk {R : Type*} [comm_ring R] {I J : ideal R} (h : I = J) (x : R) : quot_equiv_of_eq h (ideal.quotient.mk I x) = ideal.quotient.mk J x := rfl section pi variables (ι : Type v) /-- `R^n/I^n` is a `R/I`-module. -/ instance module_pi : module (I.quotient) (I.pi ι).quotient := { smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) begin intros c₁ m₁ c₂ m₂ hc hm, apply ideal.quotient.eq.2, intro i, exact I.mul_sub_mul_mem hc (hm i), end, one_smul := begin rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact one_mul (a i), end, mul_smul := begin rintro ⟨a⟩ ⟨b⟩ ⟨c⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, simp only [(•)], congr' with i, exact mul_assoc a b (c i), end, smul_add := begin rintro ⟨a⟩ ⟨b⟩ ⟨c⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact mul_add a (b i) (c i), end, smul_zero := begin rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact mul_zero a, end, add_smul := begin rintro ⟨a⟩ ⟨b⟩ ⟨c⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact add_mul a b (c i), end, zero_smul := begin rintro ⟨a⟩, change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, exact zero_mul (a i), end, } /-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/ noncomputable def pi_quot_equiv : (I.pi ι).quotient ≃ₗ[I.quotient] (ι → I.quotient) := { to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $ λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)), map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl }, map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl }, inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i), left_inv := begin rintro ⟨x⟩, exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _)) end, right_inv := begin intro x, ext i, obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i), simp_rw ←hr, convert quotient.out_eq' _ end } /-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is contained in `I^m`. -/ lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → α) (hi : ∀ i, x i ∈ I) (f : (ι → α) →ₗ[α] (ι' → α)) (i : ι') : f x i ∈ I := begin rw pi_eq_sum_univ x, simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul], exact I.sum_mem (λ j hj, I.mul_mem_right _ (hi j)) end end pi end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : ¬ is_field R) : M ≠ ⊥ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, finish, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : α} /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end
5df7c861dc4be171e98fc4d19dcdf1e223237e5a
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/polynomial/degree/lemmas.lean
ff2759e8da78d499778455f1e183c15a15f91613
[ "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
8,686
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.eval import tactic.interval_cases /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ noncomputable theory open_locale classical open finsupp finset namespace polynomial universes u v w variables {R : Type u} {S : Type v} { ι : Type w} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section degree lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... = _ : congr_arg degree comp_eq_sum_left ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n • (degree q) : add_le_add degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n • (nat_degree q) : add_le_add_left (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) _ ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_eq_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f _) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, f.map_zero] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma nat_degree_map_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f hf) lemma leading_coeff_map_of_leading_coeff_ne_zero [semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_of_leading_coeff_ne_zero f hf], end lemma degree_pos_of_root {p : polynomial R} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, simp only [h, ring_hom.map_zero] at this, exact hp this, end lemma nat_degree_le_iff_coeff_eq_zero : p.nat_degree ≤ n ↔ ∀ N : ℕ, n < N → p.coeff N = 0 := by simp_rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero, with_bot.coe_lt_coe] lemma nat_degree_C_mul_le (a : R) (f : polynomial R) : (C a * f).nat_degree ≤ f.nat_degree := calc (C a * f).nat_degree ≤ (C a).nat_degree + f.nat_degree : nat_degree_mul_le ... = 0 + f.nat_degree : by rw nat_degree_C a ... = f.nat_degree : zero_add _ lemma nat_degree_mul_C_le (f : polynomial R) (a : R) : (f * C a).nat_degree ≤ f.nat_degree := calc (f * C a).nat_degree ≤ f.nat_degree + (C a).nat_degree : nat_degree_mul_le ... = f.nat_degree + 0 : by rw nat_degree_C a ... = f.nat_degree : add_zero _ lemma eq_nat_degree_of_le_mem_support (pn : p.nat_degree ≤ n) (ns : n ∈ p.support) : p.nat_degree = n := le_antisymm pn (le_nat_degree_of_mem_supp _ ns) lemma nat_degree_C_mul_eq_of_mul_eq_one {ai : R} (au : ai * a = 1) : (C a * p).nat_degree = p.nat_degree := le_antisymm (nat_degree_C_mul_le a p) (calc p.nat_degree = (1 * p).nat_degree : by nth_rewrite 0 [← one_mul p] ... = (C ai * (C a * p)).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (C a * p).nat_degree : nat_degree_C_mul_le ai (C a * p)) lemma nat_degree_mul_C_eq_of_mul_eq_one {ai : R} (au : a * ai = 1) : (p * C a).nat_degree = p.nat_degree := le_antisymm (nat_degree_mul_C_le p a) (calc p.nat_degree = (p * 1).nat_degree : by nth_rewrite 0 [← mul_one p] ... = ((p * C a) * C ai).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (p * C a).nat_degree : nat_degree_mul_C_le (p * C a) ai) /-- Although not explicitly stated, the assumptions of lemma `nat_degree_mul_C_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. Lemma `nat_degree_mul_C_eq_of_no_zero_divisors` below separates cases, in order to overcome this hurdle. -/ lemma nat_degree_mul_C_eq_of_mul_ne_zero (h : p.leading_coeff * a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_mul_C_le p a) _, refine mem_support_iff.mpr _, rwa coeff_mul_C, end /-- Although not explicitly stated, the assumptions of lemma `nat_degree_C_mul_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. Lemma `nat_degree_C_mul_eq_of_no_zero_divisors` below separates cases, in order to overcome this hurdle. -/ lemma nat_degree_C_mul_eq_of_mul_ne_zero (h : a * p.leading_coeff ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_C_mul_le a p) _, refine mem_support_iff.mpr _, rwa coeff_C_mul, end lemma nat_degree_add_coeff_mul (f g : polynomial R) : (f * g).coeff (f.nat_degree + g.nat_degree) = f.coeff f.nat_degree * g.coeff g.nat_degree := by simp only [coeff_nat_degree, coeff_mul_degree_add_degree] lemma nat_degree_lt_coeff_mul (h : p.nat_degree + q.nat_degree < m + n) : (p * q).coeff (m + n) = 0 := coeff_eq_zero_of_nat_degree_lt (nat_degree_mul_le.trans_lt h) variables [semiring S] lemma nat_degree_pos_of_eval₂_root {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < nat_degree p := lt_of_not_ge $ λ hlt, begin have A : p = C (p.coeff 0) := eq_C_of_nat_degree_le_zero hlt, rw [A, eval₂_C] at hz, simp only [inj (p.coeff 0) hz, ring_hom.map_zero] at A, exact hp A end lemma degree_pos_of_eval₂_root {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < degree p := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_eval₂_root hp f hz inj) section injective open function variables {f : R →+* S} (hf : injective f) include hf lemma degree_map_eq_of_injective (p : polynomial R) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← f.map_zero]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma degree_map' (p : polynomial R) : degree (p.map f) = degree p := p.degree_map_eq_of_injective hf lemma nat_degree_map' (p : polynomial R) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) lemma leading_coeff_map' (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map' hf p], end lemma next_coeff_map (p : polynomial R) : (p.map f).next_coeff = f p.next_coeff := begin unfold next_coeff, rw nat_degree_map' hf, split_ifs; simp end end injective section variable {f : polynomial R} lemma monomial_nat_degree_leading_coeff_eq_self (h : f.support.card ≤ 1) : monomial f.nat_degree f.leading_coeff = f := begin rcases card_support_le_one_iff_monomial.1 h with ⟨n, a, rfl⟩, by_cases ha : a = 0; simp [ha] end lemma C_mul_X_pow_eq_self (h : f.support.card ≤ 1) : C f.leading_coeff * X^f.nat_degree = f := by rw [C_mul_X_pow_eq_monomial, monomial_nat_degree_leading_coeff_eq_self h] end end degree end semiring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : polynomial R} lemma nat_degree_mul_C_eq_of_no_zero_divisors (a0 : a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin by_cases p0 : p = 0, { rw [p0, zero_mul] }, { exact nat_degree_mul_C_eq_of_mul_ne_zero (mul_ne_zero (leading_coeff_ne_zero.mpr p0) a0) } end lemma nat_degree_C_mul_eq_of_no_zero_divisors (a0 : a ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin by_cases p0 : p = 0, { rw [p0, mul_zero] }, { exact nat_degree_C_mul_eq_of_mul_ne_zero (mul_ne_zero a0 (leading_coeff_ne_zero.mpr p0)) } end end no_zero_divisors end polynomial
3674b7b7c5d58112210d5a9f408164972d0b11c5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/category/Mon/colimits.lean
b1bbcb32c2f8daa8e03747e0c01cb3a27cc34b4f
[ "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
7,654
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Mon.basic import category_theory.limits.has_limits import category_theory.concrete_category.elementwise /-! # The category of monoids has all colimits. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We do this construction knowing nothing about monoids. In particular, I want to claim that this file could be produced by a python script that just looks at the output of `#print monoid`: -- structure monoid : Type u → Type u -- fields: -- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α -- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) -- monoid.one : Π (α : Type u) [c : monoid α], α -- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a -- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a and if we'd fed it the output of `#print comm_ring`, this file would instead build colimits of commutative rings. A slightly bolder claim is that we could do this with tactics, as well. -/ universes v open category_theory open category_theory.limits namespace Mon.colimits /-! We build the colimit of a diagram in `Mon` by constructing the free monoid on the disjoint union of all the monoids in the diagram, then taking the quotient by the monoid laws within each monoid, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ Mon.{v}) /-- An inductive type representing all monoid expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | one : prequotient | mul : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.one⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the monoid laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' ((F.map f) x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | mul : Π (j) (x y : F.obj j), relation (of j (x * y)) (mul (of j x) (of j y)) | one : Π (j), relation (of j 1) one -- Then one relation per argument of each operation | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x /-- The setoid corresponding to monoid expressions modulo monoid relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `Mon`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance monoid_colimit_type : monoid (colimit_type F) := { mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, one := begin exact quot.mk _ one end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end } @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled monoid giving the colimit of a diagram. -/ def colimit : Mon := ⟨colimit_type F, by apply_instance⟩ /-- The function from a given monoid in the diagram to the colimit monoid. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := quot.sound (relation.one _), map_mul' := λ x y, quot.sound (relation.mul _ _ _) } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit monoid. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F, } }. /-- The function from the free monoid on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | one := 1 | (mul x y) := desc_fun_lift x * desc_fun_lift y /-- The function from the colimit monoid to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- mul { simp, }, -- one { simp, }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- mul_assoc { rw mul_assoc, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, } } end /-- The monoid homomorphism from the colimit monoid to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_mul' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_Mon : has_colimits Mon := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end Mon.colimits
e942e7d771681f6360607af2bab94578e37830d5
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/metric_space/gromov_hausdorff.lean
f26cca3205147887c05d64a28a70f01fdc9b5a02
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
55,705
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.closeds import set_theory.cardinal import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.completion /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λx y, nonempty (x.val ≃ᵢ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding α⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp [-singleton_zero]⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val := begin simp only [to_GH_space, quotient.eq], split, { assume h, rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry α).isometric_on_range.trans e, use λx, f x, split, { apply isometry_subtype_coe.comp f.isometry }, { rw [range_comp, f.range_coe, set.image_univ, subtype.range_coe] } }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry α).isometric_on_range.symm.trans isomΨ.isometric_on_range).symm, have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val) = (p.val ≃ᵢ range (Kuratowski_embedding α)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, have g := cast E f, exact ⟨g⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := begin refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.range_coe⟩, apply isometry_subtype_coe end section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type u} [metric_space β] [compact_space β] [nonempty β] : to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) := ⟨begin simp only [to_GH_space, quotient.eq], assume h, rcases h with e, have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val) = ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have e' := cast I e, have f := (Kuratowski_embedding.isometry α).isometric_on_range, have g := (Kuratowski_embedding.isometry β).isometric_on_range.symm, have h := (f.trans e').trans g, exact ⟨h⟩ end, begin rintros ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry α).isometric_on_range.symm, have g := (Kuratowski_embedding.isometry β).isometric_on_range, have h := (f.trans e).trans g, have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) = ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have h' := cast I h, exact ⟨h'⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λx y, Inf ((λp : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α] [metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] {γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not separable in general. We restrict to the union of the images of `α` and `β` in `γ`, which is separable and therefore embeddable in `ℓ^∞(ℝ)`. -/ rcases exists_mem_of_nonempty α with ⟨xα, _⟩, letI : inhabited α := ⟨xα⟩, letI : inhabited β := classical.inhabited_of_nonempty (by assumption), let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λx y, ha x y, have IΨ' : isometry Ψ' := λx y, hb x y, have : is_compact s, from (compact_range ha.continuous).union (compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹is_compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xα⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `α` and `β` under this embedding. They are in `ℓ^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _, (compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _, (compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, have Aα : ⟦A⟧ = to_GH_space α, { rw eq_to_GH_space_iff, exact ⟨λx, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ }, have Bβ : ⟦B⟧ = to_GH_space β, { rw eq_to_GH_space_iff, exact ⟨λx, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [Aα, Bβ] end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β := begin inhabit α, inhabit β, /- we only need to check the inequality `≤`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `α ⊕ β` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β), { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β), { rw Ψrange, have : Φ xα ∈ p.val := Φrange ▸ mem_range_self _, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set α) := Φisom.diam_range, have DΨ : diam (range Ψ) = diam (univ : set β) := Ψisom.diam_range, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) } ... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring }, let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end, let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates α β, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λx y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq x y }, { exact λx y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq x y }, { exact λx y, dist_comm _ _ }, { exact λx y z, dist_triangle _ _ _ }, { exact λx y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact (p.2.2.union q.2.2).bounded, end ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λr hr, _)), have I1 : ∀x : α, infi (λy:β, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc infi (λy:β, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) y ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀y : β, infi (λx:α, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc infi (λx:α, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) x ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α] (β : Type v) [metric_space β] [compact_space β] [nonempty β] : ∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling α β), let Φ := F ∘ optimal_GH_injl α β, let Ψ := F ∘ optimal_GH_injr α β, refine ⟨Φ, Ψ, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl α β) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr α β) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end -- without the next two lines, `{ exact hΦ.is_closed }` in the next -- proof is very slow, as the `t2_space` instance is very hard to find local attribute [instance, priority 10] order_topology.t2_space local attribute [instance, priority 10] order_closed_topology.to_t2_space /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance GH_space_metric_space : metric_space GH_space := { dist_self := λx, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λx y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, prod.swap, image_swap_prod], end, eq_of_dist_eq_zero := λx y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : is_compact (range Φ) := compact_range Φisom.continuous, have hΨ : is_compact (range Ψ) := compact_range Ψisom.continuous, apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm), { exact hΦ.is_closed }, { exact hΨ.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΦ.bounded hΨ.bounded } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometric_on_range.symm, have e := Φisom.isometric_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := λx y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y`and `Z` in a space `γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `γ` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [eq.symm range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α] (p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {α : Type u} [metric_space α] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (coe : p.val → α) := isometry_subtype_coe, have hb : isometry (coe : q.val → α) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (coe : p.val → α), by simp, have J : q.val = range (coe : q.val → α), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε₁ ε₂ ε₃ : ℝ} (hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε₁) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε₃) (H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) : GH_dist α β ≤ ε₁ + ε₂ / 2 + ε₃ := begin refine real.le_of_forall_epsilon_le (λδ δ0, _), rcases exists_mem_of_nonempty α with ⟨xα, _⟩, rcases hs xα with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λp q, calc abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q ... ≤ 2 * (ε₂/2 + δ) : by linarith, -- glue `α` and `β` along the almost matching subsets letI : metric_space (α ⊕ β) := glue_metric_approx (λ x:s, (x:α)) (λx, Φ x) (ε₂/2 + δ) (by linarith) this, let Fl := @sum.inl α β, let Fr := @sum.inr α β, have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `α` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of `Φ s` and `β` (in the coupling or, equivalently, in the original space). The first term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `α ⊕ β`). -/ have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := (compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.subset (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x) (λx hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (λ x:s, (x:α)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε₂/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty β with ⟨xβ, _⟩, rcases hs' xβ with ⟨xs', Dxs'⟩, have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance second_countable : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λδ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λp, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos, -- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, rcases fintype.exists_equiv_fin t with ⟨n, hn⟩, rcases hn with e, exact ⟨n, e, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := λp:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := λp:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `ε`-dense set `s p`. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩, refine ⟨_, by apply_instance, F, λp q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≤ δ`. For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then composing with the canonical inclusion we get `Φ`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λx, Ψ x, -- Use the almost isometry `Φ` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i := ((E q) ⟨y, ys⟩).1, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw fin.ext_iff, have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i := ((E p) x).1, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)).1, by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j := ((E p) y).1, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp [ε], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (𝓝 0)) (hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λδ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose `n` for which `u n < ε` rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n (le_refl _), simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n` have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`. let M := (floor (ε⁻¹ * max C 0)).to_nat, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat, lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, by apply_instance, (λp, F p), _⟩, -- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λx, Ψ x, have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i := ((E q) ⟨y, ys⟩).1, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw fin.ext_iff, have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i := ((E p) x).1, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)).1, by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j := ((E p) y).1, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M (floor (ε⁻¹ * dist x y)).to_nat : by simp only [F, (E p).symm_apply_apply] ... = (floor (ε⁻¹ * dist x y)).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos.2 εpos)), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : by simp only [F, (E q).symm_apply_apply] ... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos.2 εpos)), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), { rw [Ap, Aq] at this, have D : 0 ≤ floor (ε⁻¹ * dist x y) := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] }, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp [ε], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := λx y, rfl } (λn a, by letI : metric_space a.space := a.metric; exact { space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injr (X n) (X n.succ)), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X n.succ)) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space (GH_space) := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply _root_.pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _), -- `X n` is a representative of `u n` let X := λn, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, letI : ∀n, metric_space (Y n).space := λn, (Y n).metric, have E : ∀n:ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := λn, by { simp [Y, aux_gluing], refl }, let c := λn, cast (E n), have ic : ∀n, isometry (c n) := λn x y, rfl, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Πn, (Y n).space → (Y n.succ).space := λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : ∀n, isometry (f n), { assume n, apply isometry.comp, { assume x y, refl }, { apply to_glue_l_isometry } }, -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, apply isometry.comp completion.coe_isometry _, apply isometry.comp _ (Y n).isom, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp completion.coe_isometry _, apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)), apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n, ⟨range_nonempty _, compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λn, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], constructor, convert (isom n).isometric_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
75d57372cbe618e5ed421b2c44e6076f0045360c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/fiber_bundle/trivialization.lean
fcde8b14a33e42b363e7a0a83baa80929977aefc
[ "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
31,422
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.bundle import topology.algebra.order.field import topology.local_homeomorph /-! # Trivializations > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions ### Basic definitions * `trivialization F p` : structure extending local homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. * `pretrivialization F proj` : trivialization as a local equivalence, mainly used when the topology on the total space has not yet been defined. ### Operations on bundles We provide the following operations on `trivialization`s. * `trivialization.comp_homeomorph`: given a local trivialization `e` of a fiber bundle `p : Z → B` and a homeomorphism `h : Z' ≃ₜ Z`, returns a local trivialization of the fiber bundle `p ∘ h`. ## Implementation notes Previously, in mathlib, there was a structure `topological_vector_bundle.trivialization` which extended another structure `topological_fiber_bundle.trivialization` by a linearity hypothesis. As of PR #17359, we have changed this to a single structure `trivialization` (no namespace), together with a mixin class `trivialization.is_linear`. This permits all the *data* of a vector bundle to be held at the level of fiber bundles, so that the same trivializations can underlie an object's structure as (say) a vector bundle over `ℂ` and as a vector bundle over `ℝ`, as well as its structure simply as a fiber bundle. This might be a little surprising, given the general trend of the library to ever-increased bundling. But in this case the typical motivation for more bundling does not apply: there is no algebraic or order structure on the whole type of linear (say) trivializations of a bundle. Indeed, since trivializations only have meaning on their base sets (taking junk values outside), the type of linear trivializations is not even particularly well-behaved. -/ open topological_space filter set bundle open_locale topology classical bundle variables {ι : Type*} {B : Type*} {F : Type*} {E : B → Type*} variables (F) {Z : Type*} [topological_space B] [topological_space F] {proj : Z → B} /-- This structure contains the information left for a local trivialization (which is implemented below as `trivialization F proj`) if the total space has not been given a topology, but we have a topology on both the fiber and the base space. Through the construction `topological_fiber_prebundle F proj` it will be possible to promote a `pretrivialization F proj` to a `trivialization F proj`. -/ @[ext, nolint has_nonempty_instance] structure pretrivialization (proj : Z → B) extends local_equiv Z (B × F) := (open_target : is_open target) (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = base_set ×ˢ univ) (proj_to_fun : ∀ p ∈ source, (to_fun p).1 = proj p) namespace pretrivialization instance : has_coe_to_fun (pretrivialization F proj) (λ _, Z → (B × F)) := ⟨λ e, e.to_fun⟩ variables {F} (e : pretrivialization F proj) {x : Z} @[simp, mfld_simps] lemma coe_coe : ⇑e.to_local_equiv = e := rfl @[simp, mfld_simps] lemma coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_to_fun x ex lemma mem_source : x ∈ e.source ↔ proj x ∈ e.base_set := by rw [e.source_eq, mem_preimage] lemma coe_fst' (ex : proj x ∈ e.base_set) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) protected lemma eq_on : eq_on (prod.fst ∘ e) proj e.source := λ x hx, e.coe_fst hx lemma mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst ex).symm rfl lemma mk_proj_snd' (ex : proj x ∈ e.base_set) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst' ex).symm rfl /-- Composition of inverse and coercion from the subtype of the target. -/ def set_symm : e.target → Z := e.target.restrict e.to_local_equiv.symm lemma mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.base_set := by rw [e.target_eq, prod_univ, mem_preimage] lemma proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.to_local_equiv.symm x) = x.1 := begin have := (e.coe_fst (e.to_local_equiv.map_target hx)).symm, rwa [← e.coe_coe, e.to_local_equiv.right_inv hx] at this end lemma proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : proj (e.to_local_equiv.symm (b, x)) = b := e.proj_symm_apply (e.mem_target.2 hx) lemma proj_surj_on_base_set [nonempty F] : set.surj_on proj e.source e.base_set := λ b hb, let ⟨y⟩ := ‹nonempty F› in ⟨e.to_local_equiv.symm (b, y), e.to_local_equiv.map_target $ e.mem_target.2 hb, e.proj_symm_apply' hb⟩ lemma apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.to_local_equiv.symm x) = x := e.to_local_equiv.right_inv hx lemma apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : e (e.to_local_equiv.symm (b, x)) = (b, x) := e.apply_symm_apply (e.mem_target.2 hx) lemma symm_apply_apply {x : Z} (hx : x ∈ e.source) : e.to_local_equiv.symm (e x) = x := e.to_local_equiv.left_inv hx @[simp, mfld_simps] lemma symm_apply_mk_proj {x : Z} (ex : x ∈ e.source) : e.to_local_equiv.symm (proj x, (e x).2) = x := by rw [← e.coe_fst ex, prod.mk.eta, ← e.coe_coe, e.to_local_equiv.left_inv ex] @[simp, mfld_simps] lemma preimage_symm_proj_base_set : (e.to_local_equiv.symm ⁻¹' (proj ⁻¹' e.base_set)) ∩ e.target = e.target := begin refine inter_eq_right_iff_subset.mpr (λ x hx, _), simp only [mem_preimage, local_equiv.inv_fun_as_coe, e.proj_symm_apply hx], exact e.mem_target.mp hx, end @[simp, mfld_simps] lemma preimage_symm_proj_inter (s : set B) : (e.to_local_equiv.symm ⁻¹' (proj ⁻¹' s)) ∩ e.base_set ×ˢ univ = (s ∩ e.base_set) ×ˢ univ := begin ext ⟨x, y⟩, suffices : x ∈ e.base_set → (proj (e.to_local_equiv.symm (x, y)) ∈ s ↔ x ∈ s), by simpa only [prod_mk_mem_set_prod_eq, mem_inter_iff, and_true, mem_univ, and.congr_left_iff], intro h, rw [e.proj_symm_apply' h] end lemma target_inter_preimage_symm_source_eq (e f : pretrivialization F proj) : f.target ∩ (f.to_local_equiv.symm) ⁻¹' e.source = (e.base_set ∩ f.base_set) ×ˢ univ := by rw [inter_comm, f.target_eq, e.source_eq, f.preimage_symm_proj_inter] lemma trans_source (e f : pretrivialization F proj) : (f.to_local_equiv.symm.trans e.to_local_equiv).source = (e.base_set ∩ f.base_set) ×ˢ univ := by rw [local_equiv.trans_source, local_equiv.symm_source, e.target_inter_preimage_symm_source_eq] lemma symm_trans_symm (e e' : pretrivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).symm = e'.to_local_equiv.symm.trans e.to_local_equiv := by rw [local_equiv.trans_symm_eq_symm_trans_symm, local_equiv.symm_symm] lemma symm_trans_source_eq (e e' : pretrivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).source = (e.base_set ∩ e'.base_set) ×ˢ univ := by rw [local_equiv.trans_source, e'.source_eq, local_equiv.symm_source, e.target_eq, inter_comm, e.preimage_symm_proj_inter, inter_comm] lemma symm_trans_target_eq (e e' : pretrivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).target = (e.base_set ∩ e'.base_set) ×ˢ univ := by rw [← local_equiv.symm_source, symm_trans_symm, symm_trans_source_eq, inter_comm] variables {B F} (e' : pretrivialization F (π F E)) {x' : total_space F E} {b : B} {y : E b} @[simp] theorem coe_mem_source : ↑y ∈ e'.source ↔ b ∈ e'.base_set := e'.mem_source @[simp, mfld_simps] lemma coe_coe_fst (hb : b ∈ e'.base_set) : (e' y).1 = b := e'.coe_fst (e'.mem_source.2 hb) lemma mk_mem_target {x : B} {y : F} : (x, y) ∈ e'.target ↔ x ∈ e'.base_set := e'.mem_target lemma symm_coe_proj {x : B} {y : F} (e' : pretrivialization F (π F E)) (h : x ∈ e'.base_set) : (e'.to_local_equiv.symm (x, y)).1 = x := e'.proj_symm_apply' h section has_zero variables [∀ x, has_zero (E x)] /-- A fiberwise inverse to `e`. This is the function `F → E b` that induces a local inverse `B × F → total_space F E` of `e` on `e.base_set`. It is defined to be `0` outside `e.base_set`. -/ protected noncomputable def symm (e : pretrivialization F (π F E)) (b : B) (y : F) : E b := if hb : b ∈ e.base_set then cast (congr_arg E (e.proj_symm_apply' hb)) (e.to_local_equiv.symm (b, y)).2 else 0 lemma symm_apply (e : pretrivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : F) : e.symm b y = cast (congr_arg E (e.symm_coe_proj hb)) (e.to_local_equiv.symm (b, y)).2 := dif_pos hb lemma symm_apply_of_not_mem (e : pretrivialization F (π F E)) {b : B} (hb : b ∉ e.base_set) (y : F) : e.symm b y = 0 := dif_neg hb lemma coe_symm_of_not_mem (e : pretrivialization F (π F E)) {b : B} (hb : b ∉ e.base_set) : (e.symm b : F → E b) = 0 := funext $ λ y, dif_neg hb lemma mk_symm (e : pretrivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : F) : total_space.mk b (e.symm b y) = e.to_local_equiv.symm (b, y) := by rw [e.symm_apply hb, total_space.mk_cast, total_space.eta] lemma symm_proj_apply (e : pretrivialization F (π F E)) (z : total_space F E) (hz : z.proj ∈ e.base_set) : e.symm z.proj (e z).2 = z.2 := by rw [e.symm_apply hz, cast_eq_iff_heq, e.mk_proj_snd' hz, e.symm_apply_apply (e.mem_source.mpr hz)] lemma symm_apply_apply_mk (e : pretrivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : E b) : e.symm b (e ⟨b, y⟩).2 = y := e.symm_proj_apply ⟨b, y⟩ hb lemma apply_mk_symm (e : pretrivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : F) : e ⟨b, e.symm b y⟩ = (b, y) := by rw [e.mk_symm hb, e.apply_symm_apply (e.mk_mem_target.mpr hb)] end has_zero end pretrivialization variables [topological_space Z] [topological_space (total_space F E)] /-- A structure extending local homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a local homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' base_set` and `base_set × F`, acting trivially on the first coordinate. -/ @[ext, nolint has_nonempty_instance] structure trivialization (proj : Z → B) extends local_homeomorph Z (B × F) := (base_set : set B) (open_base_set : is_open base_set) (source_eq : source = proj ⁻¹' base_set) (target_eq : target = base_set ×ˢ univ) (proj_to_fun : ∀ p ∈ source, (to_local_homeomorph p).1 = proj p) namespace trivialization variables {F} (e : trivialization F proj) {x : Z} /-- Natural identification as a `pretrivialization`. -/ def to_pretrivialization : pretrivialization F proj := { ..e } instance : has_coe_to_fun (trivialization F proj) (λ _, Z → B × F) := ⟨λ e, e.to_fun⟩ instance : has_coe (trivialization F proj) (pretrivialization F proj) := ⟨to_pretrivialization⟩ lemma to_pretrivialization_injective : function.injective (λ e : trivialization F proj, e.to_pretrivialization) := by { intros e e', rw [pretrivialization.ext_iff, trivialization.ext_iff, ← local_homeomorph.to_local_equiv_injective.eq_iff], exact id } @[simp, mfld_simps] lemma coe_coe : ⇑e.to_local_homeomorph = e := rfl @[simp, mfld_simps] lemma coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_to_fun x ex protected lemma eq_on : eq_on (prod.fst ∘ e) proj e.source := λ x hx, e.coe_fst hx lemma mem_source : x ∈ e.source ↔ proj x ∈ e.base_set := by rw [e.source_eq, mem_preimage] lemma coe_fst' (ex : proj x ∈ e.base_set) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) lemma mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst ex).symm rfl lemma mk_proj_snd' (ex : proj x ∈ e.base_set) : (proj x, (e x).2) = e x := prod.ext (e.coe_fst' ex).symm rfl lemma source_inter_preimage_target_inter (s : set (B × F)) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := e.to_local_homeomorph.source_inter_preimage_target_inter s @[simp, mfld_simps] lemma coe_mk (e : local_homeomorph Z (B × F)) (i j k l m) (x : Z) : (trivialization.mk e i j k l m : trivialization F proj) x = e x := rfl lemma mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.base_set := e.to_pretrivialization.mem_target lemma map_target {x : B × F} (hx : x ∈ e.target) : e.to_local_homeomorph.symm x ∈ e.source := e.to_local_homeomorph.map_target hx lemma proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.to_local_homeomorph.symm x) = x.1 := e.to_pretrivialization.proj_symm_apply hx lemma proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : proj (e.to_local_homeomorph.symm (b, x)) = b := e.to_pretrivialization.proj_symm_apply' hx lemma proj_surj_on_base_set [nonempty F] : set.surj_on proj e.source e.base_set := e.to_pretrivialization.proj_surj_on_base_set lemma apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.to_local_homeomorph.symm x) = x := e.to_local_homeomorph.right_inv hx lemma apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.base_set) : e (e.to_local_homeomorph.symm (b, x)) = (b, x) := e.to_pretrivialization.apply_symm_apply' hx @[simp, mfld_simps] lemma symm_apply_mk_proj (ex : x ∈ e.source) : e.to_local_homeomorph.symm (proj x, (e x).2) = x := e.to_pretrivialization.symm_apply_mk_proj ex lemma symm_trans_source_eq (e e' : trivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).source = (e.base_set ∩ e'.base_set) ×ˢ univ := pretrivialization.symm_trans_source_eq e.to_pretrivialization e' lemma symm_trans_target_eq (e e' : trivialization F proj) : (e.to_local_equiv.symm.trans e'.to_local_equiv).target = (e.base_set ∩ e'.base_set) ×ˢ univ := pretrivialization.symm_trans_target_eq e.to_pretrivialization e' lemma coe_fst_eventually_eq_proj (ex : x ∈ e.source) : prod.fst ∘ e =ᶠ[𝓝 x] proj := mem_nhds_iff.2 ⟨e.source, λ y hy, e.coe_fst hy, e.open_source, ex⟩ lemma coe_fst_eventually_eq_proj' (ex : proj x ∈ e.base_set) : prod.fst ∘ e =ᶠ[𝓝 x] proj := e.coe_fst_eventually_eq_proj (e.mem_source.2 ex) lemma map_proj_nhds (ex : x ∈ e.source) : map proj (𝓝 x) = 𝓝 (proj x) := by rw [← e.coe_fst ex, ← map_congr (e.coe_fst_eventually_eq_proj ex), ← map_map, ← e.coe_coe, e.to_local_homeomorph.map_nhds_eq ex, map_fst_nhds] lemma preimage_subset_source {s : set B} (hb : s ⊆ e.base_set) : proj ⁻¹' s ⊆ e.source := λ p hp, e.mem_source.mpr (hb hp) lemma image_preimage_eq_prod_univ {s : set B} (hb : s ⊆ e.base_set) : e '' (proj ⁻¹' s) = s ×ˢ univ := subset.antisymm (image_subset_iff.mpr (λ p hp, ⟨(e.proj_to_fun p (e.preimage_subset_source hb hp)).symm ▸ hp, trivial⟩)) (λ p hp, let hp' : p ∈ e.target := e.mem_target.mpr (hb hp.1) in ⟨e.inv_fun p, mem_preimage.mpr ((e.proj_symm_apply hp').symm ▸ hp.1), e.apply_symm_apply hp'⟩) /-- The preimage of a subset of the base set is homeomorphic to the product with the fiber. -/ def preimage_homeomorph {s : set B} (hb : s ⊆ e.base_set) : proj ⁻¹' s ≃ₜ s × F := (e.to_local_homeomorph.homeomorph_of_image_subset_source (e.preimage_subset_source hb) (e.image_preimage_eq_prod_univ hb)).trans ((homeomorph.set.prod s univ).trans ((homeomorph.refl s).prod_congr (homeomorph.set.univ F))) @[simp] lemma preimage_homeomorph_apply {s : set B} (hb : s ⊆ e.base_set) (p : proj ⁻¹' s) : e.preimage_homeomorph hb p = (⟨proj p, p.2⟩, (e p).2) := prod.ext (subtype.ext (e.proj_to_fun p (e.mem_source.mpr (hb p.2)))) rfl @[simp] lemma preimage_homeomorph_symm_apply {s : set B} (hb : s ⊆ e.base_set) (p : s × F) : (e.preimage_homeomorph hb).symm p = ⟨e.symm (p.1, p.2), ((e.preimage_homeomorph hb).symm p).2⟩ := rfl /-- The source is homeomorphic to the product of the base set with the fiber. -/ def source_homeomorph_base_set_prod : e.source ≃ₜ e.base_set × F := (homeomorph.set_congr e.source_eq).trans (e.preimage_homeomorph subset_rfl) @[simp] lemma source_homeomorph_base_set_prod_apply (p : e.source) : e.source_homeomorph_base_set_prod p = (⟨proj p, e.mem_source.mp p.2⟩, (e p).2) := e.preimage_homeomorph_apply subset_rfl ⟨p, e.mem_source.mp p.2⟩ @[simp] lemma source_homeomorph_base_set_prod_symm_apply (p : e.base_set × F) : e.source_homeomorph_base_set_prod.symm p = ⟨e.symm (p.1, p.2), (e.source_homeomorph_base_set_prod.symm p).2⟩ := rfl /-- Each fiber of a trivialization is homeomorphic to the specified fiber. -/ def preimage_singleton_homeomorph {b : B} (hb : b ∈ e.base_set) : proj ⁻¹' {b} ≃ₜ F := (e.preimage_homeomorph (set.singleton_subset_iff.mpr hb)).trans (((homeomorph.homeomorph_of_unique ({b} : set B) punit).prod_congr (homeomorph.refl F)).trans (homeomorph.punit_prod F)) @[simp] lemma preimage_singleton_homeomorph_apply {b : B} (hb : b ∈ e.base_set) (p : proj ⁻¹' {b}) : e.preimage_singleton_homeomorph hb p = (e p).2 := rfl @[simp] lemma preimage_singleton_homeomorph_symm_apply {b : B} (hb : b ∈ e.base_set) (p : F) : (e.preimage_singleton_homeomorph hb).symm p = ⟨e.symm (b, p), by rw [mem_preimage, e.proj_symm_apply' hb, mem_singleton_iff]⟩ := rfl /-- In the domain of a bundle trivialization, the projection is continuous-/ lemma continuous_at_proj (ex : x ∈ e.source) : continuous_at proj x := (e.map_proj_nhds ex).le /-- Composition of a `trivialization` and a `homeomorph`. -/ protected def comp_homeomorph {Z' : Type*} [topological_space Z'] (h : Z' ≃ₜ Z) : trivialization F (proj ∘ h) := { to_local_homeomorph := h.to_local_homeomorph.trans e.to_local_homeomorph, base_set := e.base_set, open_base_set := e.open_base_set, source_eq := by simp [e.source_eq, preimage_preimage], target_eq := by simp [e.target_eq], proj_to_fun := λ p hp, have hp : h p ∈ e.source, by simpa using hp, by simp [hp] } /-- Read off the continuity of a function `f : Z → X` at `z : Z` by transferring via a trivialization of `Z` containing `z`. -/ lemma continuous_at_of_comp_right {X : Type*} [topological_space X] {f : Z → X} {z : Z} (e : trivialization F proj) (he : proj z ∈ e.base_set) (hf : continuous_at (f ∘ e.to_local_equiv.symm) (e z)) : continuous_at f z := begin have hez : z ∈ e.to_local_equiv.symm.target, { rw [local_equiv.symm_target, e.mem_source], exact he }, rwa [e.to_local_homeomorph.symm.continuous_at_iff_continuous_at_comp_right hez, local_homeomorph.symm_symm] end /-- Read off the continuity of a function `f : X → Z` at `x : X` by transferring via a trivialization of `Z` containing `f x`. -/ lemma continuous_at_of_comp_left {X : Type*} [topological_space X] {f : X → Z} {x : X} (e : trivialization F proj) (hf_proj : continuous_at (proj ∘ f) x) (he : proj (f x) ∈ e.base_set) (hf : continuous_at (e ∘ f) x) : continuous_at f x := begin rw e.to_local_homeomorph.continuous_at_iff_continuous_at_comp_left, { exact hf }, rw [e.source_eq, ← preimage_comp], exact hf_proj.preimage_mem_nhds (e.open_base_set.mem_nhds he), end variables {E} (e' : trivialization F (π F E)) {x' : total_space F E} {b : B} {y : E b} protected lemma continuous_on : continuous_on e' e'.source := e'.continuous_to_fun lemma coe_mem_source : ↑y ∈ e'.source ↔ b ∈ e'.base_set := e'.mem_source lemma open_target : is_open e'.target := by { rw e'.target_eq, exact e'.open_base_set.prod is_open_univ } @[simp, mfld_simps] lemma coe_coe_fst (hb : b ∈ e'.base_set) : (e' y).1 = b := e'.coe_fst (e'.mem_source.2 hb) lemma mk_mem_target {y : F} : (b, y) ∈ e'.target ↔ b ∈ e'.base_set := e'.to_pretrivialization.mem_target lemma symm_apply_apply {x : total_space F E} (hx : x ∈ e'.source) : e'.to_local_homeomorph.symm (e' x) = x := e'.to_local_equiv.left_inv hx @[simp, mfld_simps] lemma symm_coe_proj {x : B} {y : F} (e : trivialization F (π F E)) (h : x ∈ e.base_set) : (e.to_local_homeomorph.symm (x, y)).1 = x := e.proj_symm_apply' h section has_zero variables [∀ x, has_zero (E x)] /-- A fiberwise inverse to `e'`. The function `F → E x` that induces a local inverse `B × F → total_space F E` of `e'` on `e'.base_set`. It is defined to be `0` outside `e'.base_set`. -/ protected noncomputable def symm (e : trivialization F (π F E)) (b : B) (y : F) : E b := e.to_pretrivialization.symm b y lemma symm_apply (e : trivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : F) : e.symm b y = cast (congr_arg E (e.symm_coe_proj hb)) (e.to_local_homeomorph.symm (b, y)).2 := dif_pos hb lemma symm_apply_of_not_mem (e : trivialization F (π F E)) {b : B} (hb : b ∉ e.base_set) (y : F) : e.symm b y = 0 := dif_neg hb lemma mk_symm (e : trivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : F) : total_space.mk b (e.symm b y) = e.to_local_homeomorph.symm (b, y) := e.to_pretrivialization.mk_symm hb y lemma symm_proj_apply (e : trivialization F (π F E)) (z : total_space F E) (hz : z.proj ∈ e.base_set) : e.symm z.proj (e z).2 = z.2 := e.to_pretrivialization.symm_proj_apply z hz lemma symm_apply_apply_mk (e : trivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : E b) : e.symm b (e ⟨b, y⟩).2 = y := e.symm_proj_apply ⟨b, y⟩ hb lemma apply_mk_symm (e : trivialization F (π F E)) {b : B} (hb : b ∈ e.base_set) (y : F) : e ⟨b, e.symm b y⟩ = (b, y) := e.to_pretrivialization.apply_mk_symm hb y lemma continuous_on_symm (e : trivialization F (π F E)) : continuous_on (λ z : B × F, total_space.mk' F z.1 (e.symm z.1 z.2)) (e.base_set ×ˢ univ) := begin have : ∀ (z : B × F) (hz : z ∈ e.base_set ×ˢ (univ : set F)), total_space.mk z.1 (e.symm z.1 z.2) = e.to_local_homeomorph.symm z, { rintro x ⟨hx : x.1 ∈ e.base_set, _⟩, simp_rw [e.mk_symm hx, prod.mk.eta] }, refine continuous_on.congr _ this, rw [← e.target_eq], exact e.to_local_homeomorph.continuous_on_symm end end has_zero /-- If `e` is a `trivialization` of `proj : Z → B` with fiber `F` and `h` is a homeomorphism `F ≃ₜ F'`, then `e.trans_fiber_homeomorph h` is the trivialization of `proj` with the fiber `F'` that sends `p : Z` to `((e p).1, h (e p).2)`. -/ def trans_fiber_homeomorph {F' : Type*} [topological_space F'] (e : trivialization F proj) (h : F ≃ₜ F') : trivialization F' proj := { to_local_homeomorph := e.to_local_homeomorph.trans_homeomorph $ (homeomorph.refl _).prod_congr h, base_set := e.base_set, open_base_set := e.open_base_set, source_eq := e.source_eq, target_eq := by simp [e.target_eq, prod_univ, preimage_preimage], proj_to_fun := e.proj_to_fun } @[simp] lemma trans_fiber_homeomorph_apply {F' : Type*} [topological_space F'] (e : trivialization F proj) (h : F ≃ₜ F') (x : Z) : e.trans_fiber_homeomorph h x = ((e x).1, h (e x).2) := rfl /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations. See also `trivialization.coord_change_homeomorph` for a version bundled as `F ≃ₜ F`. -/ def coord_change (e₁ e₂ : trivialization F proj) (b : B) (x : F) : F := (e₂ $ e₁.to_local_homeomorph.symm (b, x)).2 lemma mk_coord_change (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) (x : F) : (b, e₁.coord_change e₂ b x) = e₂ (e₁.to_local_homeomorph.symm (b, x)) := begin refine prod.ext _ rfl, rw [e₂.coe_fst', ← e₁.coe_fst', e₁.apply_symm_apply' h₁], { rwa [e₁.proj_symm_apply' h₁] }, { rwa [e₁.proj_symm_apply' h₁] } end lemma coord_change_apply_snd (e₁ e₂ : trivialization F proj) {p : Z} (h : proj p ∈ e₁.base_set) : e₁.coord_change e₂ (proj p) (e₁ p).snd = (e₂ p).snd := by rw [coord_change, e₁.symm_apply_mk_proj (e₁.mem_source.2 h)] lemma coord_change_same_apply (e : trivialization F proj) {b : B} (h : b ∈ e.base_set) (x : F) : e.coord_change e b x = x := by rw [coord_change, e.apply_symm_apply' h] lemma coord_change_same (e : trivialization F proj) {b : B} (h : b ∈ e.base_set) : e.coord_change e b = id := funext $ e.coord_change_same_apply h lemma coord_change_coord_change (e₁ e₂ e₃ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) (x : F) : e₂.coord_change e₃ b (e₁.coord_change e₂ b x) = e₁.coord_change e₃ b x := begin rw [coord_change, e₁.mk_coord_change _ h₁ h₂, ← e₂.coe_coe, e₂.to_local_homeomorph.left_inv, coord_change], rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] end lemma continuous_coord_change (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : continuous (e₁.coord_change e₂ b) := begin refine continuous_snd.comp (e₂.to_local_homeomorph.continuous_on.comp_continuous (e₁.to_local_homeomorph.continuous_on_symm.comp_continuous _ _) _), { exact continuous_const.prod_mk continuous_id }, { exact λ x, e₁.mem_target.2 h₁ }, { intro x, rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] } end /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations, as a homeomorphism. -/ protected def coord_change_homeomorph (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : F ≃ₜ F := { to_fun := e₁.coord_change e₂ b, inv_fun := e₂.coord_change e₁ b, left_inv := λ x, by simp only [*, coord_change_coord_change, coord_change_same_apply], right_inv := λ x, by simp only [*, coord_change_coord_change, coord_change_same_apply], continuous_to_fun := e₁.continuous_coord_change e₂ h₁ h₂, continuous_inv_fun := e₂.continuous_coord_change e₁ h₂ h₁ } @[simp] lemma coord_change_homeomorph_coe (e₁ e₂ : trivialization F proj) {b : B} (h₁ : b ∈ e₁.base_set) (h₂ : b ∈ e₂.base_set) : ⇑(e₁.coord_change_homeomorph e₂ h₁ h₂) = e₁.coord_change e₂ b := rfl variables {F} {B' : Type*} [topological_space B'] lemma is_image_preimage_prod (e : trivialization F proj) (s : set B) : e.to_local_homeomorph.is_image (proj ⁻¹' s) (s ×ˢ univ) := λ x hx, by simp [e.coe_fst', hx] /-- Restrict a `trivialization` to an open set in the base. `-/ protected def restr_open (e : trivialization F proj) (s : set B) (hs : is_open s) : trivialization F proj := { to_local_homeomorph := ((e.is_image_preimage_prod s).symm.restr (is_open.inter e.open_target (hs.prod is_open_univ))).symm, base_set := e.base_set ∩ s, open_base_set := is_open.inter e.open_base_set hs, source_eq := by simp [e.source_eq], target_eq := by simp [e.target_eq, prod_univ], proj_to_fun := λ p hp, e.proj_to_fun p hp.1 } section piecewise lemma frontier_preimage (e : trivialization F proj) (s : set B) : e.source ∩ frontier (proj ⁻¹' s) = proj ⁻¹' (e.base_set ∩ frontier s) := by rw [← (e.is_image_preimage_prod s).frontier.preimage_eq, frontier_prod_univ_eq, (e.is_image_preimage_prod _).preimage_eq, e.source_eq, preimage_inter] /-- Given two bundle trivializations `e`, `e'` of `proj : Z → B` and a set `s : set B` such that the base sets of `e` and `e'` intersect `frontier s` on the same set and `e p = e' p` whenever `proj p ∈ e.base_set ∩ frontier s`, `e.piecewise e' s Hs Heq` is the bundle trivialization over `set.ite s e.base_set e'.base_set` that is equal to `e` on `proj ⁻¹ s` and is equal to `e'` otherwise. -/ noncomputable def piecewise (e e' : trivialization F proj) (s : set B) (Hs : e.base_set ∩ frontier s = e'.base_set ∩ frontier s) (Heq : eq_on e e' $ proj ⁻¹' (e.base_set ∩ frontier s)) : trivialization F proj := { to_local_homeomorph := e.to_local_homeomorph.piecewise e'.to_local_homeomorph (proj ⁻¹' s) (s ×ˢ univ) (e.is_image_preimage_prod s) (e'.is_image_preimage_prod s) (by rw [e.frontier_preimage, e'.frontier_preimage, Hs]) (by rwa e.frontier_preimage), base_set := s.ite e.base_set e'.base_set, open_base_set := e.open_base_set.ite e'.open_base_set Hs, source_eq := by simp [e.source_eq, e'.source_eq], target_eq := by simp [e.target_eq, e'.target_eq, prod_univ], proj_to_fun := by rintro p (⟨he, hs⟩|⟨he, hs⟩); simp * } /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.base_set ∩ e'.base_set` such that `e` equals `e'` on `proj ⁻¹' {a}`, `e.piecewise_le_of_eq e' a He He' Heq` is the bundle trivialization over `set.ite (Iic a) e.base_set e'.base_set` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `e'` otherwise. -/ noncomputable def piecewise_le_of_eq [linear_order B] [order_topology B] (e e' : trivialization F proj) (a : B) (He : a ∈ e.base_set) (He' : a ∈ e'.base_set) (Heq : ∀ p, proj p = a → e p = e' p) : trivialization F proj := e.piecewise e' (Iic a) (set.ext $ λ x, and.congr_left_iff.2 $ λ hx, by simp [He, He', mem_singleton_iff.1 (frontier_Iic_subset _ hx)]) (λ p hp, Heq p $ frontier_Iic_subset _ hp.2) /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.base_set ∩ e'.base_set`, `e.piecewise_le e' a He He'` is the bundle trivialization over `set.ite (Iic a) e.base_set e'.base_set` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `((e' p).1, h (e' p).2)` otherwise, where `h = `e'.coord_change_homeomorph e _ _` is the homeomorphism of the fiber such that `h (e' p).2 = (e p).2` whenever `e p = a`. -/ noncomputable def piecewise_le [linear_order B] [order_topology B] (e e' : trivialization F proj) (a : B) (He : a ∈ e.base_set) (He' : a ∈ e'.base_set) : trivialization F proj := e.piecewise_le_of_eq (e'.trans_fiber_homeomorph (e'.coord_change_homeomorph e He' He)) a He He' $ by { unfreezingI {rintro p rfl }, ext1, { simp [e.coe_fst', e'.coe_fst', *] }, { simp [e'.coord_change_apply_snd, *] } } /-- Given two bundle trivializations `e`, `e'` over disjoint sets, `e.disjoint_union e' H` is the bundle trivialization over the union of the base sets that agrees with `e` and `e'` over their base sets. -/ noncomputable def disjoint_union (e e' : trivialization F proj) (H : disjoint e.base_set e'.base_set) : trivialization F proj := { to_local_homeomorph := e.to_local_homeomorph.disjoint_union e'.to_local_homeomorph (by { rw [e.source_eq, e'.source_eq], exact H.preimage _, }) (by { rw [e.target_eq, e'.target_eq, disjoint_iff_inf_le], intros x hx, exact H.le_bot ⟨hx.1.1, hx.2.1⟩ }), base_set := e.base_set ∪ e'.base_set, open_base_set := is_open.union e.open_base_set e'.open_base_set, source_eq := congr_arg2 (∪) e.source_eq e'.source_eq, target_eq := (congr_arg2 (∪) e.target_eq e'.target_eq).trans union_prod.symm, proj_to_fun := begin rintro p (hp|hp'), { show (e.source.piecewise e e' p).1 = proj p, rw [piecewise_eq_of_mem, e.coe_fst]; exact hp }, { show (e.source.piecewise e e' p).1 = proj p, rw [piecewise_eq_of_not_mem, e'.coe_fst hp'], simp only [e.source_eq, e'.source_eq] at hp' ⊢, exact λ h, H.le_bot ⟨h, hp'⟩ } end } end piecewise end trivialization
cbc53d9e2764388b363afdfdadb61d2783197b85
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/list/permutation.lean
1221305360e015b1b14a4a4a662bf9cfc1f8b691
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,846
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.list.basic /-! # Permutations of a list In this file we prove properties about `list.permutations`, a list of all permutations of a list. It is defined in `data.list.defs`. ## Order of the permutations Designed for performance, the order in which the permutations appear in `list.permutations` is rather intricate and not very amenable to induction. That's why we also provide `list.permutations'` as a less efficient but more straightforward way of listing permutations. ### `list.permutations` TODO. In the meantime, you can try decrypting the docstrings. ### `list.permutations'` The list of partitions is built by recursion. The permutations of `[]` are `[[]]`. Then, the permutations of `a :: l` are obtained by taking all permutations of `l` in order and adding `a` in all positions. Hence, to build `[0, 1, 2, 3].permutations'`, it does * `[[]]` * `[[3]]` * `[[2, 3], [3, 2]]]` * `[[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]` * `[[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0],` `[0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0],` `[0, 2, 3, 1], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0],` `[0, 1, 3, 2], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0],` `[0, 3, 1, 2], [3, 0, 1, 2], [3, 1, 0, 2], [3, 1, 2, 0],` `[0, 3, 2, 1], [3, 0, 2, 1], [3, 2, 0, 1], [3, 2, 1, 0]]` ## TODO Show that `l.nodup → l.permutations.nodup`. See `data.fintype.list`. -/ open nat variables {α β : Type*} namespace list lemma permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] lemma permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] lemma permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end /-- The `r` argument to `permutations_aux2` is the same as appending. -/ lemma permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * /-- The `ts` argument to `permutations_aux2` can be folded into the `f` argument. -/ lemma permutations_aux2_comp_append {t : α} {ts ys : list α} {r : list β} (f : list α → β) : (permutations_aux2 t [] r ys $ λ x, f (x ++ ts)).2 = (permutations_aux2 t ts r ys f).2 := begin induction ys generalizing f, { simp }, { simp [ys_ih (λ xs, f (ys_hd :: xs))] }, end lemma map_permutations_aux2' {α β α' β'} (g : α → α') (g' : β → β') (t : α) (ts ys : list α) (r : list β) (f : list α → β) (f' : list α' → β') (H : ∀ a, g' (f a) = f' (map g a)) : map g' (permutations_aux2 t ts r ys f).2 = (permutations_aux2 (g t) (map g ts) (map g' r) (map g ys) f').2 := begin induction ys generalizing f f'; simp *, apply ys_ih, simp [H], end /-- The `f` argument to `permutations_aux2` when `r = []` can be eliminated. -/ lemma map_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts [] ys id).2.map f = (permutations_aux2 t ts [] ys f).2 := begin convert map_permutations_aux2' id _ _ _ _ _ _ _ _; simp only [map_id, id.def], exact (λ _, rfl) end /-- An expository lemma to show how all of `ts`, `r`, and `f` can be eliminated from `permutations_aux2`. `(permutations_aux2 t [] [] ys id).2`, which appears on the RHS, is a list whose elements are produced by inserting `t` into every non-terminal position of `ys` in order. As an example: ```lean #eval permutations_aux2 1 [] [] [2, 3, 4] id -- [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4]] ``` -/ lemma permutations_aux2_snd_eq (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r ys f).2 = (permutations_aux2 t [] [] ys id).2.map (λ x, f (x ++ ts)) ++ r := by rw [← permutations_aux2_append, map_permutations_aux2, permutations_aux2_comp_append] lemma map_map_permutations_aux2 {α α'} (g : α → α') (t : α) (ts ys : list α) : map (map g) (permutations_aux2 t ts [] ys id).2 = (permutations_aux2 (g t) (map g ts) [] (map g ys) id).2 := map_permutations_aux2' _ _ _ _ _ _ _ _ (λ _, rfl) lemma map_map_permutations'_aux (f : α → β) (t : α) (ts : list α) : map (map f) (permutations'_aux t ts) = permutations'_aux (f t) (map f ts) := by induction ts with a ts ih; [refl, {simp [← ih], refl}] lemma permutations'_aux_eq_permutations_aux2 (t : α) (ts : list α) : permutations'_aux t ts = (permutations_aux2 t [] [ts ++ [t]] ts id).2 := begin induction ts with a ts ih, {refl}, simp [permutations'_aux, permutations_aux2_snd_cons, ih], simp only [← permutations_aux2_append] {single_pass := tt}, simp [map_permutations_aux2], end lemma mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split, { rintro (e | ⟨l₁, l₂, l0, ye, _⟩), { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } }, { rintro ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩, { simp [ye] }, { simp only [cons_append] at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } end lemma mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2 lemma length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * lemma foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] lemma mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} : l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := have (∃ (a : list α), a ∈ L ∧ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts), from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩, λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] lemma length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] lemma length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α)) (n) (H : ∀ l ∈ L, length l = n) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, have sum_map : sum (map length L) = n * length L := ih (λ l m, H l (mem_cons_of_mem _ m)), have length_l : length l = n := H _ (mem_cons_self _ _), simp [sum_map, length_l, mul_add, add_comm] end @[simp] lemma permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] lemma permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl @[simp] lemma permutations_nil : permutations ([] : list α) = [[]] := by rw [permutations, permutations_aux_nil] lemma map_permutations_aux (f : α → β) : ∀ (ts is : list α), map (map f) (permutations_aux ts is) = permutations_aux (map f ts) (map f is) := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2, rw map at IH2, simp only [foldr_permutations_aux2, map_append, map, map_map_permutations_aux2, permutations, bind_map, IH1, append_assoc, permutations_aux_cons, cons_bind, ← IH2, map_bind], end lemma map_permutations (f : α → β) (ts : list α) : map (map f) (permutations ts) = permutations (map f ts) := by rw [permutations, permutations, map, map_permutations_aux, map] lemma map_permutations' (f : α → β) (ts : list α) : map (map f) (permutations' ts) = permutations' (map f ts) := by induction ts with t ts ih; [refl, simp [← ih, map_bind, ← map_map_permutations'_aux, bind_map]] lemma permutations_aux_append (is is' ts : list α) : permutations_aux (is ++ ts) is' = (permutations_aux is is').map (++ ts) ++ permutations_aux ts (is.reverse ++ is') := begin induction is with t is ih generalizing is', {simp}, simp [foldr_permutations_aux2, ih, bind_map], congr' 2, funext ys, rw [map_permutations_aux2], simp only [← permutations_aux2_comp_append] {single_pass := tt}, simp only [id, append_assoc], end lemma permutations_append (is ts : list α) : permutations (is ++ ts) = (permutations is).map (++ ts) ++ permutations_aux ts is.reverse := by simp [permutations, permutations_aux_append] end list
8e14758014f4324e4b0240e900c6e811c798aad9
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Tactic/Location.lean
51bd35d2b4b5ec79c8c3befb93763d0202cfb3d5
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
2,222
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.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic /-- Denotes a set of locations where a tactic should be applied for the main goal. See also `withLocation`. -/ inductive Location where /-- Apply the tactic everywhere. -/ | wildcard /-- `hypotheses` are hypothesis names in the main goal that the tactic should be applied to. If `type` is true, then the tactic should also be applied to the target type. -/ | targets (hypotheses : Array Syntax) (type : Bool) /- Recall that ``` syntax locationWildcard := "*" syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) ``` -/ def expandLocation (stx : Syntax) : Location := let arg := stx[1] if arg.getKind == ``Parser.Tactic.locationWildcard then Location.wildcard else Location.targets arg[0].getArgs (!arg[1].isNone) def expandOptLocation (stx : Syntax) : Location := if stx.isNone then Location.targets #[] true else expandLocation stx[0] open Meta /-- Runs the given `atLocal` and `atTarget` methods on each of the locations selected by the given `loc`. If any of the selected tactic applications fail, it will call `failed` with the main goal mvar. -/ def withLocation (loc : Location) (atLocal : FVarId → TacticM Unit) (atTarget : TacticM Unit) (failed : MVarId → TacticM Unit) : TacticM Unit := do match loc with | Location.targets hyps type => hyps.forM fun hyp => withMainContext do let fvarId ← getFVarId hyp atLocal fvarId if type then atTarget | Location.wildcard => let worked ← tryTactic <| withMainContext <| atTarget withMainContext do let mut worked := worked -- We must traverse backwards because the given `atLocal` may use the revert/intro idiom for fvarId in (← getLCtx).getFVarIds.reverse do worked := worked || (← tryTactic <| withMainContext <| atLocal fvarId) unless worked do failed (← getMainGoal) end Lean.Elab.Tactic
6bc38ffa10b05fa52375a75320f669097a518a68
367134ba5a65885e863bdc4507601606690974c1
/src/topology/uniform_space/uniform_convergence.lean
b6ff3e3d303a7ee3e4e018a203e4af7955b4d2da
[ "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
16,649
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.uniform_space.basic /-! # Uniform convergence A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality `dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit, most notably continuity. We prove this in the file, defining the notion of uniform convergence in the more general setting of uniform spaces, and with respect to an arbitrary indexing set endowed with a filter (instead of just `ℕ` with `at_top`). ## Main results Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β` (where the index `n` belongs to an indexing type `ι` endowed with a filter `p`). * `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has `(f y, Fₙ y) ∈ u` for all `y ∈ s`. * `tendsto_uniformly F f p`: same notion with `s = univ`. * `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous on this set is itself continuous on this set. * `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous. * `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. * `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. We also define notions where the convergence is locally uniform, called `tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems all have corresponding versions under locally uniform convergence. ## Implementation notes Most results hold under weaker assumptions of locally uniform approximation. In a first section, we prove the results under these weaker assumptions. Then, we derive the results on uniform convergence from them. ## Tags Uniform limit, uniform convergence, tends uniformly to -/ noncomputable theory open_locale topological_space classical uniformity open set filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-! ### Different notions of uniform convergence We define uniform convergence and locally uniform convergence, on a set or in the whole space. -/ variables {ι : Type*} [uniform_space β] {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α} /-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/ def tendsto_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x ∈ s, (f x, F n x) ∈ u /-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x`. -/ def tendsto_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x, (f x, F n x) ∈ u lemma tendsto_uniformly_on_univ : tendsto_uniformly_on F f p univ ↔ tendsto_uniformly F f p := by simp [tendsto_uniformly_on, tendsto_uniformly] lemma tendsto_uniformly_on.mono {s' : set α} (h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' := λ u hu, (h u hu).mono (λ n hn x hx, hn x (h' hx)) lemma tendsto_uniformly.tendsto_uniformly_on (h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s := (tendsto_uniformly_on_univ.2 h).mono (subset_univ s) /-- Composing on the right by a function preserves uniform convergence on a set -/ lemma tendsto_uniformly_on.comp (h : tendsto_uniformly_on F f p s) (g : γ → α) : tendsto_uniformly_on (λ n, F n ∘ g) (f ∘ g) p (g ⁻¹' s) := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x hx, hn _ hx end /-- Composing on the right by a function preserves uniform convergence -/ lemma tendsto_uniformly.comp (h : tendsto_uniformly F f p) (g : γ → α) : tendsto_uniformly (λ n, F n ∘ g) (f ∘ g) p := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x, hn _ end variable [topological_space α] /-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/ def tendsto_locally_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u /-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x`. -/ def tendsto_locally_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ (x : α), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u lemma tendsto_uniformly_on.tendsto_locally_uniformly_on (h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s := λ u hu x hx, ⟨s, self_mem_nhds_within, h u hu⟩ lemma tendsto_uniformly.tendsto_locally_uniformly (h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p := λ u hu x, ⟨univ, univ_mem_sets, by simpa using h u hu⟩ lemma tendsto_locally_uniformly_on.mono (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_locally_uniformly_on F f p s' := begin assume u hu x hx, rcases h u hu x (h' hx) with ⟨t, ht, H⟩, exact ⟨t, nhds_within_mono x h' ht, H.mono (λ n, id)⟩ end lemma tendsto_locally_uniformly_on_univ : tendsto_locally_uniformly_on F f p univ ↔ tendsto_locally_uniformly F f p := by simp [tendsto_locally_uniformly_on, tendsto_locally_uniformly, nhds_within_univ] lemma tendsto_locally_uniformly_on.comp [topological_space γ] {t : set γ} (h : tendsto_locally_uniformly_on F f p s) (g : γ → α) (hg : maps_to g t s) (cg : continuous_on g t) : tendsto_locally_uniformly_on (λ n, (F n) ∘ g) (f ∘ g) p t := begin assume u hu x hx, rcases h u hu (g x) (hg hx) with ⟨a, ha, H⟩, have : g⁻¹' a ∈ 𝓝[t] x := ((cg x hx).preimage_mem_nhds_within' (nhds_within_mono (g x) hg.image_subset ha)), exact ⟨g ⁻¹' a, this, H.mono (λ n hn y hy, hn _ hy)⟩ end lemma tendsto_locally_uniformly.comp [topological_space γ] (h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) : tendsto_locally_uniformly (λ n, (F n) ∘ g) (f ∘ g) p := begin rw ← tendsto_locally_uniformly_on_univ at h ⊢, rw continuous_iff_continuous_on_univ at cg, exact h.comp _ (maps_to_univ _ _) cg end /-! ### Uniform approximation In this section, we give lemmas ensuring that a function is continuous if it can be approximated uniformly by continuous functions. We give various versions, within a set or the whole space, at a single point or at all points, with locally uniform approximation or uniform approximation. All the statements are derived from a statement about locally uniform approximation within a set at a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/ /-- A function which can be locally uniformly approximated by functions which are continuous within a set at a point is continuous within this set at this point. -/ lemma continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (hx : x ∈ s) (L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝[s] x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_within_at (F n) s x) : continuous_within_at f s x := begin apply uniform.continuous_within_at_iff'_left.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, obtain ⟨u₂, h₂, hsymm, u₂₁⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), (∀{a b}, (a, b) ∈ u → (b, a) ∈ u) ∧ comp_rel u u ⊆ u₁ := comp_symm_of_uniformity h₁, rcases L u₂ h₂ with ⟨t, tx, n, ht⟩, have A : ∀ᶠ y in 𝓝[s] x, (f y, F n y) ∈ u₂ := eventually.mono tx ht, have B : ∀ᶠ y in 𝓝[s] x, (F n y, F n x) ∈ u₂ := uniform.continuous_within_at_iff'_left.1 (C n) h₂, have C : ∀ᶠ y in 𝓝[s] x, (f y, F n x) ∈ u₁ := (A.and B).mono (λ y hy, u₂₁ (prod_mk_mem_comp_rel hy.1 hy.2)), have : (F n x, f x) ∈ u₁ := u₂₁ (prod_mk_mem_comp_rel (refl_mem_uniformity h₂) (hsymm (A.self_of_nhds_within hx))), exact C.mono (λ y hy, u₁₀ (prod_mk_mem_comp_rel hy this)) end /-- A function which can be locally uniformly approximated by functions which are continuous at a point is continuous at this point. -/ lemma continuous_at_of_locally_uniform_approx_of_continuous_at (L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_at (F n) x) : continuous_at f x := begin simp only [← continuous_within_at_univ] at C ⊢, apply continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (mem_univ _) _ C, simpa [nhds_within_univ] using L end /-- A function which can be locally uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_locally_uniform_approx_of_continuous_on (L : ∀ (x ∈ s) (u ∈ 𝓤 β), ∃t ∈ 𝓝[s] x, ∃n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_on (F n) s) : continuous_on f s := λ x hx, continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx (L x hx) (λ n, C n x hx) /-- A function which can be uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_uniform_approx_of_continuous_on (L : ∀ u ∈ 𝓤 β, ∃ n, ∀ y ∈ s, (f y, F n y) ∈ u) : (∀ n, continuous_on (F n) s) → continuous_on f s := continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, ⟨s, self_mem_nhds_within, L u hu⟩) /-- A function which can be locally uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_locally_uniform_approx_of_continuous (L : ∀ (x : α), ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous (F n)) : continuous f := begin simp only [continuous_iff_continuous_on_univ] at ⊢ C, apply continuous_on_of_locally_uniform_approx_of_continuous_on _ C, simpa [nhds_within_univ] using L end /-- A function which can be uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_uniform_approx_of_continuous (L : ∀ u ∈ 𝓤 β, ∃ N, ∀ y, (f y, F N y) ∈ u) : (∀ n, continuous (F n)) → continuous f := continuous_of_locally_uniform_approx_of_continuous $ λx u hu, ⟨univ, by simpa [filter.univ_mem_sets] using L u hu⟩ /-! ### Uniform limits From the previous statements on uniform approximation, we deduce continuity results for uniform limits. -/ /-- A locally uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_locally_uniformly_on.continuous_on (h : tendsto_locally_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) [ne_bot p] : continuous_on f s := begin apply continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, _) hc, rcases h u hu x hx with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists⟩ end /-- A uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_uniformly_on.continuous_on (h : tendsto_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) [ne_bot p] : continuous_on f s := h.tendsto_locally_uniformly_on.continuous_on hc /-- A locally uniform limit of continuous functions is continuous. -/ lemma tendsto_locally_uniformly.continuous (h : tendsto_locally_uniformly F f p) (hc : ∀ n, continuous (F n)) [ne_bot p] : continuous f := begin apply continuous_of_locally_uniform_approx_of_continuous (λ x u hu, _) hc, rcases h u hu x with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists⟩ end /-- A uniform limit of continuous functions is continuous. -/ lemma tendsto_uniformly.continuous (h : tendsto_uniformly F f p) (hc : ∀ n, continuous (F n)) [ne_bot p] : continuous f := h.tendsto_locally_uniformly.continuous hc /-! ### Composing limits under uniform convergence In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In this paragraph, we prove variations around this statement. -/ /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f` which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit_within (h : continuous_within_at f s x) (hg : tendsto g p (𝓝[s] x)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin apply uniform.tendsto_nhds_right.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, rcases hunif u₁ h₁ with ⟨s, sx, hs⟩, have A : ∀ᶠ n in p, g n ∈ s := hg sx, have B : ∀ᶠ n in p, (f x, f (g n)) ∈ u₁ := hg (uniform.continuous_within_at_iff'_right.1 h h₁), refine ((hs.and A).and B).mono (λ y hy, _), rcases hy with ⟨⟨H1, H2⟩, H3⟩, exact u₁₀ (prod_mk_mem_comp_rel H3 (H1 _ H2)) end /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit (h : continuous_at f x) (hg : tendsto g p (𝓝 x)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin rw ← continuous_within_at_univ at h, rw ← nhds_within_univ at hunif hg, exact tendsto_comp_of_locally_uniform_limit_within h hg hunif end /-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/ lemma tendsto_locally_uniformly_on.tendsto_comp (h : tendsto_locally_uniformly_on F f p s) (hf : continuous_within_at f s x) (hx : x ∈ s) (hg : tendsto g p (𝓝[s] x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, h u hu x hx) /-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. -/ lemma tendsto_uniformly_on.tendsto_comp (h : tendsto_uniformly_on F f p s) (hf : continuous_within_at f s x) (hg : tendsto g p (𝓝[s] x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, ⟨s, self_mem_nhds_within, h u hu⟩) /-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_locally_uniformly.tendsto_comp (h : tendsto_locally_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit hf hg (λ u hu, h u hu x) /-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_uniformly.tendsto_comp (h : tendsto_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := h.tendsto_locally_uniformly.tendsto_comp hf hg
b76c38ea4794b7a809636b8a7fb485fb8d3c83e1
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.14.lean
0bb51519ad8b88812a13764ec7d2b48222eed189
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
804
lean
import standard namespace hide variables {A : Type} (R : A → A → Prop) definition reflexive : Prop := ∀ (a : A), R a a definition symmetric : Prop := ∀ ⦃a b : A⦄, R a b → R b a definition transitive : Prop := ∀ ⦃a b c : A⦄, R a b → R b c → R a c definition euclidean : Prop := ∀ ⦃a b c : A⦄, R a b → R a c → R b c variable {R} theorem th1 (refl : reflexive R) (eucl : euclidean R) : symmetric R := take a b : A, assume (H : R a b), show R b a, from eucl H !refl theorem th2 (symm : symmetric R) (eucl : euclidean R) : transitive R := take (a b c : A), assume (H : R a b) (K : R b c), have H' : R b a, from symm H, show R a c, from eucl H' K -- BEGIN theorem th3 (refl : reflexive R) (eucl : euclidean R) : transitive R := th2 (th1 refl eucl) eucl -- END end hide
02a20d29cf886e0674037b4e0735f1502fe2e26d
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/src/for_mathlib/filter_decides.lean
81b4897389168ba2e5dfafb4239cfdf86b933aa3
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
1,858
lean
import order.filter import for_mathlib.boolean_subalgebra /- We say a filter F *decides* a set S if either S or Sᶜ belongs to F. The sets decided by a filter form a boolean subalgebra. For a fixed boolean subalgebra A, an *ultrafilter on A* is a filter which decides every member of A. To check that a filter F is an ultrafilter on A, it then suffices to check that it decides the members of a family of elements of A which generate it as a boolean subalgebra. An ultrafilter in the mathlib sense is the same as an ultrafilter on the boolean algebra of all sets. -/ variables {α : Type*} namespace filter def decides (f : filter α) (s : set α) : Prop := s ∈ f ∨ sᶜ ∈ f variables {f : filter α} {s t : set α} lemma decides_empty : f.decides ∅ := or.inr (by { convert f.univ_sets, simp }) lemma decides.union (hs : f.decides s) (ht : f.decides t) : f.decides (s ∪ t) := begin -- If either s or t belongs to f, then so does s ∪ t cases hs, { left, apply f.sets_of_superset hs (set.subset_union_left _ _) }, cases ht, { left, apply f.sets_of_superset ht (set.subset_union_right _ _) }, -- Otherwise, both sᶜ and tᶜ belong to f right, rw set.compl_union, apply f.inter_sets hs ht end lemma decides.compl (hs : f.decides s) : f.decides (sᶜ) := begin unfold decides, rw [or_comm, set.compl_compl], exact hs end lemma is_boolean_subalgebra_decides : is_boolean_subalgebra f.decides := ⟨decides_empty, λ _ _, decides.union, λ _, decides.compl⟩ /-- If a filter decides every member of S, then it also decides every member of the boolean subalgebra generated by S. -/ lemma decides_gen {S : set (set α)} (h : ∀ s ∈ S, f.decides s) : ∀ {t : set α}, t ∈ boolean_subalgebra.gen S → f.decides t := (boolean_subalgebra.gen_subset_iff_subset is_boolean_subalgebra_decides).mpr h end filter
57da5802c2001117199d438797e115425ada184a
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/sigma/basic.lean
209d7e533b7ca43c0306d03618cbb6616ab6e3e1
[ "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
4,042
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ section sigma variables {α : Type*} {β : α → Type*} instance [inhabited α] [inhabited (β (default α))] : inhabited (sigma β) := ⟨⟨default α, default (β (default α))⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (sigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n e₁)) end @[simp] theorem sigma.mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : sigma.mk a₁ b₁ = ⟨a₂, b₂⟩ ↔ (a₁ = a₂ ∧ b₁ == b₂) := ⟨sigma.mk.inj, λ ⟨h₁, h₂⟩, by congr; assumption⟩ @[simp] theorem sigma.forall {p : (Σ a, β a) → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem sigma.exists {p : (Σ a, β a) → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ variables {α₁ : Type*} {α₂ : Type*} {β₁ : α₁ → Type*} {β₂ : α₂ → Type*} /-- Map the left and right components of a sigma -/ def sigma.map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) : sigma β₁ → sigma β₂ | ⟨a, b⟩ := ⟨f₁ a, f₂ a b⟩ end sigma section psigma variables {α : Sort*} {β : α → Sort*} instance [inhabited α] [inhabited (β (default α))] : inhabited (psigma β) := ⟨⟨default α, default (β (default α))⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (psigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n e₁)) end theorem psigma.mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : @psigma.mk α β a₁ b₁ = @psigma.mk α β a₂ b₂ ↔ (a₁ = a₂ ∧ b₁ == b₂) := iff.intro psigma.mk.inj $ assume ⟨h₁, h₂⟩, match a₁, a₂, b₁, b₂, h₁, h₂ with _, _, _, _, eq.refl a, heq.refl b := rfl end variables {α₁ : Sort*} {α₂ : Sort*} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} /-- Map the left and right components of a sigma -/ def psigma.map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) : psigma β₁ → psigma β₂ | ⟨a, b⟩ := ⟨f₁ a, f₂ a b⟩ end psigma section subtype variables {α : Sort*} {β : α → Prop} @[simp] theorem subtype.coe_eta {α : Type*} {β : α → Prop} (a : {a // β a}) (h : β a) : subtype.mk ↑a h = a := subtype.eta _ _ @[simp] theorem subtype.coe_mk {α : Type*} {β : α → Prop} (a h) : (@subtype.mk α β a h : α) = a := rfl @[simp] theorem subtype.mk_eq_mk {α : Type*} {β : α → Prop} {a h a' h'} : @subtype.mk α β a h = @subtype.mk α β a' h' ↔ a = a' := ⟨λ H, by injection H, λ H, by congr; assumption⟩ @[simp] theorem subtype.forall {p : {a // β a} → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem subtype.exists {p : {a // β a} → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ end subtype
dc3d928a0eb96986c9392e87faa07eaf07a98494
a2ee6a66690e8da666951cac0c243d42db11f9f3
/src/algebra/continued_fractions/computation/approximations.lean
a3b38bd994c1294cfb2c87f9484806021367f2cc
[ "Apache-2.0" ]
permissive
shyamalschandra/mathlib
6d414d7c334bf383e764336843f065bd14c44273
ca679acad147870b2c5087d90fe3550f107dea49
refs/heads/master
1,671,730,354,335
1,601,883,576,000
1,601,883,576,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,642
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.translations import algebra.continued_fractions.continuants_recurrence import algebra.continued_fractions.terminated_stable import data.nat.fib /-! # Approximations for Continued Fraction Computations (`gcf.of`) ## Summary Let us write `gcf` for `generalized_continued_fraction`. This file contains useful approximations for the values involved in the continued fractions computation `gcf.of`. ## Main Theorems - `gcf.of_part_num_eq_one`: shows that all partial numerators `aᵢ` are equal to one. - `gcf.exists_int_eq_of_part_denom`: shows that all partial denominators `bᵢ` correspond to an integer. - `gcf.one_le_of_nth_part_denom`: shows that `1 ≤ bᵢ`. - `gcf.succ_nth_fib_le_of_nth_denom`: shows that the `n`th denominator `Bₙ` is greater than or equal to the `n + 1`th fibonacci number `nat.fib (n + 1)`. - `gcf.le_of_succ_nth_denom`: shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator of the continued fraction. ## References - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {K : Type*} {v : K} {n : ℕ} [discrete_linear_ordered_field K] [floor_ring K] /- We begin with some lemmas about the stream of `int_fract_pair`s, which presumably are not of great interest for the end user. -/ namespace int_fract_pair /-- Shows that the fractional parts of the stream are in `[0,1)`. -/ lemma nth_stream_fr_nonneg_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr ∧ ifp_n.fr < 1 := begin cases n, case nat.zero { have : int_fract_pair.of v = ifp_n, by injection nth_stream_eq, simp [fract_lt_one, fract_nonneg, int_fract_pair.of, this.symm] }, case nat.succ { rcases (succ_nth_stream_eq_some_iff.elim_left nth_stream_eq) with ⟨_, _, _, if_of_eq_ifp_n⟩, simp [fract_lt_one, fract_nonneg, int_fract_pair.of, if_of_eq_ifp_n.symm] } end /-- Shows that the fractional parts of the stream are nonnegative. -/ lemma nth_stream_fr_nonneg {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : 0 ≤ ifp_n.fr := (nth_stream_fr_nonneg_lt_one nth_stream_eq).left /-- Shows that the fractional parts of the stream smaller than one. -/ lemma nth_stream_fr_lt_one {ifp_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) : ifp_n.fr < 1 := (nth_stream_fr_nonneg_lt_one nth_stream_eq).right /-- Shows that the integer parts of the stream are at least one. -/ lemma one_le_succ_nth_stream_b {ifp_succ_n : int_fract_pair K} (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : 1 ≤ ifp_succ_n.b := begin obtain ⟨ifp_n, nth_stream_eq, stream_nth_fr_ne_zero, ⟨_⟩⟩ : ∃ ifp_n, int_fract_pair.stream v 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 succ_nth_stream_eq, change 1 ≤ ⌊ifp_n.fr⁻¹⌋, suffices : 1 ≤ ifp_n.fr⁻¹, { rw_mod_cast [le_floor], assumption }, suffices : ifp_n.fr ≤ 1, { have h : 0 < ifp_n.fr := lt_of_le_of_ne (nth_stream_fr_nonneg nth_stream_eq) stream_nth_fr_ne_zero.symm, apply one_le_inv h this }, simp [(le_of_lt (nth_stream_fr_lt_one nth_stream_eq))] end local attribute [reducible] with_one /-- Shows that the `n + 1`th integer part `bₙ₊₁` of the stream is smaller or equal than the inverse of the `n`th fractional part `frₙ` of the stream. This result is straight-forward as `bₙ₊₁` is defined as the floor of `1 / frₙ` -/ lemma succ_nth_stream_b_le_nth_stream_fr_inv {ifp_n ifp_succ_n : int_fract_pair K} (nth_stream_eq : int_fract_pair.stream v n = some ifp_n) (succ_nth_stream_eq : int_fract_pair.stream v (n + 1) = some ifp_succ_n) : (ifp_succ_n.b : K) ≤ ifp_n.fr⁻¹ := begin suffices : (⌊ifp_n.fr⁻¹⌋ : K) ≤ ifp_n.fr⁻¹, by { cases ifp_n with _ ifp_n_fr, have : ifp_n_fr ≠ 0, by { intro h, simpa [h, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq }, have : int_fract_pair.of ifp_n_fr⁻¹ = ifp_succ_n, by { rw with_one.coe_inj.symm, simpa [this, int_fract_pair.stream, nth_stream_eq] using succ_nth_stream_eq }, rwa ←this }, exact (floor_le ifp_n.fr⁻¹) end end int_fract_pair /- Next we translate above results about the stream of `int_fract_pair`s to the computed continued fraction `gcf.of`. -/ /-- Shows that the integer parts of the continued fraction are at least one. -/ lemma of_one_le_nth_part_denom {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : 1 ≤ b := begin obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, (gcf.of v).s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, obtain ⟨ifp_n, succ_nth_stream_eq, ifp_n_b_eq_gp_n_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp_n.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, rw [←ifp_n_b_eq_gp_n_b], exact_mod_cast (int_fract_pair.one_le_succ_nth_stream_b succ_nth_stream_eq) end /-- Shows that the partial numerators `aᵢ` of the continued fraction are equal to one and the partial denominators `bᵢ` correspond to integers. -/ lemma of_part_num_eq_one_and_exists_int_part_denom_eq {gp : gcf.pair K} (nth_s_eq : (gcf.of v).s.nth n = some gp) : gp.a = 1 ∧ ∃ (z : ℤ), gp.b = (z : K) := begin obtain ⟨ifp, stream_succ_nth_eq, ifp_b_eq_gp_b⟩ : ∃ ifp, int_fract_pair.stream v (n + 1) = some ifp ∧ (ifp.b : K) = gp.b, from int_fract_pair.exists_succ_nth_stream_of_gcf_of_nth_eq_some nth_s_eq, have : (gcf.of v).s.nth n = some ⟨1, ifp.b⟩, from nth_of_eq_some_of_succ_nth_int_fract_pair_stream stream_succ_nth_eq, have : some gp = some ⟨1, ifp.b⟩, by rwa nth_s_eq at this, have : gp = ⟨1, ifp.b⟩, by injection this, -- We know the shape of gp, so now we just have to split the goal and use this knowledge. cases gp, split, { injection this }, { existsi ifp.b, injection this } end /-- Shows that the partial numerators `aᵢ` are equal to one. -/ lemma of_part_num_eq_one {a : K} (nth_part_num_eq : (gcf.of v).partial_numerators.nth n = some a) : a = 1 := begin obtain ⟨gp, nth_s_eq, gp_a_eq_a_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.a = a, from exists_s_a_of_part_num nth_part_num_eq, have : gp.a = 1, from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).left, rwa gp_a_eq_a_n at this end /-- Shows that the partial denominators `bᵢ` correspond to an integer. -/ lemma exists_int_eq_of_part_denom {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : ∃ (z : ℤ), b = (z : K) := begin obtain ⟨gp, nth_s_eq, gp_b_eq_b_n⟩ : ∃ gp, (gcf.of v).s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, have : ∃ (z : ℤ), gp.b = (z : K), from (of_part_num_eq_one_and_exists_int_part_denom_eq nth_s_eq).right, rwa gp_b_eq_b_n at this end /- One of our next goals is to show that `Bₙ₊₁ ≥ bₙ * Bₙ`. For this, we first show that the partial denominators `Bₙ` are bounded from below by the fibonacci sequence `nat.fib`. This then implies that `0 ≤ Bₙ` and hence `Bₙ₊₂ = bₙ₊₁ * Bₙ₊₁ + Bₙ ≥ bₙ₊₁ * Bₙ₊₁ + 0 = bₙ₊₁ * Bₙ₊₁`. -/ -- open `nat` as we will make use of fibonacci numbers. open nat lemma fib_le_of_continuants_aux_b : (n ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 2)) → (fib n : K) ≤ ((gcf.of v).continuants_aux n).b := nat.strong_induction_on n begin clear n, assume n IH hyp, rcases n with _|_|n, { simp [fib_succ_succ, continuants_aux] }, -- case n = 0 { simp [fib_succ_succ, continuants_aux] }, -- case n = 1 { let g := gcf.of v, -- case 2 ≤ n have : ¬(n + 2 ≤ 1), by linarith, have not_terminated_at_n : ¬g.terminated_at n, from or.resolve_left hyp this, obtain ⟨gp, s_ppred_nth_eq⟩ : ∃ gp, g.s.nth n = some gp, from option.ne_none_iff_exists'.mp not_terminated_at_n, set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux suffices : (fib n : K) + fib (n + 1) ≤ gp.a * ppconts.b + gp.b * pconts.b, by simpa [fib_succ_succ, add_comm, (continuants_aux_recurrence s_ppred_nth_eq ppconts_eq pconts_eq)], -- make use of the fact that gp.a = 1 suffices : (fib n : K) + fib (n + 1) ≤ ppconts.b + gp.b * pconts.b, by simpa [(of_part_num_eq_one $ part_num_eq_s_a s_ppred_nth_eq)], have not_terminated_at_pred_n : ¬g.terminated_at (n - 1), from mt (terminated_stable $ nat.sub_le n 1) not_terminated_at_n, have not_terminated_at_ppred_n : ¬terminated_at g (n - 2), from mt (terminated_stable (n - 1).pred_le) not_terminated_at_pred_n, -- use the IH to get the inequalities for `pconts` and `ppconts` have : (fib (n + 1) : K) ≤ pconts.b, from IH _ (nat.lt.base $ n + 1) (or.inr not_terminated_at_pred_n), have ppred_nth_fib_le_ppconts_B : (fib n : K) ≤ ppconts.b, from IH n (lt_trans (nat.lt.base n) $ nat.lt.base $ n + 1) (or.inr not_terminated_at_ppred_n), suffices : (fib (n + 1) : K) ≤ gp.b * pconts.b, solve_by_elim [(add_le_add ppred_nth_fib_le_ppconts_B)], -- finally use the fact that 1 ≤ gp.b to solve the goal suffices : 1 * (fib (n + 1) : K) ≤ gp.b * pconts.b, by rwa [one_mul] at this, have one_le_gp_b : (1 : K) ≤ gp.b, from of_one_le_nth_part_denom (part_denom_eq_s_b s_ppred_nth_eq), have : (0 : K) ≤ fib (n + 1), by exact_mod_cast (fib (n + 1)).zero_le, have : (0 : K) ≤ gp.b, from le_trans zero_le_one one_le_gp_b, mono } end /-- Shows that the `n`th denominator is greater than or equal to the `n + 1`th fibonacci number, that is `nat.fib (n + 1) ≤ Bₙ`. -/ lemma succ_nth_fib_le_of_nth_denom (hyp: n = 0 ∨ ¬(gcf.of v).terminated_at (n - 1)) : (fib (n + 1) : K) ≤ (gcf.of v).denominators n := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], have : (n + 1) ≤ 1 ∨ ¬(gcf.of v).terminated_at (n - 1), by { cases n, case nat.zero : { exact (or.inl $ le_refl 1) }, case nat.succ : { exact or.inr (or.resolve_left hyp n.succ_ne_zero) } }, exact (fib_le_of_continuants_aux_b this) end /- As a simple consequence, we can now derive that all denominators are nonnegative. -/ lemma zero_le_of_continuants_aux_b : 0 ≤ ((gcf.of v).continuants_aux n).b := begin let g := gcf.of v, induction n with n IH, case nat.zero: { refl }, case nat.succ: { cases (decidable.em $ g.terminated_at (n - 1)) with terminated not_terminated, { cases n, { simp[zero_le_one] }, { have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_step_of_terminated terminated, simp[this, IH] } }, { calc (0 : K) ≤ fib (n + 1) : by exact_mod_cast (n + 1).fib.zero_le ... ≤ ((gcf.of v).continuants_aux (n + 1)).b : fib_le_of_continuants_aux_b (or.inr not_terminated) } } end /-- Shows that all denominators are nonnegative. -/ lemma zero_le_of_denom : 0 ≤ (gcf.of v).denominators n := by { rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact zero_le_of_continuants_aux_b } lemma le_of_succ_succ_nth_continuants_aux_b {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : b * ((gcf.of v).continuants_aux $ n + 1).b ≤ ((gcf.of v).continuants_aux $ n + 2).b := begin set g := gcf.of v with g_eq, obtain ⟨gp_n, nth_s_eq, ⟨_⟩⟩ : ∃ gp_n, g.s.nth n = some gp_n ∧ gp_n.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, let conts := g.continuants_aux (n + 2), set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, -- use the recurrence of continuants_aux and the fact that gp_n.a = 1 suffices : gp_n.b * pconts.b ≤ ppconts.b + gp_n.b * pconts.b, by { have : gp_n.a = 1, from of_part_num_eq_one (part_num_eq_s_a nth_s_eq), finish [(gcf.continuants_aux_recurrence nth_s_eq ppconts_eq pconts_eq)] }, have : 0 ≤ ppconts.b, from zero_le_of_continuants_aux_b, solve_by_elim [le_add_of_nonneg_of_le, le_refl] end /-- Shows that `Bₙ₊₁ ≥ bₙ * Bₙ`, where `bₙ` is the `n`th partial denominator and `Bₙ₊₁` and `Bₙ` are the `n + 1`th and `n`th denominator of the continued fraction. -/ theorem le_of_succ_nth_denom {b : K} (nth_part_denom_eq : (gcf.of v).partial_denominators.nth n = some b) : b * (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) := begin rw [denom_eq_conts_b, nth_cont_eq_succ_nth_cont_aux], exact (le_of_succ_succ_nth_continuants_aux_b nth_part_denom_eq) end /-- Shows that the sequence of denominators is monotonically increasing, that is `Bₙ ≤ Bₙ₊₁`. -/ theorem of_denom_mono : (gcf.of v).denominators n ≤ (gcf.of v).denominators (n + 1) := begin let g := gcf.of v, cases (decidable.em $ g.partial_denominators.terminated_at n) with terminated not_terminated, { have : g.partial_denominators.nth n = none, by rwa seq.terminated_at at terminated, have : g.terminated_at n, from terminated_at_iff_part_denom_none.elim_right (by rwa seq.terminated_at at terminated), have : (gcf.of v).denominators (n + 1) = (gcf.of v).denominators n, from denominators_stable_of_terminated n.le_succ this, rw this }, { obtain ⟨b, nth_part_denom_eq⟩ : ∃ b, g.partial_denominators.nth n = some b, from option.ne_none_iff_exists'.mp not_terminated, have : 1 ≤ b, from of_one_le_nth_part_denom nth_part_denom_eq, calc (gcf.of v).denominators n ≤ b * (gcf.of v).denominators n : by simpa using mul_le_mul_of_nonneg_right this zero_le_of_denom ... ≤ (gcf.of v).denominators (n + 1) : le_of_succ_nth_denom nth_part_denom_eq } end end generalized_continued_fraction
260ede93d706dcd5b5d127134e30dc4fd58532a0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/defeq_simp_lemmas1.lean
1fda928e18a64dc94fb96d6465bdbfd68d915347
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
537
lean
namespace foo universe l constants (A : Type.{l}) definition q (x : A) := x definition h (x : A) : A := q x definition g (x y : A) := h y definition f (x y z : A) := g (g x y) z definition d (x y z w : A) := f (f x y z) (f y z w) (f x w z) definition h.def [defeq] (x : A) : h x = q x := rfl definition g.def [defeq] (x y : A) : g x y = h y := rfl definition f.def [defeq] (x y z : A) : f x y z = g (g x y) z := rfl definition d.def [defeq] (x y z w : A) : d x y z w = f (f x y z) (f y z w) (f x w z) := rfl print [defeq] foo end foo
957deda9562bf549c8f4adbd4dbce81d9145deb7
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/tools/fake_simplifier.lean
2d01a65c3afc5b1fa3a44681c33a34dc3832d7d9
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
158
lean
import .tactic open tactic namespace fake_simplifier -- until we have the simplifier... opaque definition simp : tactic := apply sorry end fake_simplifier
e0e040647b91c506e642ae0707c438103bb7835b
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/archive/100-theorems-list/73_ascending_descending_sequences.lean
cf9e834ddcd461ac0fb3f0604e42a51e4fdf45fa
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,136
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import tactic.basic import data.fintype.basic /-! # Erdős–Szekeres theorem This file proves Theorem 73 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/), also known as the Erdős–Szekeres theorem: given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. We use the proof outlined at https://en.wikipedia.org/wiki/Erdos-Szekeres_theorem#Pigeonhole_principle. ## Tags sequences, increasing, decreasing, Ramsey, Erdos-Szekeres, Erdős–Szekeres, Erdős-Szekeres -/ variables {α : Type*} [linear_order α] {β : Type*} open function finset open_locale classical /-- **Erdős–Szekeres Theorem**: Given a sequence of more than `r * s` distinct values, there is an increasing sequence of length longer than `r` or a decreasing sequence of length longer than `s`. Proof idea: We label each value in the sequence with two numbers specifying the longest increasing subsequence ending there, and the longest decreasing subsequence ending there. We then show the pair of labels must be unique. Now if there is no increasing sequence longer than `r` and no decreasing sequence longer than `s`, then there are at most `r * s` possible labels, which is a contradiction if there are more than `r * s` elements. -/ theorem erdos_szekeres {r s n : ℕ} {f : fin n → α} (hn : r * s < n) (hf : injective f) : (∃ (t : finset (fin n)), r < t.card ∧ strict_mono_on f ↑t) ∨ (∃ (t : finset (fin n)), s < t.card ∧ strict_anti_on f ↑t) := begin -- Given an index `i`, produce the set of increasing (resp., decreasing) subsequences which ends -- at `i`. let inc_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = some i ∧ strict_mono_on f ↑t), let dec_sequences_ending_in : fin n → finset (finset (fin n)) := λ i, univ.powerset.filter (λ t, finset.max t = some i ∧ strict_anti_on f ↑t), -- The singleton sequence is in both of the above collections. -- (This is useful to show that the maximum length subsequence is at least 1, and that the set -- of subsequences is nonempty.) have inc_i : ∀ i, {i} ∈ inc_sequences_ending_in i := λ i, by simp [strict_mono_on], have dec_i : ∀ i, {i} ∈ dec_sequences_ending_in i := λ i, by simp [strict_anti_on], -- Define the pair of labels: at index `i`, the pair is the maximum length of an increasing -- subsequence ending at `i`, paired with the maximum length of a decreasing subsequence ending -- at `i`. -- We call these labels `(a_i, b_i)`. let ab : fin n → ℕ × ℕ, { intro i, apply (max' ((inc_sequences_ending_in i).image card) (nonempty.image ⟨{i}, inc_i i⟩ _), max' ((dec_sequences_ending_in i).image card) (nonempty.image ⟨{i}, dec_i i⟩ _)) }, -- It now suffices to show that one of the labels is 'big' somewhere. In particular, if the -- first in the pair is more than `r` somewhere, then we have an increasing subsequence in our -- set, and if the second is more than `s` somewhere, then we have a decreasing subsequence. suffices : ∃ i, r < (ab i).1 ∨ s < (ab i).2, { obtain ⟨i, hi⟩ := this, apply or.imp _ _ hi, work_on_goal 0 { have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 1 { have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { intro hi, rw mem_image at this, obtain ⟨t, ht₁, ht₂⟩ := this, refine ⟨t, by rwa ht₂, _⟩, rw mem_filter at ht₁, apply ht₁.2.2 } }, -- Show first that the pair of labels is unique. have : injective ab, { apply injective_of_lt_imp_ne, intros i j k q, injection q with q₁ q₂, -- We have two cases: `f i < f j` or `f j < f i`. -- In the former we'll show `a_i < a_j`, and in the latter we'll show `b_i < b_j`. cases lt_or_gt_of_ne (λ _, ne_of_lt ‹i < j› (hf ‹f i = f j›)), work_on_goal 0 { apply ne_of_lt _ q₁, have : (ab i).1 ∈ _ := max'_mem _ _ }, work_on_goal 1 { apply ne_of_lt _ q₂, have : (ab i).2 ∈ _ := max'_mem _ _ }, all_goals { -- Reduce to showing there is a subsequence of length `a_i + 1` which ends at `j`. rw nat.lt_iff_add_one_le, apply le_max', rw mem_image at this ⊢, -- In particular we take the subsequence `t` of length `a_i` which ends at `i`, by definition -- of `a_i` rcases this with ⟨t, ht₁, ht₂⟩, rw mem_filter at ht₁, -- Ensure `t` ends at `i`. have : i ∈ t.max, simp [ht₁.2.1], -- Now our new subsequence is given by adding `j` at the end of `t`. refine ⟨insert j t, _, _⟩, -- First make sure it's valid, i.e., that this subsequence ends at `j` and is increasing { rw mem_filter, refine ⟨_, _, _⟩, { rw mem_powerset, apply subset_univ }, -- It ends at `j` since `i < j`. { convert max_insert, rw [ht₁.2.1, option.lift_or_get_some_some, max_eq_left, with_top.some_eq_coe], apply le_of_lt ‹i < j› }, -- To show it's increasing (i.e., `f` is monotone increasing on `t.insert j`), we do cases -- on what the possibilities could be - either in `t` or equals `j`. simp only [strict_mono_on, strict_anti_on, coe_insert, set.mem_insert_iff, mem_coe], -- Most of the cases are just bashes. rintros x ⟨rfl | _⟩ y ⟨rfl | _⟩ _, { apply (irrefl _ ‹j < j›).elim }, { exfalso, apply not_le_of_lt (trans ‹i < j› ‹j < y›) (le_max_of_mem ‹y ∈ t› ‹i ∈ t.max›) }, { apply lt_of_le_of_lt _ ‹f i < f j› <|> apply lt_of_lt_of_le ‹f j < f i› _, rcases lt_or_eq_of_le (le_max_of_mem ‹x ∈ t› ‹i ∈ t.max›) with _ | rfl, { apply le_of_lt (ht₁.2.2 ‹x ∈ t› (mem_of_max ‹i ∈ t.max›) ‹x < i›) }, { refl } }, { apply ht₁.2.2 ‹x ∈ t› ‹y ∈ t› ‹x < y› } }, -- Finally show that this new subsequence is one longer than the old one. { rw [card_insert_of_not_mem, ht₂], intro _, apply not_le_of_lt ‹i < j› (le_max_of_mem ‹j ∈ t› ‹i ∈ t.max›) } } }, -- Finished both goals! -- Now that we have uniqueness of each label, it remains to do some counting to finish off. -- Suppose all the labels are small. by_contra q, push_neg at q, -- Then the labels `(a_i, b_i)` all fit in the following set: `{ (x,y) | 1 ≤ x ≤ r, 1 ≤ y ≤ s }` let ran : finset (ℕ × ℕ) := ((range r).image nat.succ).product ((range s).image nat.succ), -- which we prove here. have : image ab univ ⊆ ran, -- First some logical shuffling { rintro ⟨x₁, x₂⟩, simp only [mem_image, exists_prop, mem_range, mem_univ, mem_product, true_and, prod.mk.inj_iff], rintros ⟨i, rfl, rfl⟩, specialize q i, -- Show `1 ≤ a_i` and `1 ≤ b_i`, which is easy from the fact that `{i}` is a increasing and -- decreasing subsequence which we did right near the top. have z : 1 ≤ (ab i).1 ∧ 1 ≤ (ab i).2, { split; { apply le_max', rw mem_image, refine ⟨{i}, by solve_by_elim, card_singleton i⟩ } }, refine ⟨_, _⟩, -- Need to get `a_i ≤ r`, here phrased as: there is some `a < r` with `a+1 = a_i`. { refine ⟨(ab i).1 - 1, _, nat.succ_pred_eq_of_pos z.1⟩, rw nat.sub_lt_right_iff_lt_add z.1, apply nat.lt_succ_of_le q.1 }, { refine ⟨(ab i).2 - 1, _, nat.succ_pred_eq_of_pos z.2⟩, rw nat.sub_lt_right_iff_lt_add z.2, apply nat.lt_succ_of_le q.2 } }, -- To get our contradiction, it suffices to prove `n ≤ r * s` apply not_le_of_lt hn, -- Which follows from considering the cardinalities of the subset above, since `ab` is injective. simpa [nat.succ_injective, card_image_of_injective, ‹injective ab›] using card_le_of_subset this, end
2fc5bfb129199793482ab49a733b7b2197d2516d
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/real/cardinality.lean
316ee34160c3da0abc1cf8c09b01971e9ce6be62
[ "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
4,894
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The cardinality of the reals. -/ import data.real.basic set_theory.ordinal analysis.specific_limits data.rat.denumerable open nat set noncomputable theory namespace cardinal variables {c : ℝ} {f g : ℕ → bool} {n : ℕ} def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n := by simp [cantor_function_aux, h] @[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 := by simp [cantor_function_aux, h] lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := by { cases h' : f n; simp [h'], apply pow_nonneg h } lemma cantor_function_aux_eq (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := by simp [cantor_function_aux, h] lemma cantor_function_aux_succ (f : ℕ → bool) : (λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n := by { ext n, cases h : f (n + 1); simp [h, _root_.pow_succ] } lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := begin apply summable_of_summable_of_sub _ _ (summable_geometric h1 h2), intro n, cases h : f n; simp [h] end def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑ n, cantor_function_aux c f n lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantor_function c f ≤ cantor_function c g := begin apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2), intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1], replace h3 : g n = tt := h3 n h, simp [h, h3] end lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) := begin rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)], rw [cantor_function_aux_succ, tsum_mul_left _ (summable_cantor_function _ h1 h2)], refl end lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool} (hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) : cantor_function c f < cantor_function c g := begin have h3 : c < 1, { apply lt_trans h2, norm_num }, induction n with n ih generalizing f g, { let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n, have hf_max : ∀n, f n → f_max n, { intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl }, let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n, have hg_min : ∀n, g_min n → g n, { intros n hn, cases n, rw [gn], apply rfl, contradiction }, apply lt_of_le_of_lt (cantor_function_le (le_of_lt h1) h3 hf_max), apply lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min), have : c / (1 - c) < 1, { rw [div_lt_one_iff_lt, lt_sub_iff_add_lt], { convert add_lt_add h2 h2, norm_num }, rwa sub_pos }, convert this, { rw [cantor_function_succ _ (le_of_lt h1) h3, div_eq_mul_inv, ←tsum_geometric (le_of_lt h1) h3], apply zero_add }, { apply tsum_eq_single 0, intros n hn, cases n, contradiction, refl, apply_instance }}, rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3], rw [hn 0 $ zero_lt_succ n], apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn end lemma injective_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) : function.injective (cantor_function c) := begin intros f g hfg, classical, by_contra h, revert hfg, have : ∃n, f n ≠ g n, { rw [←not_forall], intro h', apply h, ext, apply h' }, let n := nat.find this, have hn : ∀ (k : ℕ), k < n → f k = g k, { intros k hk, apply of_not_not, exact nat.find_min this hk }, cases fn : f n, { apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _, apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this }, { apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn, apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this } end lemma mk_real : mk ℝ = 2 ^ omega.{0} := begin apply le_antisymm, { dsimp [real], apply le_trans mk_quotient_le, apply le_trans (mk_subtype_le _), rw [←power_def, mk_nat, mk_rat, power_self_eq (le_refl _)] }, { convert mk_le_of_injective (injective_cantor_function _ _), rw [←power_def, mk_bool, mk_nat], exact 1 / 3, norm_num, norm_num } end lemma not_countable_real : ¬ countable (set.univ : set ℝ) := by { rw [countable_iff, not_le, mk_univ, mk_real], apply cantor } end cardinal
4a9d06695ea29211fd748a161cf3d25bbadc273d
6e9cd8d58e550c481a3b45806bd34a3514c6b3e0
/src/group_theory/order_of_element.lean
561ea9d318a3fa5ecd6e54f455139f033dad2897
[ "Apache-2.0" ]
permissive
sflicht/mathlib
220fd16e463928110e7b0a50bbed7b731979407f
1b2048d7195314a7e34e06770948ee00f0ac3545
refs/heads/master
1,665,934,056,043
1,591,373,803,000
1,591,373,803,000
269,815,267
0
0
Apache-2.0
1,591,402,068,000
1,591,402,067,000
null
UTF-8
Lean
false
false
24,258
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 -/ import group_theory.coset import data.nat.totient import data.set.finite open function variables {α : Type*} {s : set α} {a a₁ a₂ b c: α} -- TODO this lemma isn't used anywhere in this file, and should be moved elsewhere. namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset lemma conj_inj [group α] {x : α} : function.injective (λ (g : α), x * g * x⁻¹) := λ a b h, by simpa [mul_left_inj, mul_right_inj] using h lemma mem_normalizer_fintype [group α] {s : set α} [fintype s] {x : α} (h : ∀ n, n ∈ s → x * n * x⁻¹ ∈ s) : x ∈ is_subgroup.normalizer s := by haveI := classical.prop_decidable; haveI := set.fintype_image s (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' s = s := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective s conj_inj), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' s := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_inj hy.2 ▸ hy.1⟩ section order_of variable [group α] open quotient_group set @[simp] lemma card_trivial [fintype (is_subgroup.trivial α)] : fintype.card (is_subgroup.trivial α) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : α), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ variables [fintype α] [dec : decidable_eq α] instance quotient_group.fintype (s : set α) [is_subgroup s] [d : decidable_pred s] : fintype (quotient s) := @quotient.fintype _ _ (left_rel s) (λ _ _, d _) lemma card_eq_card_quotient_mul_card_subgroup (s : set α) [hs : is_subgroup s] [fintype s] [decidable_pred s] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (is_subgroup.group_equiv_quotient_times_subgroup hs) lemma card_subgroup_dvd_card (s : set α) [is_subgroup s] [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card (s : set α) [is_subgroup s] [decidable_pred s] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi:ℤ, a ^ i), from not_injective_infinite_fintype _, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [sub_eq_add_neg, gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end include dec /-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_pos (a : α) : 0 < order_of a := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_gpowers_iff_mem_range_order_of {a a' : α} : a' ∈ gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) (assume i, gpow_eq_mod_order_of.symm) instance decidable_gpowers : decidable_pred (gpowers a) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_gpowers_iff_mem_range_order_of lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (order_of_pos _)) ⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩) lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of a ∣ n ↔ a ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n := nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩ lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) : ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = (finset.univ.filter (λ a : α, a ^ n = 1)).card := calc ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = _ : (finset.card_bind (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext.2 (begin assume a, suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) section local attribute [instance] set_fintype lemma order_eq_card_gpowers : order_of a = fintype.card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ order_of_pos a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma order_of_one : order_of (1 : α) = 1 := by rw [order_eq_card_gpowers, fintype.card_eq_one_iff]; exact ⟨⟨1, 0, rfl⟩, λ ⟨a, i, ha⟩, by simp [ha.symm]⟩ @[simp] lemma order_of_eq_one_iff : order_of a = 1 ↔ a = 1 := ⟨λ h, by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] }, λ h, by simp [h]⟩ lemma order_of_eq_prime {p : ℕ} [hp : fact p.prime] (hg : a^p = 1) (hg1 : a ≠ 1) : order_of a = p := (hp.2 _ (order_of_dvd_of_pow_eq_one hg)).resolve_left (mt order_of_eq_one_iff.1 hg1) section classical open_locale classical open quotient_group /- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := have ft_prod : fintype (quotient (gpowers a) × (gpowers a)), from fintype.of_equiv α (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers a), from @fintype.fintype_prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers a)), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, is_submonoid.one_mem⟩⟩, have ft : fintype (quotient (gpowers a) × (gpowers a)), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (quotient (gpowers a)) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] omit dec @[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] lemma powers_eq_gpowers (a : α) : powers a = gpowers a := set.ext (λ x, ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩) end classical open nat lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n := dvd_antisymm (order_of_dvd_of_pow_eq_one (by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow])) (have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a), have hdvd : order_of a ∣ n * order_of (a ^ n), from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]), coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos) (dvd_of_mul_dvd_mul_right gcd_pos (by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm]))) lemma image_range_order_of (a : α) : finset.image (λ i, a ^ i) (finset.range (order_of a)) = (gpowers a).to_finset := by { ext x, rw [set.mem_to_finset, mem_gpowers_iff_mem_range_order_of] } omit dec open_locale classical lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 := ⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $ by_contradiction (λ ha, by rw pow_eq_mod_order_of at h; exact (not_le_of_gt (nat.mod_lt n (order_of_pos a))) (order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)), let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in by rw [hm, pow_mul, h, _root_.one_pow]⟩ end end order_of section cyclic local attribute [instance] set_fintype /-- A group is called *cyclic* if it is generated by a single element. -/ class is_cyclic (α : Type*) [group α] : Prop := (exists_generator [] : ∃ g : α, ∀ x, x ∈ gpowers g) /-- A cyclic group is always commutative. This is not an `instance` because often we have a better proof of `comm_group`. -/ def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α := { mul_comm := λ x y, show x * y = y * x, from let ⟨g, hg⟩ := is_cyclic.exists_generator α in let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in hm ▸ hn ▸ gpow_mul_comm _ _ _, ..hg } lemma is_cyclic_of_order_of_eq_card [group α] [fintype α] [decidable_eq α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := ⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le (set.subset_univ _) (by rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers])⟩⟩ lemma order_of_eq_card_of_forall_mem_gpowers [group α] [fintype α] [decidable_eq α] {g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α := by rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers]; simp [hx]; congr instance [group α] : is_cyclic (is_subgroup.trivial α) := ⟨⟨(1 : is_subgroup.trivial α), λ x, ⟨0, subtype.eq $ eq.symm (is_subgroup.mem_trivial.1 x.2)⟩⟩⟩ instance is_subgroup.is_cyclic [group α] [is_cyclic α] (H : set α) [is_subgroup H] : is_cyclic H := by haveI := classical.prop_decidable; exact let ⟨g, hg⟩ := is_cyclic.exists_generator α in if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then let ⟨x, hx₁, hx₂⟩ := hx in let ⟨k, hk⟩ := hg x in have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H, from ⟨k.nat_abs, nat.pos_of_ne_zero (λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]), match k, hk with | (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁ | -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat, ← is_subgroup.inv_mem_iff H]; simp * at * end⟩, ⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩, λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex), from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩, have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H, by rw gpow_mul; exact is_subgroup.gpow_mem (nat.find_spec hex).2, have hk₃ : g ^ (k % nat.find hex) ∈ H, from (is_subgroup.mul_mem_cancel_left H hk₂).1 $ by rw [← gpow_add, int.mod_add_div, hk]; exact hx, have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs, by rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)), have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H, by rwa [← gpow_coe_nat, ← hk₄], have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0, from by_contradiction (λ h, nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄]; exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1)) ⟨nat.pos_of_ne_zero h, hk₅⟩), ⟨k / (nat.find hex : ℤ), subtype.coe_ext.2 begin suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x, { simpa [gpow_mul] }, rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk] end⟩⟩⟩ else have H = is_subgroup.trivial α, from set.ext $ λ x, ⟨λ h, by simp at *; tauto, λ h, by rw [is_subgroup.mem_trivial.1 h]; exact is_submonoid.one_mem⟩, by clear _let_match; subst this; apply_instance open finset nat lemma is_cyclic.card_pow_eq_one_le [group α] [fintype α] [decidable_eq α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n := let ⟨g, hg⟩ := is_cyclic.exists_generator α in calc (univ.filter (λ a : α, a ^ n = 1)).card ≤ (gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))).to_finset.card : card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ), have hgmn : g ^ (m * gcd n (fintype.card α)) = 1, by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2, begin rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm], refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _, conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]}, exact order_of_dvd_of_pow_eq_one hgmn end⟩) ... ≤ n : let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)), begin rw [← fintype.card_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers, order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg], rw [hm] {occs := occurrences.pos [2,3]}, rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left, hm, nat.mul_div_cancel _ hm0], exact le_of_dvd hn0 (gcd_dvd_left _ _) end lemma is_cyclic.exists_monoid_generator (α : Type*) [group α] [fintype α] [is_cyclic α] : ∃ x : α, ∀ y : α, y ∈ powers x := by simp only [powers_eq_gpowers]; exact is_cyclic.exists_generator α section variables [group α] [fintype α] [decidable_eq α] lemma is_cyclic.image_range_order_of (ha : ∀ x : α, x ∈ gpowers a) : finset.image (λ i, a ^ i) (range (order_of a)) = univ := begin simp only [image_range_order_of, set.eq_univ_iff_forall.mpr ha], convert set.to_finset_univ end lemma is_cyclic.image_range_card (ha : ∀ x : α, x ∈ gpowers a) : finset.image (λ i, a ^ i) (range (fintype.card α)) = univ := by rw [← order_of_eq_card_of_forall_mem_gpowers ha, is_cyclic.image_range_order_of ha] end section totient variables [group α] [fintype α] [decidable_eq α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n) include hn lemma card_pow_eq_one_eq_order_of_aux (a : α) : (finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a := le_antisymm (hn _ (order_of_pos _)) (calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers ... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (fintype.of_finset _ (λ _, iff.rfl)) : @fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _, let ⟨i, hi⟩ := b.2 in by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat, pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h)) ... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : fintype.card_of_finset _ _) open_locale nat -- use φ for nat.totient private lemma card_order_of_eq_totient_aux₁ : ∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card → (univ.filter (λ a : α, order_of a = d)).card = φ d | 0 := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in absurd (mem_filter.1 ha).2 $ ne_of_gt $ order_of_pos a | (d+1) := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in have ha : order_of a = d.succ, from (mem_filter.1 ha).2, have h : ((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) = ((range d.succ).filter (∣ d.succ)).sum φ, from finset.sum_congr rfl (λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1, have hm : m ∣ d.succ, from (mem_filter.1 hm).2, card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2 ⟨a ^ (d.succ / m), mem_filter.2 ⟨mem_univ _, by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm), nat.div_div_self hm (succ_pos _)]⟩⟩)), have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ)) = (range d.succ.succ).filter (∣ d.succ), from (finset.ext.2 $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h, range_succ]) (by clear _let_match; simp [range_succ]; tauto), by clear _let_match; simp [range_succ] {contextual := tt}; tauto⟩), have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ), by simp [mem_range, zero_le_one, le_succ], (add_left_inj (((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card))).1 (calc _ = (insert d.succ (filter (∣ d.succ) (range d.succ))).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (finset.sum_insert (by simp [mem_range, zero_le_one, le_succ])) ... = ((range d.succ.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : sum_congr hinsert (λ _ _, rfl) ... = (univ.filter (λ a : α, a ^ d.succ = 1)).card : sum_card_order_of_eq_card_pow_eq_one (succ_pos d) ... = ((range d.succ.succ).filter (∣ d.succ)).sum φ : ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm ... = _ : by rw [h, ← sum_insert hinsert₁]; exact finset.sum_congr hinsert.symm (λ _ _, rfl)) lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = φ d := by_contradiction $ λ h, have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 := not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)), let c := fintype.card α in have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩, lt_irrefl c $ calc c = (univ.filter (λ a : α, a ^ c = 1)).card : congr_arg card $ by simp [finset.ext, c] ... = ((range c.succ).filter (∣ c)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : (sum_card_order_of_eq_card_pow_eq_one hc0).symm ... = (((range c.succ).filter (∣ c)).erase d).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, have m = d, by simp at *; cc, by simp [*, finset.ext] at *; exact h0)) ... ≤ (((range c.succ).filter (∣ c)).erase d).sum φ : sum_le_sum (λ m hm, have hmc : m ∣ c, by simp at hm; tauto, (imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim (λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le]) (by { intro h, rw h, apply le_refl })) ... < φ d + (((range c.succ).filter (∣ c)).erase d).sum φ : lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero (λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd)))) ... = (insert d (((range c.succ).filter (∣ c)).erase d)).sum φ : eq.symm (sum_insert (by simp)) ... = ((range c.succ).filter (∣ c)).sum φ : finset.sum_congr (finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl) ... = c : sum_totient _ lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α := have (univ.filter (λ a : α, order_of a = fintype.card α)).nonempty, from (card_pos.1 $ by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)]; exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)), let ⟨x, hx⟩ := this in is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2 end totient lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [fintype α] [decidable_eq α] {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d := card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd end cyclic
9a1ce5cd0e913cb0d9b0c00317c129546171b5fa
4727251e0cd73359b15b664c3170e5d754078599
/src/data/sum/basic.lean
5bcda17b5f4ed88fe3217d4730485545118545cd
[ "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
14,802
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury G. Kudryashov -/ import data.option.basic /-! # Disjoint union of types This file proves basic results about the sum type `α ⊕ β`. `α ⊕ β` is the type made of a copy of `α` and a copy of `β`. It is also called *disjoint union*. ## Main declarations * `sum.get_left`: Retrieves the left content of `x : α ⊕ β` or returns `none` if it's coming from the right. * `sum.get_right`: Retrieves the right content of `x : α ⊕ β` or returns `none` if it's coming from the left. * `sum.is_left`: Returns whether `x : α ⊕ β` comes from the left component or not. * `sum.is_right`: Returns whether `x : α ⊕ β` comes from the right component or not. * `sum.map`: Maps `α ⊕ β` to `γ ⊕ δ` component-wise. * `sum.elim`: Nondependent eliminator/induction principle for `α ⊕ β`. * `sum.swap`: Maps `α ⊕ β` to `β ⊕ α` by swapping components. * `sum.lex`: Lexicographic order on `α ⊕ β` induced by a relation on `α` and a relation on `β`. ## Notes The definition of `sum` takes values in `Type*`. This effectively forbids `Prop`- valued sum types. To this effect, we have `psum`, which takes value in `Sort*` and carries a more complicated universe signature in consequence. The `Prop` version is `or`. -/ universes u v w x variables {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {γ δ : Type*} namespace sum attribute [derive decidable_eq] sum @[simp] lemma «forall» {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ ∀ b, p (inr b) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] lemma «exists» {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ lemma inl_injective : function.injective (inl : α → α ⊕ β) := λ x y, inl.inj lemma inr_injective : function.injective (inr : β → α ⊕ β) := λ x y, inr.inj section get /-- Check if a sum is `inl` and if so, retrieve its contents. -/ @[simp] def get_left : α ⊕ β → option α | (inl a) := some a | (inr _) := none /-- Check if a sum is `inr` and if so, retrieve its contents. -/ @[simp] def get_right : α ⊕ β → option β | (inr b) := some b | (inl _) := none /-- Check if a sum is `inl`. -/ @[simp] def is_left : α ⊕ β → bool | (inl _) := tt | (inr _) := ff /-- Check if a sum is `inr`. -/ @[simp] def is_right : α ⊕ β → bool | (inl _) := ff | (inr _) := tt variables {x y : α ⊕ β} lemma get_left_eq_none_iff : x.get_left = none ↔ x.is_right := by cases x; simp only [get_left, is_right, coe_sort_tt, coe_sort_ff, eq_self_iff_true] lemma get_right_eq_none_iff : x.get_right = none ↔ x.is_left := by cases x; simp only [get_right, is_left, coe_sort_tt, coe_sort_ff, eq_self_iff_true] end get /-- Map `α ⊕ β` to `α' ⊕ β'` sending `α` to `α'` and `β` to `β'`. -/ protected def map (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' | (inl x) := inl (f x) | (inr x) := inr (g x) @[simp] lemma map_inl (f : α → α') (g : β → β') (x : α) : (inl x).map f g = inl (f x) := rfl @[simp] lemma map_inr (f : α → α') (g : β → β') (x : β) : (inr x).map f g = inr (g x) := rfl @[simp] lemma map_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : ∀ x : α ⊕ β, (x.map f g).map f' g' = x.map (f' ∘ f) (g' ∘ g) | (inl a) := rfl | (inr b) := rfl @[simp] lemma map_comp_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : (sum.map f' g') ∘ (sum.map f g) = sum.map (f' ∘ f) (g' ∘ g) := funext $ map_map f' g' f g @[simp] lemma map_id_id (α β) : sum.map (@id α) (@id β) = id := funext $ λ x, sum.rec_on x (λ _, rfl) (λ _, rfl) theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. /-- Define a function on `α ⊕ β` by giving separate definitions on `α` and `β`. -/ protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g @[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) : sum.elim f g (inl x) = f x := rfl @[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) : sum.elim f g (inr x) = g x := rfl @[simp] lemma elim_comp_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inl = f := rfl @[simp] lemma elim_comp_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inr = g := rfl @[simp] lemma elim_inl_inr {α β : Sort*} : @sum.elim α β _ inl inr = id := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) lemma comp_elim {α β γ δ : Sort*} (f : γ → δ) (g : α → γ) (h : β → γ): f ∘ sum.elim g h = sum.elim (f ∘ g) (f ∘ h) := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) @[simp] lemma elim_comp_inl_inr {α β γ : Sort*} (f : α ⊕ β → γ) : sum.elim (f ∘ inl) (f ∘ inr) = f := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) lemma elim_comp_map {α β γ δ ε : Sort*} {f₁ : α → β} {f₂ : β → ε} {g₁ : γ → δ} {g₂ : δ → ε} : sum.elim f₂ g₂ ∘ sum.map f₁ g₁ = sum.elim (f₂ ∘ f₁) (g₂ ∘ g₁) := begin ext (_|_), { rw [function.comp_app, map_inl, elim_inl, elim_inl] }, { rw [function.comp_app, map_inr, elim_inr, elim_inr] }, end open function (update update_eq_iff update_comp_eq_of_injective update_comp_eq_of_forall_ne) @[simp] lemma update_elim_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : α} {x : γ} : update (sum.elim f g) (inl i) x = sum.elim (update f i x) g := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_elim_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : β} {x : γ} : update (sum.elim f g) (inr i) x = sum.elim f (update g i x) := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_inl_comp_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inl = update (f ∘ inl) i x := update_comp_eq_of_injective _ inl_injective _ _ @[simp] lemma update_inl_apply_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : α} {x : γ} : update f (inl i) x (inl j) = update (f ∘ inl) i x j := by rw ← update_inl_comp_inl @[simp] lemma update_inl_comp_inr [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inr = f ∘ inr := update_comp_eq_of_forall_ne _ _ $ λ _, inr_ne_inl @[simp] lemma update_inl_apply_inr [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inl i) x (inr j) = f (inr j) := function.update_noteq inr_ne_inl _ _ @[simp] lemma update_inr_comp_inl [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inl = f ∘ inl := update_comp_eq_of_forall_ne _ _ $ λ _, inl_ne_inr @[simp] lemma update_inr_apply_inl [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inr j) x (inl i) = f (inl i) := function.update_noteq inl_ne_inr _ _ @[simp] lemma update_inr_comp_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inr = update (f ∘ inr) i x := update_comp_eq_of_injective _ inr_injective _ _ @[simp] lemma update_inr_apply_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : β} {x : γ} : update f (inr i) x (inr j) = update (f ∘ inr) i x j := by rw ← update_inr_comp_inr /-- Swap the factors of a sum type -/ @[simp] def swap : α ⊕ β → β ⊕ α | (inl a) := inr a | (inr b) := inl b @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap section lift_rel /-- Lifts pointwise two relations between `α` and `γ` and between `β` and `δ` to a relation between `α ⊕ β` and `γ ⊕ δ`. -/ inductive lift_rel (r : α → γ → Prop) (s : β → δ → Prop) : α ⊕ β → γ ⊕ δ → Prop | inl {a c} : r a c → lift_rel (inl a) (inl c) | inr {b d} : s b d → lift_rel (inr b) (inr d) attribute [protected] lift_rel.inl lift_rel.inr variables {r r₁ r₂ : α → γ → Prop} {s s₁ s₂ : β → δ → Prop} {a : α} {b : β} {c : γ} {d : δ} {x : α ⊕ β} {y : γ ⊕ δ} @[simp] lemma lift_rel_inl_inl : lift_rel r s (inl a) (inl c) ↔ r a c := ⟨λ h, by { cases h, assumption }, lift_rel.inl⟩ @[simp] lemma not_lift_rel_inl_inr : ¬ lift_rel r s (inl a) (inr d) . @[simp] lemma not_lift_rel_inr_inl : ¬ lift_rel r s (inr b) (inl c) . @[simp] lemma lift_rel_inr_inr : lift_rel r s (inr b) (inr d) ↔ s b d := ⟨λ h, by { cases h, assumption }, lift_rel.inr⟩ instance [Π a c, decidable (r a c)] [Π b d, decidable (s b d)] : Π (ab : α ⊕ β) (cd : γ ⊕ δ), decidable (lift_rel r s ab cd) | (inl a) (inl c) := decidable_of_iff' _ lift_rel_inl_inl | (inl a) (inr d) := decidable.is_false not_lift_rel_inl_inr | (inr b) (inl c) := decidable.is_false not_lift_rel_inr_inl | (inr b) (inr d) := decidable_of_iff' _ lift_rel_inr_inr lemma lift_rel.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ a b, s₁ a b → s₂ a b) (h : lift_rel r₁ s₁ x y) : lift_rel r₂ s₂ x y := by { cases h, exacts [lift_rel.inl (hr _ _ ‹_›), lift_rel.inr (hs _ _ ‹_›)] } lemma lift_rel.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) (h : lift_rel r₁ s x y) : lift_rel r₂ s x y := h.mono hr $ λ _ _, id lemma lift_rel.mono_right (hs : ∀ a b, s₁ a b → s₂ a b) (h : lift_rel r s₁ x y) : lift_rel r s₂ x y := h.mono (λ _ _, id) hs protected lemma lift_rel.swap (h : lift_rel r s x y) : lift_rel s r x.swap y.swap := by { cases h, exacts [lift_rel.inr ‹_›, lift_rel.inl ‹_›] } @[simp] lemma lift_rel_swap_iff : lift_rel s r x.swap y.swap ↔ lift_rel r s x y := ⟨λ h, by { rw [←swap_swap x, ←swap_swap y], exact h.swap }, lift_rel.swap⟩ end lift_rel section lex /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex (r : α → α → Prop) (s : β → β → Prop) : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : r a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : s b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) attribute [protected] sum.lex.inl sum.lex.inr attribute [simp] lex.sep variables {r r₁ r₂ : α → α → Prop} {s s₁ s₂ : β → β → Prop} {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α ⊕ β} @[simp] lemma lex_inl_inl : lex r s (inl a₁) (inl a₂) ↔ r a₁ a₂ := ⟨λ h, by { cases h, assumption }, lex.inl⟩ @[simp] lemma lex_inr_inr : lex r s (inr b₁) (inr b₂) ↔ s b₁ b₂ := ⟨λ h, by { cases h, assumption }, lex.inr⟩ @[simp] lemma lex_inr_inl : ¬ lex r s (inr b) (inl a) . instance [decidable_rel r] [decidable_rel s] : decidable_rel (lex r s) | (inl a) (inl c) := decidable_of_iff' _ lex_inl_inl | (inl a) (inr d) := decidable.is_true (lex.sep _ _) | (inr b) (inl c) := decidable.is_false lex_inr_inl | (inr b) (inr d) := decidable_of_iff' _ lex_inr_inr protected lemma lift_rel.lex {a b : α ⊕ β} (h : lift_rel r s a b) : lex r s a b := by { cases h, exacts [lex.inl ‹_›, lex.inr ‹_›] } lemma lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ a b, s₁ a b → s₂ a b) (h : lex r₁ s₁ x y) : lex r₂ s₂ x y := by { cases h, exacts [lex.inl (hr _ _ ‹_›), lex.inr (hs _ _ ‹_›), lex.sep _ _] } lemma lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) (h : lex r₁ s x y) : lex r₂ s x y := h.mono hr $ λ _ _, id lemma lex.mono_right (hs : ∀ a b, s₁ a b → s₂ a b) (h : lex r s₁ x y) : lex r s₂ x y := h.mono (λ _ _, id) hs lemma lex_acc_inl {a} (aca : acc r a) : acc (lex r s) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end lemma lex_acc_inr (aca : ∀ a, acc (lex r s) (inl a)) {b} (acb : acc s b) : acc (lex r s) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end lemma lex_wf (ha : well_founded r) (hb : well_founded s) : well_founded (lex r s) := have aca : ∀ a, acc (lex r s) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end lex end sum open sum namespace function lemma injective.sum_elim {f : α → γ} {g : β → γ} (hf : injective f) (hg : injective g) (hfg : ∀ a b, f a ≠ g b) : injective (sum.elim f g) | (inl x) (inl y) h := congr_arg inl $ hf h | (inl x) (inr y) h := (hfg x y h).elim | (inr x) (inl y) h := (hfg y x h.symm).elim | (inr x) (inr y) h := congr_arg inr $ hg h lemma injective.sum_map {f : α → β} {g : α' → β'} (hf : injective f) (hg : injective g) : injective (sum.map f g) | (inl x) (inl y) h := congr_arg inl $ hf $ inl.inj h | (inr x) (inr y) h := congr_arg inr $ hg $ inr.inj h lemma surjective.sum_map {f : α → β} {g : α' → β'} (hf : surjective f) (hg : surjective g) : surjective (sum.map f g) | (inl y) := let ⟨x, hx⟩ := hf y in ⟨inl x, congr_arg inl hx⟩ | (inr y) := let ⟨x, hx⟩ := hg y in ⟨inr x, congr_arg inr hx⟩ end function /-! ### Ternary sum Abbreviations for the maps from the summands to `α ⊕ β ⊕ γ`. This is useful for pattern-matching. -/ namespace sum3 /-- The map from the first summand into a ternary sum. -/ @[pattern, simp, reducible] def in₀ (a) : α ⊕ β ⊕ γ := inl a /-- The map from the second summand into a ternary sum. -/ @[pattern, simp, reducible] def in₁ (b) : α ⊕ β ⊕ γ := inr $ inl b /-- The map from the third summand into a ternary sum. -/ @[pattern, simp, reducible] def in₂ (c) : α ⊕ β ⊕ γ := inr $ inr c end sum3
e992003b526f45e24d7835e2334331dcb13ee9ee
94e33a31faa76775069b071adea97e86e218a8ee
/src/group_theory/submonoid/operations.lean
6516c992520255cd354c20483b3242ec1ae613ae
[ "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
44,942
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import group_theory.group_action.defs import group_theory.submonoid.basic import group_theory.subsemigroup.operations /-! # Operations on `submonoid`s In this file we define various operations on `submonoid`s and `monoid_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `submonoid.to_add_submonoid`, `submonoid.to_add_submonoid'`, `add_submonoid.to_submonoid`, `add_submonoid.to_submonoid'`: convert between multiplicative and additive submonoids of `M`, `multiplicative M`, and `additive M`. These are stated as `order_iso`s. ### (Commutative) monoid structure on a submonoid * `submonoid.to_monoid`, `submonoid.to_comm_monoid`: a submonoid inherits a (commutative) monoid structure. ### Group actions by submonoids * `submonoid.mul_action`, `submonoid.distrib_mul_action`: a submonoid inherits (distributive) multiplicative actions. ### Operations on submonoids * `submonoid.comap`: preimage of a submonoid under a monoid homomorphism as a submonoid of the domain; * `submonoid.map`: image of a submonoid under a monoid homomorphism as a submonoid of the codomain; * `submonoid.prod`: product of two submonoids `s : submonoid M` and `t : submonoid N` as a submonoid of `M × N`; ### Monoid homomorphisms between submonoid * `submonoid.subtype`: embedding of a submonoid into the ambient monoid. * `submonoid.inclusion`: given two submonoids `S`, `T` such that `S ≤ T`, `S.inclusion T` is the inclusion of `S` into `T` as a monoid homomorphism; * `mul_equiv.submonoid_congr`: converts a proof of `S = T` into a monoid isomorphism between `S` and `T`. * `submonoid.prod_equiv`: monoid isomorphism between `s.prod t` and `s × t`; ### Operations on `monoid_hom`s * `monoid_hom.mrange`: range of a monoid homomorphism as a submonoid of the codomain; * `monoid_hom.mker`: kernel of a monoid homomorphism as a submonoid of the domain; * `monoid_hom.restrict`: restrict a monoid homomorphism to a submonoid; * `monoid_hom.cod_restrict`: restrict the codomain of a monoid homomorphism to a submonoid; * `monoid_hom.mrange_restrict`: restrict a monoid homomorphism to its range; ## Tags submonoid, range, product, map, comap -/ variables {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (S : submonoid M) /-! ### Conversion to/from `additive`/`multiplicative` -/ section /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ @[simps] def submonoid.to_add_submonoid : submonoid M ≃o add_submonoid (additive M) := { to_fun := λ S, { carrier := additive.to_mul ⁻¹' S, zero_mem' := S.one_mem', add_mem' := S.mul_mem' }, inv_fun := λ S, { carrier := additive.of_mul ⁻¹' S, one_mem' := S.zero_mem', mul_mem' := S.add_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive submonoids of an additive monoid `additive M` are isomorphic to submonoids of `M`. -/ abbreviation add_submonoid.to_submonoid' : add_submonoid (additive M) ≃o submonoid M := submonoid.to_add_submonoid.symm lemma submonoid.to_add_submonoid_closure (S : set M) : (submonoid.closure S).to_add_submonoid = add_submonoid.closure (additive.to_mul ⁻¹' S) := le_antisymm (submonoid.to_add_submonoid.le_symm_apply.1 $ submonoid.closure_le.2 add_submonoid.subset_closure) (add_submonoid.closure_le.2 submonoid.subset_closure) lemma add_submonoid.to_submonoid'_closure (S : set (additive M)) : (add_submonoid.closure S).to_submonoid' = submonoid.closure (multiplicative.of_add ⁻¹' S) := le_antisymm (add_submonoid.to_submonoid'.le_symm_apply.1 $ add_submonoid.closure_le.2 submonoid.subset_closure) (submonoid.closure_le.2 add_submonoid.subset_closure) end section variables {A : Type*} [add_zero_class A] /-- Additive submonoids of an additive monoid `A` are isomorphic to multiplicative submonoids of `multiplicative A`. -/ @[simps] def add_submonoid.to_submonoid : add_submonoid A ≃o submonoid (multiplicative A) := { to_fun := λ S, { carrier := multiplicative.to_add ⁻¹' S, one_mem' := S.zero_mem', mul_mem' := S.add_mem' }, inv_fun := λ S, { carrier := multiplicative.of_add ⁻¹' S, zero_mem' := S.one_mem', add_mem' := S.mul_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Submonoids of a monoid `multiplicative A` are isomorphic to additive submonoids of `A`. -/ abbreviation submonoid.to_add_submonoid' : submonoid (multiplicative A) ≃o add_submonoid A := add_submonoid.to_submonoid.symm lemma add_submonoid.to_submonoid_closure (S : set A) : (add_submonoid.closure S).to_submonoid = submonoid.closure (multiplicative.to_add ⁻¹' S) := le_antisymm (add_submonoid.to_submonoid.to_galois_connection.l_le $ add_submonoid.closure_le.2 submonoid.subset_closure) (submonoid.closure_le.2 add_submonoid.subset_closure) lemma submonoid.to_add_submonoid'_closure (S : set (multiplicative A)) : (submonoid.closure S).to_add_submonoid' = add_submonoid.closure (additive.of_mul ⁻¹' S) := le_antisymm (submonoid.to_add_submonoid'.to_galois_connection.l_le $ submonoid.closure_le.2 add_submonoid.subset_closure) (add_submonoid.closure_le.2 submonoid.subset_closure) end namespace submonoid variables {F : Type*} [mc : monoid_hom_class F M N] open set /-! ### `comap` and `map` -/ include mc /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap (f : F) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw map_one; exact S.one_mem, mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw map_mul; exact S.mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : submonoid N) (f : F) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : submonoid N} {f : F} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl omit mc @[to_additive] lemma comap_comap (S : submonoid P) (g : N →* P) (f : M →* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[simp, to_additive] lemma comap_id (S : submonoid P) : S.comap (monoid_hom.id P) = S := ext (by simp) include mc /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map (f : F) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, map_one f⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : F) (S : submonoid M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : F} {S : submonoid M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : F) {S : submonoid M} {x : M} (hx : x ∈ S) : f x ∈ S.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : F) (S : submonoid M) (x : S) : f x ∈ S.map f := mem_map_of_mem f x.prop omit mc @[to_additive] lemma map_map (g : N →* P) (f : M →* N) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ include mc @[to_additive] lemma mem_map_iff_mem {f : F} (hf : function.injective f) {S : submonoid M} {x : M} : f x ∈ S.map f ↔ x ∈ S := hf.mem_set_image @[to_additive] lemma map_le_iff_le_comap {f : F} {S : submonoid M} {T : submonoid N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : F) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_le_of_le_comap {T : submonoid N} {f : F} : S ≤ T.comap f → S.map f ≤ T := (gc_map_comap f).l_le @[to_additive] lemma le_comap_of_map_le {T : submonoid N} {f : F} : S.map f ≤ T → S ≤ T.comap f := (gc_map_comap f).le_u @[to_additive] lemma le_comap_map {f : F} : S ≤ (S.map f).comap f := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_le {S : submonoid N} {f : F} : (S.comap f).map f ≤ S := (gc_map_comap f).l_u_le _ @[to_additive] lemma monotone_map {f : F} : monotone (map f) := (gc_map_comap f).monotone_l @[to_additive] lemma monotone_comap {f : F} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp, to_additive] lemma map_comap_map {f : F} : ((S.map f).comap f).map f = S.map f := (gc_map_comap f).l_u_l_eq_l _ @[simp, to_additive] lemma comap_map_comap {S : submonoid N} {f : F} : ((S.comap f).map f).comap f = S.comap f := (gc_map_comap f).u_l_u_eq_u _ @[to_additive] lemma map_sup (S T : submonoid M) (f : F) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : F) (s : ι → submonoid M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_supr @[to_additive] lemma comap_inf (S T : submonoid N) (f : F) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : F) (s : ι → submonoid N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_infi @[simp, to_additive] lemma map_bot (f : F) : (⊥ : submonoid M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : F) : (⊤ : submonoid N).comap f = ⊤ := (gc_map_comap f).u_top omit mc @[simp, to_additive] lemma map_id (S : submonoid M) : S.map (monoid_hom.id M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) section galois_coinsertion variables {ι : Type*} {f : F} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. "-/] def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) @[to_additive] lemma comap_map_eq_of_injective (S : submonoid M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ @[to_additive] lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective @[to_additive] lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective @[to_additive] lemma comap_inf_map_of_injective (S T : submonoid M) : (S.map f ⊓ T.map f).comap f = S ⊓ T := (gci_map_comap hf).u_inf_l _ _ @[to_additive] lemma comap_infi_map_of_injective (S : ι → submonoid M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ @[to_additive] lemma comap_sup_map_of_injective (S T : submonoid M) : (S.map f ⊔ T.map f).comap f = S ⊔ T := (gci_map_comap hf).u_sup_l _ _ @[to_additive] lemma comap_supr_map_of_injective (S : ι → submonoid M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ @[to_additive] lemma map_le_map_iff_of_injective {S T : submonoid M} : S.map f ≤ T.map f ↔ S ≤ T := (gci_map_comap hf).l_le_l_iff @[to_additive] lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ι : Type*} {f : F} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_insertion` when `f` is surjective. "-/] def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) @[to_additive] lemma map_comap_eq_of_surjective (S : submonoid N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ @[to_additive] lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective @[to_additive] lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective @[to_additive] lemma map_inf_comap_of_surjective (S T : submonoid N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T := (gi_map_comap hf).l_inf_u _ _ @[to_additive] lemma map_infi_comap_of_surjective (S : ι → submonoid N) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ @[to_additive] lemma map_sup_comap_of_surjective (S T : submonoid N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T := (gi_map_comap hf).l_sup_u _ _ @[to_additive] lemma map_supr_comap_of_surjective (S : ι → submonoid N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ @[to_additive] lemma comap_le_comap_iff_of_surjective {S T : submonoid N} : S.comap f ≤ T.comap f ↔ S ≤ T := (gi_map_comap hf).u_le_u_iff @[to_additive] lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion end submonoid namespace submonoid_class variables {A : Type*} [set_like A M] [hA : submonoid_class A M] (S' : A) include hA /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S' := ⟨⟨_, one_mem S'⟩⟩ @[simp, norm_cast, to_additive] lemma coe_one : ((1 : S') : M) = 1 := rfl variables {S'} @[simp, norm_cast, to_additive] lemma coe_eq_one {x : S'} : (↑x : M) = 1 ↔ x = 1 := (subtype.ext_iff.symm : (x : M) = (1 : S') ↔ x = 1) variables (S') @[to_additive] lemma one_def : (1 : S') = ⟨1, one_mem S'⟩ := rfl omit hA /-- An `add_submonoid` of an `add_monoid` inherits a scalar multiplication. -/ instance _root_.add_submonoid_class.has_nsmul {M} [add_monoid M] {A : Type*} [set_like A M] [add_submonoid_class A M] (S : A) : has_smul ℕ S := ⟨λ n a, ⟨n • a.1, nsmul_mem a.2 n⟩⟩ /-- A submonoid of a monoid inherits a power operator. -/ instance has_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : has_pow S ℕ := ⟨λ a n, ⟨a.1 ^ n, pow_mem a.2 n⟩⟩ attribute [to_additive] submonoid_class.has_pow @[simp, norm_cast, to_additive] lemma coe_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} (x : S) (n : ℕ) : (↑(x ^ n) : M) = ↑x ^ n := rfl @[simp, to_additive] lemma mk_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} (x : M) (hx : x ∈ S) (n : ℕ) : (⟨x, hx⟩ : S) ^ n = ⟨x ^ n, pow_mem hx n⟩ := rfl /-- A submonoid of a unital magma inherits a unital magma structure. -/ @[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma structure.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_mul_one_class {M : Type*} [mul_one_class M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : mul_one_class S := subtype.coe_injective.mul_one_class _ rfl (λ _ _, rfl) /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_monoid {M : Type*} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : monoid S := subtype.coe_injective.monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_comm_monoid {M} [comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : comm_monoid S := subtype.coe_injective.comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : ordered_comm_monoid S := subtype.coe_injective.ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : linear_ordered_comm_monoid S := subtype.coe_injective.linear_ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : ordered_cancel_comm_monoid S := subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : linear_ordered_cancel_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) include hA /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S' →* M := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : (submonoid_class.subtype S' : S' → M) = coe := rfl end submonoid_class namespace submonoid /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl @[simp, to_additive] lemma mk_mul_mk (x y : M) (hx : x ∈ S) (hy : y ∈ S) : (⟨x, hx⟩ : S) * ⟨y, hy⟩ = ⟨x * y, S.mul_mem hx hy⟩ := rfl @[to_additive] lemma mul_def (x y : S) : x * y = ⟨x * y, S.mul_mem x.2 y.2⟩ := rfl @[to_additive] lemma one_def : (1 : S) = ⟨1, S.one_mem⟩ := rfl /-- A submonoid of a unital magma inherits a unital magma structure. -/ @[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma structure."] instance to_mul_one_class {M : Type*} [mul_one_class M] (S : submonoid M) : mul_one_class S := subtype.coe_injective.mul_one_class coe rfl (λ _ _, rfl) @[to_additive] protected lemma pow_mem {M : Type*} [monoid M] (S : submonoid M) {x : M} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := pow_mem hx n @[simp, norm_cast, to_additive] theorem coe_pow {M : Type*} [monoid M] {S : submonoid M} (x : S) (n : ℕ) : ↑(x ^ n) = (x ^ n : M) := rfl /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S := subtype.coe_injective.monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := subtype.coe_injective.comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`."] instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] (S : submonoid M) : ordered_comm_monoid S := subtype.coe_injective.ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`."] instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] (S : submonoid M) : linear_ordered_comm_monoid S := subtype.coe_injective.linear_ordered_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`."] instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] (S : submonoid M) : ordered_cancel_comm_monoid S := subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`."] instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M] (S : submonoid M) : linear_ordered_cancel_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S →* M := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl /-- The top submonoid is isomorphic to the monoid. -/ @[to_additive "The top additive submonoid is isomorphic to the additive monoid.", simps] def top_equiv : (⊤ : submonoid M) ≃* M := { to_fun := λ x, x, inv_fun := λ x, ⟨x, mem_top x⟩, left_inv := λ x, x.eta _, right_inv := λ _, rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] lemma top_equiv_to_monoid_hom : (top_equiv : _ ≃* M).to_monoid_hom = (⊤ : submonoid M).subtype := rfl /-- A submonoid is isomorphic to its image under an injective function -/ @[to_additive "An additive submonoid is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (f : M →* N) (hf : function.injective f) : S ≃* S.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f S hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (f : M →* N) (hf : function.injective f) (x : S) : (equiv_map_of_injective S f hf x : N) = f x := rfl @[simp, to_additive] lemma closure_closure_coe_preimage {s : set M} : closure ((coe : closure s → M) ⁻¹' s) = ⊤ := eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin refine closure_induction' _ (λ g hg, _) _ (λ g₁ g₂ hg₁ hg₂, _) hx, { exact subset_closure hg }, { exact submonoid.one_mem _ }, { exact submonoid.mul_mem _ }, end /-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s × t` as a submonoid of `M × N`. -/ @[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s × t` as an `add_submonoid` of `A × B`."] def prod (s : submonoid M) (t : submonoid N) : submonoid (M × N) := { carrier := (s : set M) ×ˢ (t : set N), one_mem' := ⟨s.one_mem, t.one_mem⟩, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M × N)) = (s : set M) ×ˢ (t : set N) := rfl @[to_additive mem_prod] lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ s₂ : submonoid M} {t₁ t₂ : submonoid N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : submonoid M) : s.prod (⊤ : submonoid N) = s.comap (monoid_hom.fst M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : submonoid N) : (⊤ : submonoid M).prod s = s.comap (monoid_hom.snd M N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : submonoid M).prod (⊤ : submonoid N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : submonoid M).prod (⊥ : submonoid N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- The product of submonoids is isomorphic to their product as monoids. -/ @[to_additive prod_equiv "The product of additive submonoids is isomorphic to their product as additive monoids"] def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } open monoid_hom @[to_additive] lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod ⊥ := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨hx, set.mem_singleton 1⟩, λ ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩ @[to_additive] lemma map_inr (s : submonoid N) : s.map (inr M N) = prod ⊥ s := ext $ λ p, ⟨λ ⟨x, hx, hp⟩, hp ▸ ⟨set.mem_singleton 1, hx⟩, λ ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩ @[simp, to_additive prod_bot_sup_bot_prod] lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono (le_refl s) bot_le) (prod_mono bot_le (le_refl t))) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set.mem_singleton 1⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set.mem_singleton 1, hp.2⟩) @[to_additive] lemma mem_map_equiv {f : M ≃* N} {K : submonoid M} {x : N} : x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : submonoid M) : K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : submonoid M) : K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom := (map_equiv_eq_comap_symm f.symm K).symm @[simp, to_additive] lemma map_equiv_top (f : M ≃* N) : (⊤ : submonoid M).map f.to_monoid_hom = ⊤ := set_like.coe_injective $ set.image_univ.trans f.surjective.range_eq @[to_additive le_prod_iff] lemma le_prod_iff {s : submonoid M} {t : submonoid N} {u : submonoid (M × N)} : u ≤ s.prod t ↔ u.map (fst M N) ≤ s ∧ u.map (snd M N) ≤ t := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end @[to_additive prod_le_iff] lemma prod_le_iff {s : submonoid M} {t : submonoid N} {u : submonoid (M × N)} : s.prod t ≤ u ↔ s.map (inl M N) ≤ u ∧ t.map (inr M N) ≤ u := begin split, { intros h, split, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨hx, (submonoid.one_mem _)⟩, }, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨submonoid.one_mem _, hx⟩, }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ ⟨h1, h2⟩, have h1' : inl M N x1 ∈ u, { apply hH, simpa using h1, }, have h2' : inr M N x2 ∈ u, { apply hK, simpa using h2, }, simpa using submonoid.mul_mem _ h1' h2', } end end submonoid namespace monoid_hom variables {F : Type*} [mc : monoid_hom_class F M N] open submonoid /-- For many categories (monoids, modules, rings, ...) the set-theoretic image of a morphism `f` is a subobject of the codomain. When this is the case, it is useful to define the range of a morphism in such a way that the underlying carrier set of the range subobject is definitionally `set.range f`. In particular this means that the types `↥(set.range f)` and `↥f.range` are interchangeable without proof obligations. A convenient candidate definition for range which is mathematically correct is `map ⊤ f`, just as `set.range` could have been defined as `f '' set.univ`. However, this lacks the desired definitional convenience, in that it both does not match `set.range`, and that it introduces a redudant `x ∈ ⊤` term which clutters proofs. In such a case one may resort to the `copy` pattern. A `copy` function converts the definitional problem for the carrier set of a subobject into a one-off propositional proof obligation which one discharges while writing the definition of the definitionally convenient range (the parameter `hs` in the example below). A good example is the case of a morphism of monoids. A convenient definition for `monoid_hom.mrange` would be `(⊤ : submonoid M).map f`. However since this lacks the required definitional convenience, we first define `submonoid.copy` as follows: ```lean protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm ▸ S.one_mem', mul_mem' := hs.symm ▸ S.mul_mem' } ``` and then finally define: ```lean def mrange (f : M →* N) : submonoid N := ((⊤ : submonoid M).map f).copy (set.range f) set.image_univ.symm ``` -/ library_note "range copy pattern" include mc /-- The range of a monoid homomorphism is a submonoid. See Note [range copy pattern]. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def mrange (f : F) : submonoid N := ((⊤ : submonoid M).map f).copy (set.range f) set.image_univ.symm @[simp, to_additive] lemma coe_mrange (f : F) : (mrange f : set N) = set.range f := rfl @[simp, to_additive] lemma mem_mrange {f : F} {y : N} : y ∈ mrange f ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma mrange_eq_map (f : F) : mrange f = (⊤ : submonoid M).map f := copy_eq _ omit mc @[to_additive] lemma map_mrange (g : N →* P) (f : M →* N) : f.mrange.map g = (g.comp f).mrange := by simpa only [mrange_eq_map] using (⊤ : submonoid M).map_map g f include mc @[to_additive] lemma mrange_top_iff_surjective {f : F} : mrange f = (⊤ : submonoid N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma mrange_top_of_surjective (f : F) (hf : function.surjective f) : mrange f = (⊤ : submonoid N) := mrange_top_iff_surjective.2 hf @[to_additive] lemma mclosure_preimage_le (f : F) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma map_mclosure (f : F) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) omit mc /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def restrict {N S : Type*} [mul_one_class N] [set_like S M] [submonoid_class S M] (f : M →* N) (s : S) : s →* N := f.comp (submonoid_class.subtype _) @[simp, to_additive] lemma restrict_apply {N S : Type*} [mul_one_class N] [set_like S M] [submonoid_class S M] (f : M →* N) (s : S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain.", simps apply] def cod_restrict {S} [set_like S N] [submonoid_class S N] (f : M →* N) (s : S) (h : ∀ x, f x ∈ s) : M →* s := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range interpreted as a submonoid. -/ @[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."] def mrange_restrict {N} [mul_one_class N] (f : M →* N) : M →* f.mrange := f.cod_restrict f.mrange $ λ x, ⟨x, rfl⟩ @[simp, to_additive] lemma coe_mrange_restrict {N} [mul_one_class N] (f : M →* N) (x : M) : (f.mrange_restrict x : N) = f x := rfl @[to_additive] lemma mrange_restrict_surjective (f : M →* N) : function.surjective f.mrange_restrict := λ ⟨_, ⟨x, rfl⟩⟩, ⟨x, rfl⟩ include mc /-- The multiplicative kernel of a monoid homomorphism is the submonoid of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_submonoid` of elements such that `f x = 0`"] def mker (f : F) : submonoid M := (⊥ : submonoid N).comap f @[to_additive] lemma mem_mker (f : F) {x : M} : x ∈ mker f ↔ f x = 1 := iff.rfl @[to_additive] lemma coe_mker (f : F) : (mker f : set M) = (f : M → N) ⁻¹' {1} := rfl @[to_additive] instance decidable_mem_mker [decidable_eq N] (f : F) : decidable_pred (∈ mker f) := λ x, decidable_of_iff (f x = 1) (mem_mker f) omit mc @[to_additive] lemma comap_mker (g : N →* P) (f : M →* N) : g.mker.comap f = (g.comp f).mker := rfl include mc @[simp, to_additive] lemma comap_bot' (f : F) : (⊥ : submonoid N).comap f = mker f := rfl omit mc @[to_additive] lemma range_restrict_mker (f : M →* N) : mker (mrange_restrict f) = mker f := begin ext, change (⟨f x, _⟩ : mrange f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end @[simp, to_additive] lemma mker_one : (1 : M →* N).mker = ⊤ := by { ext, simp [mem_mker] } @[to_additive] lemma prod_map_comap_prod' {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] (f : M →* N) (g : M' →* N') (S : submonoid N) (S' : submonoid N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ @[to_additive] lemma mker_prod_map {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] (f : M →* N) (g : M' →* N') : (prod_map f g).mker = f.mker.prod g.mker := by rw [←comap_bot', ←comap_bot', ←comap_bot', ←prod_map_comap_prod', bot_prod_bot] @[simp, to_additive] lemma mker_inl : (inl M N).mker = ⊥ := by { ext x, simp [mem_mker] } @[simp, to_additive] lemma mker_inr : (inr M N).mker = ⊥ := by { ext x, simp [mem_mker] } /-- The `monoid_hom` from the preimage of a submonoid to itself. -/ @[to_additive "the `add_monoid_hom` from the preimage of an additive submonoid to itself.", simps] def submonoid_comap (f : M →* N) (N' : submonoid N) : N'.comap f →* N' := { to_fun := λ x, ⟨f x, x.prop⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The `monoid_hom` from a submonoid to its image. See `mul_equiv.submonoid_map` for a variant for `mul_equiv`s. -/ @[to_additive "the `add_monoid_hom` from an additive submonoid to its image. See `add_equiv.add_submonoid_map` for a variant for `add_equiv`s.", simps] def submonoid_map (f : M →* N) (M' : submonoid M) : M' →* M'.map f := { to_fun := λ x, ⟨f x, ⟨x, x.prop, rfl⟩⟩, map_one' := subtype.eq $ f.map_one, map_mul' := λ x y, subtype.eq $ f.map_mul x y } @[to_additive] lemma submonoid_map_surjective (f : M →* N) (M' : submonoid M) : function.surjective (f.submonoid_map M') := by { rintro ⟨_, x, hx, rfl⟩, exact ⟨⟨x, hx⟩, rfl⟩ } end monoid_hom namespace submonoid open monoid_hom @[to_additive] lemma mrange_inl : (inl M N).mrange = prod ⊤ ⊥ := by simpa only [mrange_eq_map] using map_inl ⊤ @[to_additive] lemma mrange_inr : (inr M N).mrange = prod ⊥ ⊤ := by simpa only [mrange_eq_map] using map_inr ⊤ @[to_additive] lemma mrange_inl' : (inl M N).mrange = comap (snd M N) ⊥ := mrange_inl.trans (top_prod _) @[to_additive] lemma mrange_inr' : (inr M N).mrange = comap (fst M N) ⊥ := mrange_inr.trans (prod_top _) @[simp, to_additive] lemma mrange_fst : (fst M N).mrange = ⊤ := mrange_top_of_surjective (fst M N) $ @prod.fst_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma mrange_snd : (snd M N).mrange = ⊤ := mrange_top_of_surjective (snd M N) $ @prod.snd_surjective _ _ ⟨1⟩ @[to_additive] lemma prod_eq_bot_iff {s : submonoid M} {t : submonoid N} : s.prod t = ⊥ ↔ s = ⊥ ∧ t = ⊥ := by simp only [eq_bot_iff, prod_le_iff, (gc_map_comap _).le_iff_le, comap_bot', mker_inl, mker_inr] @[to_additive] lemma prod_eq_top_iff {s : submonoid M} {t : submonoid N} : s.prod t = ⊤ ↔ s = ⊤ ∧ t = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, ← mrange_eq_map, mrange_fst, mrange_snd] @[simp, to_additive] lemma mrange_inl_sup_mrange_inr : (inl M N).mrange ⊔ (inr M N).mrange = ⊤ := by simp only [mrange_inl, mrange_inr, prod_bot_sup_bot_prod, top_prod_top] /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def inclusion {S T : submonoid M} (h : S ≤ T) : S →* T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : submonoid M) : s.subtype.mrange = s := set_like.coe_injective $ (coe_mrange _).trans $ subtype.range_coe @[to_additive] lemma eq_top_iff' : S = ⊤ ↔ ∀ x : M, x ∈ S := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ @[to_additive] lemma eq_bot_iff_forall : S = ⊥ ↔ ∀ x ∈ S, x = (1 : M) := set_like.ext_iff.trans $ by simp [iff_def, S.one_mem] { contextual := tt } @[to_additive] lemma nontrivial_iff_exists_ne_one (S : submonoid M) : nontrivial S ↔ ∃ x ∈ S, x ≠ (1:M) := calc nontrivial S ↔ ∃ x : S, x ≠ 1 : nontrivial_iff_exists_ne 1 ... ↔ ∃ x (hx : x ∈ S), (⟨x, hx⟩ : S) ≠ ⟨1, S.one_mem⟩ : subtype.exists ... ↔ ∃ x ∈ S, x ≠ (1 : M) : by simp only [ne.def] /-- A submonoid is either the trivial submonoid or nontrivial. -/ @[to_additive "An additive submonoid is either the trivial additive submonoid or nontrivial."] lemma bot_or_nontrivial (S : submonoid M) : S = ⊥ ∨ nontrivial S := by simp only [eq_bot_iff_forall, nontrivial_iff_exists_ne_one, ← not_forall, classical.em] /-- A submonoid is either the trivial submonoid or contains a nonzero element. -/ @[to_additive "An additive submonoid is either the trivial additive submonoid or contains a nonzero element."] lemma bot_or_exists_ne_one (S : submonoid M) : S = ⊥ ∨ ∃ x ∈ S, x ≠ (1:M) := S.bot_or_nontrivial.imp_right S.nontrivial_iff_exists_ne_one.mp end submonoid namespace mul_equiv variables {S} {T : submonoid M} /-- Makes the identity isomorphism from a proof that two submonoids of a multiplicative monoid are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } -- this name is primed so that the version to `f.range` instead of `f.mrange` can be unprimed. /-- A monoid homomorphism `f : M →* N` with a left-inverse `g : N → M` defines a multiplicative equivalence between `M` and `f.mrange`. This is a bidirectional version of `monoid_hom.mrange_restrict`. -/ @[to_additive /-" An additive monoid homomorphism `f : M →+ N` with a left-inverse `g : N → M` defines an additive equivalence between `M` and `f.mrange`. This is a bidirectional version of `add_monoid_hom.mrange_restrict`. "-/, simps {simp_rhs := tt}] def of_left_inverse' (f : M →* N) {g : N → M} (h : function.left_inverse g f) : M ≃* f.mrange := { to_fun := f.mrange_restrict, inv_fun := g ∘ f.mrange.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := monoid_hom.mem_mrange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.mrange_restrict } /-- A `mul_equiv` `φ` between two monoids `M` and `N` induces a `mul_equiv` between a submonoid `S ≤ M` and the submonoid `φ(S) ≤ N`. See `monoid_hom.submonoid_map` for a variant for `monoid_hom`s. -/ @[to_additive "An `add_equiv` `φ` between two additive monoids `M` and `N` induces an `add_equiv` between a submonoid `S ≤ M` and the submonoid `φ(S) ≤ N`. See `add_monoid_hom.add_submonoid_map` for a variant for `add_monoid_hom`s.", simps] def submonoid_map (e : M ≃* N) (S : submonoid M) : S ≃* S.map e.to_monoid_hom := { to_fun := λ x, ⟨e x, _⟩, inv_fun := λ x, ⟨e.symm x, _⟩, -- we restate this for `simps` to avoid `⇑e.symm.to_equiv x` ..e.to_monoid_hom.submonoid_map S, ..e.to_equiv.image S } end mul_equiv section actions /-! ### Actions by `submonoid`s These instances tranfer the action by an element `m : M` of a monoid `M` written as `m • a` onto the action by an element `s : S` of a submonoid `S : submonoid M` such that `s • a = (s : M) • a`. These instances work particularly well in conjunction with `monoid.to_mul_action`, enabling `s • m` as an alias for `↑s * m`. -/ namespace submonoid variables {M' : Type*} {α β : Type*} section mul_one_class variables [mul_one_class M'] @[to_additive] instance [has_smul M' α] (S : submonoid M') : has_smul S α := has_smul.comp _ S.subtype @[to_additive] instance smul_comm_class_left [has_smul M' β] [has_smul α β] [smul_comm_class M' α β] (S : submonoid M') : smul_comm_class S α β := ⟨λ a, (smul_comm (a : M') : _)⟩ @[to_additive] instance smul_comm_class_right [has_smul α β] [has_smul M' β] [smul_comm_class α M' β] (S : submonoid M') : smul_comm_class α S β := ⟨λ a s, (smul_comm a (s : M') : _)⟩ /-- Note that this provides `is_scalar_tower S M' M'` which is needed by `smul_mul_assoc`. -/ instance [has_smul α β] [has_smul M' α] [has_smul M' β] [is_scalar_tower M' α β] (S : submonoid M') : is_scalar_tower S α β := ⟨λ a, (smul_assoc (a : M') : _)⟩ @[to_additive] lemma smul_def [has_smul M' α] {S : submonoid M'} (g : S) (m : α) : g • m = (g : M') • m := rfl instance [has_smul M' α] [has_faithful_smul M' α] (S : submonoid M') : has_faithful_smul S α := ⟨λ x y h, subtype.ext $ eq_of_smul_eq_smul h⟩ end mul_one_class variables [monoid M'] /-- The action by a submonoid is the action by the underlying monoid. -/ @[to_additive /-"The additive action by an add_submonoid is the action by the underlying add_monoid. "-/] instance [mul_action M' α] (S : submonoid M') : mul_action S α := mul_action.comp_hom _ S.subtype /-- The action by a submonoid is the action by the underlying monoid. -/ instance [add_monoid α] [distrib_mul_action M' α] (S : submonoid M') : distrib_mul_action S α := distrib_mul_action.comp_hom _ S.subtype /-- The action by a submonoid is the action by the underlying monoid. -/ instance [monoid α] [mul_distrib_mul_action M' α] (S : submonoid M') : mul_distrib_mul_action S α := mul_distrib_mul_action.comp_hom _ S.subtype example {S : submonoid M'} : is_scalar_tower S M' M' := by apply_instance end submonoid end actions
337a33fbad89a832d88985e511befe311ab37fcb
2b2a05a7af89c79da194505bf88205a6c4e05d68
/src/game/world_03_multiplication.lean
ba48ffba62ec2e128ec0689f0ce3390ef8343f42
[]
no_license
lacrosse/natural_number_game
6401a11a8c965da3903ae6695f84586edf6fac85
400179cde1d3fcc9744901dabff98813ba2b544f
refs/heads/master
1,677,566,006,582
1,612,576,917,000
1,612,576,917,000
335,655,947
2
0
null
null
null
null
UTF-8
Lean
false
false
1,679
lean
import game.world_02_addition namespace mynat lemma zero_mul (m : mynat) : 0 * m = 0 := begin[nat_num_game] induction m, rwa mul_zero, end lemma mul_one (m : mynat) : m * 1 = m := begin[nat_num_game] induction m, rwa zero_mul, rwa [one_eq_succ_zero, mul_succ, mul_zero, zero_add], end lemma one_mul (m : mynat) : 1 * m = m := begin[nat_num_game] induction m, rwa mul_zero, rwa [mul_succ, succ_eq_add_one, m_ih], end lemma mul_add (t a b : mynat) : t * (a + b) = t * a + t * b := begin[nat_num_game] induction a, rwa [mul_zero, zero_add, zero_add], rwa [mul_succ, succ_add, mul_succ, a_ih, add_right_comm], end lemma mul_assoc (a b c : mynat) : (a * b) * c = a * (b * c) := begin[nat_num_game] induction c, refl, rwa [mul_succ, mul_succ, mul_add, c_ih], end lemma succ_mul (a b : mynat) : succ a * b = a * b + b := begin[nat_num_game] induction b, rwa [add_zero, mul_zero, mul_zero], rwa [mul_succ, mul_succ, b_ih, add_succ, add_succ, add_right_comm], end lemma add_mul (a b t : mynat) : (a + b) * t = a * t + b * t := begin[nat_num_game] induction t, rwa [mul_zero, mul_zero, mul_zero, add_zero], rwa [ mul_succ, mul_succ, mul_succ, t_ih, add_assoc(a * t_n), add_assoc(a * t_n), add_comm(a), add_comm(a), add_assoc ], end lemma mul_comm (a b : mynat) : a * b = b * a := begin[nat_num_game] induction b, rwa [mul_zero, zero_mul], rwa [mul_succ, succ_mul, b_ih], end lemma mul_left_comm (a b c : mynat) : a * (b * c) = b * (a * c) := begin[nat_num_game] induction c, rwa [mul_zero, mul_zero, mul_zero], rwa [ mul_succ, mul_succ, mul_add, mul_add, c_ih, mul_comm(b), mul_comm(b) ], end end mynat
8610d1b44bde804b39ec341f0215c968d278ef5a
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/punit_instances.lean
4428aa177d370c6ad6d7846ffe7dd303d8e0362b
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
2,607
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Instances on punit. -/ import algebra.module.basic universes u namespace punit variables (x y : punit.{u+1}) (s : set punit.{u+1}) @[to_additive add_comm_group] instance : comm_group punit := by refine { mul := λ _ _, star, one := star, inv := λ _, star, .. }; intros; exact subsingleton.elim _ _ instance : comm_ring punit := by refine { .. punit.comm_group, .. punit.add_comm_group, .. }; intros; exact subsingleton.elim _ _ instance : complete_boolean_algebra punit := by refine { le := λ _ _, true, le_antisymm := λ _ _ _ _, subsingleton.elim _ _, lt := λ _ _, false, lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial), top := star, bot := star, sup := λ _ _, star, inf := λ _ _, star, Sup := λ _, star, Inf := λ _, star, compl := λ _, star, sdiff := λ _ _, star, .. }; intros; trivial instance : canonically_ordered_add_monoid punit := by refine { lt_of_add_lt_add_left := λ _ _ _, id, le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩, .. punit.comm_ring, .. punit.complete_boolean_algebra, .. }; intros; trivial instance : decidable_linear_ordered_cancel_add_comm_monoid punit := { add_left_cancel := λ _ _ _ _, subsingleton.elim _ _, add_right_cancel := λ _ _ _ _, subsingleton.elim _ _, le_of_add_le_add_left := λ _ _ _ _, trivial, le_total := λ _ _, or.inl trivial, decidable_le := λ _ _, decidable.true, decidable_eq := punit.decidable_eq, decidable_lt := λ _ _, decidable.false, .. punit.canonically_ordered_add_monoid } instance (R : Type u) [semiring R] : semimodule R punit := semimodule.of_core $ by refine { smul := λ _ _, star, .. punit.comm_ring, .. }; intros; exact subsingleton.elim _ _ @[simp] lemma zero_eq : (0 : punit) = star := rfl @[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl @[simp] lemma add_eq : x + y = star := rfl @[simp, to_additive] lemma mul_eq : x * y = star := rfl @[simp] lemma neg_eq : -x = star := rfl @[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl lemma smul_eq : x • y = star := rfl @[simp] lemma top_eq : (⊤ : punit) = star := rfl @[simp] lemma bot_eq : (⊥ : punit) = star := rfl @[simp] lemma sup_eq : x ⊔ y = star := rfl @[simp] lemma inf_eq : x ⊓ y = star := rfl @[simp] lemma Sup_eq : Sup s = star := rfl @[simp] lemma Inf_eq : Inf s = star := rfl @[simp] protected lemma le : x ≤ y := trivial @[simp] lemma not_lt : ¬(x < y) := not_false end punit
ce581d1298358ebc0c5170b4378d7cbea1b2d007
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1291.lean
ac1a24d297670ecd4b9f3fbb21e45ce75005ad16
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
145
lean
import tactic open_locale classical variable (Q : Prop) -- BEGIN example (h : ¬ ¬ Q) : Q := sorry example (h : Q) : ¬ ¬ Q := sorry -- END
c68b5229982eb1f5a630ef770e0473f7b2fc0016
78269ad0b3c342b20786f60690708b6e328132b0
/src/library_dev/topology/uniform_space.lean
9f771c378a7e94569f246542e929f3ed3d33da0d
[]
no_license
dselsam/library_dev
e74f46010fee9c7b66eaa704654cad0fcd2eefca
1b4e34e7fb067ea5211714d6d3ecef5132fc8218
refs/heads/master
1,610,372,841,675
1,497,014,421,000
1,497,014,421,000
86,526,137
0
0
null
1,490,752,133,000
1,490,752,132,000
null
UTF-8
Lean
false
false
52,374
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Theory of uniform spaces. -/ import ..algebra.lattice.filter .topological_space .continuity open set lattice filter set_option eqn_compiler.zeta true attribute [trans] subset.trans universes u v w x y section variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} def id_rel {α : Type u} := {p : α × α | p.1 = p.2} def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] lemma swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ take ⟨a, b⟩, by simp [image_swap_eq_vimage_swap]; exact eq_comm lemma monotone_comp_rel [weak_order β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := take a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ take ⟨a, b⟩, ⟨take ⟨a', (heq : a = a'), ha'⟩, heq.symm ▸ ha', take ha, ⟨a, rfl, ha⟩⟩ /- uniformity -/ class uniform_space (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : prod.swap <$> uniformity ≤ uniformity) (comp : uniformity^.lift' (λs, comp_rel s s) ≤ uniformity) lemma uniform_space_eq {u₁ u₂ : uniform_space α} (h : u₁.uniformity = u₂.uniformity) : u₁ = u₂ := begin cases u₁ with a, cases u₂ with b, assert h' : a = b, assumption, clear h, subst h' end section uniform_space variables [uniform_space α] def uniformity : filter (α × α) := uniform_space.uniformity α lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := uniform_space.refl α lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := uniform_space.symm α lemma comp_le_uniformity : uniformity^.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := uniform_space.comp α lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity^.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_iff $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have vimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ vimage prod.swap s, inter_mem_sets hs this, take a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ map (@prod.swap α α) uniformity := calc uniformity = id <$> uniformity : (functor.id_map _)^.symm ... = (prod.swap.{u u} ∘ prod.swap) <$> uniformity : congr_arg (λf : (α×α)→(α×α), f <$> uniformity) (by apply funext; intro x; cases x; refl) ... = (map prod.swap ∘ map prod.swap) uniformity : congr map_compose rfl ... ≤ prod.swap.{u u} <$> uniformity : map_mono symm_le_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity lemma uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity^.lift (λs, g (vimage prod.swap s)) ≤ f) : uniformity^.lift g ≤ f := le_trans (lift_mono uniformity_le_symm (le_refl _)) (by rw [map_lift_eq2 hg, image_swap_eq_vimage_swap]; exact h) lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s))^.lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity^.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (take x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (take x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ take s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (take s, monotone_comp_rel monotone_const monotone_id) (take s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity instance uniform_space.to_topological_space : topological_space α := { open' := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (uniformity.sets : set (set (α×α))), open_univ := by simp; intros; apply univ_mem_sets, open_inter := take s t hs ht x ⟨xs, xt⟩, uniformity.upwards_sets (inter_mem_sets (hs x xs) (ht x xt)) $ take p ⟨ps, pt⟩ h, ⟨ps h, pt h⟩, open_sUnion := take s hs x ⟨t, ts, xt⟩, uniformity.upwards_sets (hs t ts x xt) $ take p ph h, ⟨t, ts, ph h⟩ } lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff], exact take ⟨t, ht, ts, xt⟩, uniformity.upwards_sets (ht x xt) $ take ⟨x', y⟩ h eq, ts $ h eq end, take hs, mem_nhds_sets_iff.mpr $ ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, take x', assume hx' : {p : α × α | p.fst = x' → p.snd ∈ s} ∈ (@uniformity α _).sets, refl_mem_uniformity hx' rfl, take x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in uniformity.upwards_sets ht $ take ⟨a, b⟩ hp' (eq : a = x'), have hp : (x', b) ∈ t, from eq ▸ hp', show {p : α × α | p.fst = b → p.snd ∈ s} ∈ (@uniformity α _).sets, from uniformity.upwards_sets ht $ take ⟨a, b'⟩ hp' (heq : a = b), have (b, b') ∈ t, from heq ▸ hp', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_uniformity {x : α} : nhds x = uniformity^.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := filter_eq $ set.ext $ take s, begin rw [mem_lift'_iff], tactic.swap, apply monotone_vimage, simp [mem_nhds_uniformity_iff], exact ⟨take h, ⟨_, h, take y h, h rfl⟩, take ⟨t, h₁, h₂⟩, uniformity.upwards_sets h₁ $ take ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left {x : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x)^.sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right {y : α} {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y)^.sets := mem_nhds_left (symm_le_uniformity h) lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_vimage $ monotone_comp monotone_vimage monotone_principal) end (congr_arg _ $ funext $ take s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x)^.lift g = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity)^.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [-uniformity_eq_symm] ... = uniformity^.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_vimage hg ... = _ : by simp [image_swap_eq_vimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity^.lift (λs:set (α×α), uniformity^.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := show (nhds a)^.lift (λs:set α, (nhds b)^.lift (λt:set α, principal (set.prod s t))) = _, begin rw [lift_nhds_right], apply congr_arg, apply funext, intro s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ take x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity^.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_vimage }, { intro t, exact monotone_prod monotone_vimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), open' t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, open' t ∧ p ∈ t, from take ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_iff], exact ⟨d, hd, take ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_vimage monotone_vimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ open' (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), open_Union $ take (p:α×α), open_Union $ take hp, (ht p hp).right.left, take ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ take p, Union_subset $ take hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ take ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [-uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_vimage_swap, function.comp], exact monotone_prod monotone_vimage monotone_vimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_vimage monotone_vimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ take s, forall_congr $ take hs, ⟨take ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, take ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ take s, le_infi $ take hs, by simp; exact uniformity.upwards_sets hs subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ take d, le_infi $ take hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_iff $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ take x, suppose x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, from (@uniformity α _).upwards_sets hs $ this, by simp [this]) (take s hs, (uniformity.lift' interior).upwards_sets (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs /- uniform continuity -/ definition uniform_continuous [uniform_space β] (f : α → β) := filter.map (λx:α×α, (f x.1, f x.2)) uniformity ≤ uniformity definition uniform_embedding [uniform_space β] (f : α → β) := (∀a₁ a₂, f a₁ = f a₂ → a₁ = a₂) ∧ vmap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity lemma uniform_continuous_of_embedding [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := by simp [uniform_continuous, hf.right.symm]; exact take s hs, ⟨s, hs, subset.refl _⟩ lemma continuous_of_uniform [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_towards.mpr $ take a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ take s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_vimage, exact monotone_vimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) /- cauchy filters -/ definition cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity^.lift (λs:set (α×α), uniformity^.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity^.lift' (λs:set (α×α), comp_rel s s) : le_infi $ take s, le_infi $ take hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ take ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (return_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact take h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ take s, le_infi $ take hs, begin rw [-forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact f.upwards_sets hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (take s t h x h', closure_mono h h') monotone_vimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact take s t h, closure_mono h, exact monotone_vimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [-uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨take h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_vmap [uniform_space β] {f : filter β} {m : α → β} (hm : vmap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : vmap m f ≠ ⊥) : cauchy (vmap m f) := ⟨hb, calc filter.prod (vmap m f) (vmap m f) = vmap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_vmap_vmap_eq ... ≤ vmap (λp:α×α, (m p.1, m p.2)) uniformity : vmap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ protected def separation_rel (α : Type u) [uniform_space α] := (⋂₀ (@uniformity α _).sets) lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨take x, take s, refl_mem_uniformity, take x y, take h (s : set (α×α)) hs, have vimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, take x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] definition separated (α : Type u) [uniform_space α] := separation_rel α = id_rel instance separated_t2 [s : separated α] : t2_space α := ⟨take x y, assume h : x ≠ y, have separation_rel α = id_rel, from s, have (x, y) ∉ separation_rel α, by simp [this]; exact h, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := classical.bexists_not_of_not_bforall this in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ take z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ /- totally bounded -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, take t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from f.upwards_sets (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from take ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).upwards_sets (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨suppose totally_bounded s, take f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, take d hd, classical.by_contradiction $ take hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simp [not_exists_iff_forall_not, classical.not_and_iff, not_or_iff_implies] at hs; assumption, let f := ⨅t:{t : set α // finite t}, principal (s - (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (take h, hd_cover finite.empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (take ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $ take t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_right_antimono $ Union_subset_Union $ take t, Union_subset_Union_const or.inr⟩) (take ⟨t, ht⟩, by simp [diff_neq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite.empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α d c).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from take y' hy', by dsimp; simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_insert finite.empty⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.upwards_sets this $ take x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) := ⟨take hs f, cauchy_of_totally_bounded_of_ultrafilter hs, take h, totally_bounded_iff_filter.mpr $ take f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact take f hf hfs, hc (ht _ hf hfs) hfs end /- complete space -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) lemma complete_of_closed [complete_space α] {s : set α} {f : filter α} (h : closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ take f, complete_of_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (m '' univ)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨take (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f^.lift' (p s)) in have mp₀ : monotone p, from take a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from take s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ take s, le_infi $ take hs, le_infi $ take t, le_infi $ take ht, le_principal_iff.mpr $ f.upwards_sets ht $ take x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have vmap m g ≠ ⊥, from vmap_neq_bot $ take t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_iff $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_iff mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (m '' univ) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (m '' univ)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (m '' univ)) _ $ mem_nhds_left ht', have h₂ : m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (m '' univ)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ m '' univ ∈ (nhds x ⊓ principal (m '' univ)).sets, from @inter_mem_sets α (nhds x ⊓ principal (m '' univ)) _ _ h₁ h₂, let ⟨y, xyt', b, _, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, take s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (vimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (vimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).upwards_sets hg (take ⟨a, b⟩ ⟨⟨c₁, c₁t, (hc₁ : (a, c₁) ∈ s₁)⟩, ⟨c₂, c₂t, (hc₂ : (c₂, b) ∈ s₂)⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.vmap m g), from cauchy_vmap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.vmap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.vmap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map (uniform_continuous_of_embedding hm) this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (take s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance : uniform_space (quotient (separation_setoid α)) := { uniform_space . uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := take s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ vimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from take a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := have prod.swap ∘ (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ prod.swap, from funext $ take ⟨a, b⟩, rfl, calc (map prod.swap ∘ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧))) uniformity = (map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) ∘ map prod.swap) uniformity : by simp [map_compose, this] ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono symm_le_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ take s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, assert h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, note h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3 } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma vmap_quotient_le_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := take t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).upwards_sets hs $ take x hx, ⟨x, hx, rfl⟩, take ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨take f, assume hf : cauchy f, have cauchy (vmap (λx, ⟦x⟧) f), from cauchy_vmap vmap_quotient_le_uniformity hf $ vmap_neq_bot_of_surj hf.left $ take b, quotient.exists_rep _, let ⟨x, (hx : vmap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (vmap (λx, ⟦x⟧) f) : le_map_vmap $ take b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_towards.mp (continuous_of_uniform uniform_continuous_quotient_mk) _⟩⟩ end separation_space noncomputable def uniformly_extend [uniform_space γ] [nonempty γ] (emb : β → α) (f : β → γ) (a : α) : γ := classical.epsilon $ λc, map f (vmap emb (nhds a)) ≤ nhds c section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (e '' univ)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := uniformly_extend e f include h_dense h_e private lemma vmap_e_neq_empty {a : α} : vmap e (nhds a) ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ have neq_bot : nhds a ⊓ principal (e '' univ) ≠ ⊥, by simp [closure_eq_nhds] at h_dense; exact h_dense a, take s ⟨t, ht, (hs : vimage e t ⊆ s)⟩, have h₁ : t ∈ (nhds a ⊓ principal (e '' univ)).sets, from @mem_inf_sets_of_left α (nhds a) (principal (e '' univ)) t ht, have h₂ : e '' univ ∈ (nhds a ⊓ principal (e '' univ)).sets, from @mem_inf_sets_of_right α (nhds a) (principal (e '' univ)) _ $ subset.refl _, have t ∩ e '' univ ∈ (nhds a ⊓ principal (e '' univ)).sets, from @inter_mem_sets α (nhds a ⊓ principal (e '' univ)) _ _ h₁ h₂, let ⟨x, ⟨hx₁, y, hy, y_eq⟩⟩ := inhabited_of_mem_sets neq_bot this in ne_empty_of_mem $ hs $ show e y ∈ t, from y_eq.symm ▸ hx₁ include h_f lemma uniformly_extend_spec [nonempty γ] [complete_space γ] {a : α} : map f (vmap e (nhds a)) ≤ nhds (ψ a) := have cauchy (nhds a), from cauchy_nhds, have cauchy (vmap e (nhds a)), from cauchy_vmap (le_of_eq h_e.right) this $ vmap_e_neq_empty h_e h_dense, have cauchy (map f (vmap e (nhds a))), from cauchy_map h_f this, have ∃c, map f (vmap e (nhds a)) ≤ nhds c, from complete_space.complete this, classical.epsilon_spec this lemma uniformly_extend_unique [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] {a : α} {c : γ} (h : map f (vmap e (nhds a)) ≤ nhds c) : ψ a = c := have map f (vmap e (nhds a)) ≤ nhds (ψ a) ⊓ nhds c, from le_inf (@uniformly_extend_spec α β γ _ _ _ _ h_e h_dense f h_f _ cγ a) h, -- why does the elaborator not find cγ? have nhds (uniformly_extend e f a) ⊓ nhds c ≠ ⊥, from neq_bot_of_le_neq_bot (by simp [map_eq_bot_iff]; exact vmap_e_neq_empty h_e h_dense) this, @eq_of_nhds_neq_bot _ _ (@separated_t2 _ _ sγ) _ _ this lemma uniformly_extend_of_emb [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := @uniformly_extend_unique α β γ _ _ _ e h_e h_dense f h_f _ cγ sγ (e b) (f b) $ have vmap e (nhds (e b)) ≤ nhds b, begin simp [nhds_eq_uniformity], rw [vmap_lift'_eq], simp [vimage, function.comp], rw [-h_e.right], rw [vmap_lift'_eq2], exact le_refl _, exact monotone_vimage, exact monotone_vimage end, calc map f (vmap e (nhds (e b))) ≤ map f (nhds b) : map_mono this ... ≤ nhds (f b) : continuous_iff_towards.mp (continuous_of_uniform h_f) b lemma uniform_continuous_uniformly_extend [nonempty γ] [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := take d hd, let ⟨s, hs, (hs_comp : comp_rel s (comp_rel s s) ⊆ d)⟩ := (mem_lift'_iff $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have vimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have vimage (λp:β×β, (f p.1, f p.2)) s ∈ (vmap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rw [h_e.right.symm] at this; assumption, let ⟨t, ht, (ts : ∀p:(β×β), (e p.1, e p.2) ∈ t → (f p.1, f p.2) ∈ s)⟩ := this in show vimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).upwards_sets (interior_mem_uniformity ht) $ take ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from open_iff_nhds.mp open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rw [nhds_prod_eq, le_principal_iff] at this; assumption, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in have nb : ∀{x}, map f (vmap e (nhds x)) ≠ ⊥, from take x hx, by rw [map_eq_bot_iff] at hx; exact vmap_e_neq_empty h_e h_dense hx, have (f '' vimage e m₁) ∩ {y | (ψ x₁, y) ∈ s } ∈ (map f (vmap e (nhds x₁))).sets, from inter_mem_sets (image_mem_map $ vimage_mem_vmap $ hm₁) (uniformly_extend_spec h_e h_dense h_f $ mem_nhds_left hs), let ⟨a, ha₁, ha₂⟩ := inhabited_of_mem_sets nb this in have (f '' vimage e m₂) ∩ {x | (x, ψ x₂) ∈ s } ∈ (map f (vmap e (nhds x₂))).sets, from inter_mem_sets (image_mem_map $ vimage_mem_vmap $ hm₂) (uniformly_extend_spec h_e h_dense h_f $ mem_nhds_right hs), let ⟨b, hb₁, hb₂⟩ := inhabited_of_mem_sets nb this in have set.prod (vimage e m₁) (vimage e m₂) ⊆ vimage (λp:(β×β), (f p.1, f p.2)) s, from calc vimage (λp:(β×β), (e p.1, e p.2)) (set.prod m₁ m₂) ⊆ vimage (λp:(β×β), (e p.1, e p.2)) (interior t) : vimage_mono hm ... ⊆ vimage (λp:(β×β), (e p.1, e p.2)) t : vimage_mono interior_subset ... ⊆ vimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' vimage e m₁) (f '' vimage e m₂) ⊆ s, from calc set.prod (f '' vimage e m₁) (f '' vimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (vimage e m₁) (vimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' vimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff_subset_vimage.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1^.val) (p.2^.val))^.sets } lemma monotone_gen : monotone gen := monotone_set_of $ take p, @monotone_mem_sets (α×α) (filter.prod (p.1^.val) (p.2^.val)) private lemma symm_gen : map prod.swap (uniformity^.lift' gen) ≤ uniformity^.lift' gen := calc map prod.swap (uniformity^.lift' gen) = uniformity^.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2^.val) (p.1^.val))^.sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_vimage_swap] end ... ≤ uniformity^.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ take p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin note h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := take ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff^.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff^.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f^.val g^.val).upwards_sets (prod_mem_prod ht₁ ht₄) (take ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity^.lift' gen)^.lift' (λs, comp_rel s s) ≤ uniformity^.lift' gen := calc (uniformity^.lift' gen)^.lift' (λs, comp_rel s s) = uniformity^.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity^.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ take s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity^.lift' $ λs:set(α×α), comp_rel s s)^.lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity^.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := { uniformity := uniformity^.lift' gen, refl := principal_le_lift' $ take s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a^.property^.right hs, symm := symm_gen, comp := comp_gen } def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨take a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (vimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ take s, set.ext $ take ⟨a₁, a₂⟩, by simp [vimage, gen, pure_cauchy, prod_principal_principal], calc vmap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity^.lift' gen) = uniformity^.lift' (vimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : vmap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (pure_cauchy '' univ) := take f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from take s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, take y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, take ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_vimage).mpr (take s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ pure_cauchy '' univ ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_image_of_mem _ $ mem_univ y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ take f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (vimage (prod.mk f')), from le_lift' $ take s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_iff monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from take x hx, (filter.prod f (pure x)).upwards_sets (prod_mem_prod ht' $ mem_pure hx) h, f.upwards_sets ht' $ subset.trans this (vimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end end Cauchy section constructions variables {α : Type u} {β : Type v} instance : weak_order (uniform_space α) := { weak_order . le := λt s, s^.uniformity ≤ t^.uniformity, le_antisymm := take t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := take t, le_refl _, le_trans := take a b c h₁ h₂, @le_trans _ _ c^.uniformity b^.uniformity a^.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨take s, { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ take u, le_infi $ take hu, u.refl, symm := le_infi $ take u, le_infi $ take hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ take u, le_infi $ take hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ take t', le_infi $ take ht', h t' ht' instance : has_bot (uniform_space α) := ⟨{ uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ uniformity := principal id_rel, refl := le_refl _, symm := by simp; apply subset.refl, comp := begin rw [lift'_principal], { simp, apply subset.refl }, exact monotone_comp_rel monotone_id monotone_id end}⟩ instance : complete_lattice (uniform_space α) := { uniform_space.weak_order with sup := λa b, Sup {a, b}, le_sup_left := take a b, le_Sup $ by simp, le_sup_right := take a b, le_Sup $ by simp, sup_le := take a b c h₁ h₂, Sup_le $ take t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := take a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := take a b, Sup_le $ take x ⟨ha, hb⟩, ha, inf_le_right := take a b, Sup_le $ take x ⟨ha, hb⟩, hb, top := ⊤, le_top := take u, u.refl, bot := ⊥, bot_le := take a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := take s u, le_Sup, Sup_le := take s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := take s a hs, le_Sup hs, Inf_le := take s a ha, Sup_le $ take u hs, hs _ ha } instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ def uniform_space.vmap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.vmap (λp:α×α, (f p.1, f p.2)), refl := le_trans (by simp; exact take ⟨a, b⟩ (h : a = b), h ▸ rfl) (vmap_mono u.refl), symm := le_trans (by simp [map_swap_vmap_swap_eq, vmap_vmap_comp, function.comp]; exact le_refl _) (vmap_mono u.symm), comp := le_trans begin rw [vmap_lift'_eq, vmap_lift'_eq2], exact (lift'_mono' $ take s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (vmap_mono u.comp) } lemma uniform_continuous_vmap {f : α → β} {u : uniform_space β} : @uniform_continuous α β (uniform_space.vmap f u) u f := map_vmap_le lemma to_topological_space_vmap {f : α → β} {u : uniform_space β} : (uniform_space.vmap f u).to_topological_space = topological_space.induced f u.to_topological_space := eq_of_nhds_eq_nhds $ take a, begin simp [nhds_induced_eq_vmap, nhds_eq_uniformity, nhds_eq_uniformity], change vmap f (uniformity.lift' (vimage (λb, (f a, b)))) = (u.uniformity.vmap (λp:α×α, (f p.1, f p.2))).lift' (vimage (λa', (a, a'))), rw [vmap_lift'_eq monotone_vimage, vmap_lift'_eq2 monotone_vimage], exact rfl end instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.vmap subtype.val t instance [t₁ : uniform_space α] [t₂ : uniform_space β] : uniform_space (α × β) := uniform_space.vmap prod.fst t₁ ⊔ uniform_space.vmap prod.snd t₂ /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : u₁.to_topological_space ≤ u₂.to_topological_space := le_of_nhds_le_nhds $ take a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma supr_uniformity {ι : Sort v} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ take i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ take a, le_infi $ take ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma to_topological_space_top : (⊤ : uniform_space α).to_topological_space = ⊤ := top_unique $ take s hs x hx ⟨a₁, a₂⟩ (h₁ : a₁ = a₂) (h₂ : a₁ = x), h₁ ▸ h₂.symm ▸ hx lemma to_topological_space_bot : (⊥ : uniform_space α).to_topological_space = ⊥ := bot_unique $ take s hs, classical.by_cases (suppose s = ∅, this.symm ▸ @open_empty _ ⊥) (suppose s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have univ ⊆ _, from hs x hx, have s = univ, from top_unique $ take y hy, @this (x, y) ⟨⟩ rfl, this.symm ▸ @open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort v} {u : ι → uniform_space α} : (supr u).to_topological_space = (⨆i, (u i).to_topological_space) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ take a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (vimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ take i, @nhds_eq_uniformity α (u i) a), exact h, exact take a b, rfl end end) (suppose ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ take i, (this ⟨i⟩).elim, have (supr u).to_topological_space = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ take i, to_topological_space_mono $ le_supr _ _)) end constructions
52f675857b4fdd7a08cccc7dd922f4b33512c829
aa44b2a5876642f9460205af61a5449b74465655
/src/special_functions.lean
bb89982f23904ff17a9442cc28aa3f3a8d80e500
[]
no_license
robertylewis/mathematica_examples
d129d67de147dc2792dcf0b6b70fac9b2eaf8274
e317381c49db032accef2a92e7650d029952ad76
refs/heads/master
1,632,630,516,240
1,631,905,726,000
1,631,905,726,000
80,952,455
2
0
null
null
null
null
UTF-8
Lean
false
false
3,847
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import mathematica import analysis.calculus.deriv open tactic /-! This demo shows how we can axiomatically accept results from Mathematica. Bessel functions <https://en.wikipedia.org/wiki/Bessel_function> are not defined in mathlib, but we can add a constant with the right type, and import properties from Mathematica as axioms. -/ open real /- `deriv` is the single variable Frechet derivative. In the case of `ℝ`, it specializes to the familiar derivative. -/ #check (deriv : (ℝ → ℝ) → (ℝ → ℝ)) /- We add a constant representing Bessel functions and an axiom with their defining property. -/ constant BesselJ (n : ℝ) (z : ℝ) : ℝ axiom BesselJ_def (n : ℝ) (z : ℝ) : z*z*(deriv (deriv (BesselJ n)) z) + z*(deriv (BesselJ n) z) + (z*z-n*n)*(BesselJ n z) = 0 section open mathematica /- We translate Mathematica's Bessel functions to our new type. -/ @[sym_to_pexpr] meta def BesselJ_trans : sym_trans_pexpr_rule := ⟨"BesselJ", ``(BesselJ)⟩ end /-- `make_bessel_fn_eq` takes an expression, simplifies it in Mathematica, translates it back to Lean, and axiomatizes the equality of the input and output. Note that this has nothing specific to do with Bessel functions besides the translation rules used. -/ meta def make_bessel_fn_eq (e : expr) : tactic (expr × expr) := do pe ← mathematica.run_command_on_using (λ t, t ++ "// LeanForm // Activate // FullSimplify") e "bessel.m", val ← to_expr ``(%%pe : ℝ), tp ← to_expr ``(%%e = %%val), nm ← (++) `mathematica_axiom <$> new_aux_decl_name, l ← local_context, l' ← mfilter (kdepends_on tp) l, gls ← get_goals, m ← mk_meta_var tp, set_goals [m], generalizes l', tp' ← target, set_goals gls, let dcl := declaration.ax nm [] tp', add_decl dcl, prf ← mk_const nm, return (val, prf) /-- `approx e q` axiomatizes a numeric approximation of `e` to precision `q`, where `e` and `q` have type `ℝ`. -/ meta def approx (e q : expr) : tactic (expr × expr) := do pe ← mathematica.run_command_on_2 (λ e q, "Rationalize[" ++ e ++ " // LeanForm // Activate // N, " ++ q ++ "// LeanForm // Activate]") e q, val ← to_expr ```(%%pe : ℝ), (lb, _) ← to_expr ```(%%val - %%q) >>= norm_num.derive, (ub, _) ← to_expr ```(%%val + %%q) >>= norm_num.derive, tgt ← to_expr ```(%%lb < %%e ∧ %%e < %%ub), nm ← new_aux_decl_name, let nm' := `approx_axiom ++ nm, let dcl := declaration.ax nm' [] tgt, add_decl dcl, prf ← mk_const nm', return (val, prf) namespace tactic namespace interactive setup_tactic_parser meta def simplify_target : itactic := do (t, _) ← target >>= match_eq, (_, prf) ← make_bessel_fn_eq t, tactic.apply prf $> () meta def approx (e : parse parser.pexpr) (q : parse parser.pexpr) : itactic := do e' ← i_to_expr e, q' ← i_to_expr q, (_, prf) ← _root_.approx e' q', n ← get_unused_name `approx none, tactic.note n none prf, skip end interactive end tactic variable x : ℝ /- This example proves an equality between Bessel functions by checking in Mathematica that the left hand side simplifies to the right hand side. Below we can see the axiom generated by Mathematica. -/ def f1 : x*BesselJ 2 x + x*BesselJ 0 x = 2*BesselJ 1 x := by simplify_target /- In this example we axiomatically add an approximation to a numeric value to the context. Below we look at all axioms currently in the environment. Because this approximation was not actually used in the proof, it doesn't appear in the list of axioms. -/ theorem apr : true := begin approx (100*BesselJ 2 0.52) (0.00001 : ℝ), trace_state, triv end #print axioms
710e74892e8c93027e531728644f9b35baa58300
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/rec2.lean
ff1f20c5e9d44eb2a8f1cb2b9860c366963b0471
[ "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
129
lean
set_option pp.implicit true set_option pp.notation false definition ideq : Π {A : Type} {a b : A}, a = b → a = b, ideq H := H
215c586e8de614e45117f2dab0ca4e683d1f99c9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/nat_bug.lean
2a7f560631c284cfe95de7349f9a2ab52c1ae149
[ "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
798
lean
open decidable namespace experiment inductive nat : Type | zero : nat | succ : nat → nat definition refl := @eq.refl namespace nat definition pred (n : nat) : nat := nat.rec zero (fun m x, m) n theorem pred_zero : pred zero = zero := refl _ theorem pred_succ (n : nat) : pred (succ n) = n := refl _ theorem zero_or_succ (n : nat) : n = zero ∨ n = succ (pred n) := nat.rec_on n (or.intro_left _ (refl zero)) (assume m IH, or.intro_right _ (show succ m = succ (pred (succ m)), from congr_arg succ (symm (pred_succ m)))) theorem zero_or_succ2 (n : nat) : n = zero ∨ n = succ (pred n) := nat.rec_on n (or.intro_left _ (refl zero)) (assume m IH, or.intro_right _ (show succ m = succ (pred (succ m)), from congr_arg succ (symm (pred_succ m)))) end nat end experiment
64097ce0cea9b957df05a08f623e26c1625d5e3f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/nat/periodic.lean
1adf5012fd993d58cd578f839cf13a9a1299fd00
[ "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
2,165
lean
/- Copyright (c) 2021 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import algebra.periodic import data.nat.count import data.nat.interval /-! # Periodic Functions on ℕ This file identifies a few functions on `ℕ` which are periodic, and also proves a lemma about periodic predicates which helps determine their cardinality when filtering intervals over them. -/ namespace nat open nat function lemma periodic_gcd (a : ℕ) : periodic (gcd a) a := by simp only [forall_const, gcd_add_self_right, eq_self_iff_true, periodic] lemma periodic_coprime (a : ℕ) : periodic (coprime a) a := by simp only [coprime_add_self_right, forall_const, iff_self, eq_iff_iff, periodic] lemma periodic_mod (a : ℕ) : periodic (λ n, n % a) a := by simp only [forall_const, eq_self_iff_true, add_mod_right, periodic] lemma _root_.function.periodic.map_mod_nat {α : Type*} {f : ℕ → α} {a : ℕ} (hf : periodic f a) : ∀ n, f (n % a) = f n := λ n, by conv_rhs { rw [← nat.mod_add_div n a, mul_comm, ← nsmul_eq_mul, hf.nsmul] } section multiset open multiset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ lemma filter_multiset_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [decidable_pred p] (pp : periodic p a) : (filter p (Ico n (n+a))).card = a.count p := begin rw [count_eq_card_filter_range, finset.card, finset.filter_val, finset.range_coe, ←multiset_Ico_map_mod n, ←map_count_true_eq_filter_card, ←map_count_true_eq_filter_card, map_map, function.comp], simp only [pp.map_mod_nat], end end multiset section finset open finset /-- An interval of length `a` filtered over a periodic predicate of period `a` has cardinality equal to the number naturals below `a` for which `p a` is true. -/ lemma filter_Ico_card_eq_of_periodic (n a : ℕ) (p : ℕ → Prop) [decidable_pred p] (pp : periodic p a) : ((Ico n (n + a)).filter p).card = a.count p := filter_multiset_Ico_card_eq_of_periodic n a p pp end finset end nat
0e3f5cf7b32b413b476f1927bd797559fda0c8b4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/geometry/manifold/charted_space.lean
b6087b9922aadd3bc27c8fa9de2630ee31bac343
[ "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
46,839
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph /-! # Charted spaces A smooth manifold is a topological space `M` locally modelled on a euclidean space (or a euclidean half-space for manifolds with boundaries, or an infinite dimensional vector space for more general notions of manifolds), i.e., the manifold is covered by open subsets on which there are local homeomorphisms (the charts) going to a model space `H`, and the changes of charts should be smooth maps. In this file, we introduce a general framework describing these notions, where the model space is an arbitrary topological space. We avoid the word *manifold*, which should be reserved for the situation where the model space is a (subset of a) vector space, and use the terminology *charted space* instead. If the changes of charts satisfy some additional property (for instance if they are smooth), then `M` inherits additional structure (it makes sense to talk about smooth manifolds). There are therefore two different ingredients in a charted space: * the set of charts, which is data * the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop. We separate these two parts in the definition: the charted space structure is just the set of charts, and then the different smoothness requirements (smooth manifold, orientable manifold, contact manifold, and so on) are additional properties of these charts. These properties are formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable under composition and inverse, to which the change of coordinates should belong. ## Main definitions * `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition, inverse and restriction (ex: local diffeos). * `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H` * `charted_space H M` : charted space structure on `M` modelled on `H`, given by an atlas of local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class. * `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a charted space modelled on `H`, require that all coordinate changes belong to `G`. This is a type class. * `atlas H M` : when `M` is a charted space modelled on `H`, the atlas of this charted space structure, i.e., the set of charts. * `G.maximal_atlas M` : when `M` is a charted space modelled on `H` and admitting `G` as a structure groupoid, one can consider all the local homeomorphisms from `M` to `H` such that changing coordinate from any chart to them belongs to `G`. This is a larger atlas, called the maximal atlas (for the groupoid `G`). * `structomorph G M M'` : the type of diffeomorphisms between the charted spaces `M` and `M'` for the groupoid `G`. We avoid the word diffeomorphism, keeping it for the smooth category. As a basic example, we give the instance `instance charted_space_model_space (H : Type*) [topological_space H] : charted_space H H` saying that a topological space is a charted space over itself, with the identity as unique chart. This charted space structure is compatible with any groupoid. Additional useful definitions: * `pregroupoid H` : a subset of local mas of `H` stable under composition and restriction, but not inverse (ex: smooth maps) * `groupoid_of_pregroupoid` : construct a groupoid from a pregroupoid, by requiring that a map and its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps) * `chart_at H x` is a preferred chart at `x : M` when `M` has a charted space structure modelled on `H`. * `G.compatible he he'` states that, for any two charts `e` and `e'` in the atlas, the composition of `e.symm` and `e'` belongs to the groupoid `G` when `M` admits `G` as a structure groupoid. * `G.compatible_of_mem_maximal_atlas he he'` states that, for any two charts `e` and `e'` in the maximal atlas associated to the groupoid `G`, the composition of `e.symm` and `e'` belongs to the `G` if `M` admits `G` as a structure groupoid. * `charted_space_core.to_charted_space`: consider a space without a topology, but endowed with a set of charts (which are local equivs) for which the change of coordinates are local homeos. Then one can construct a topology on the space for which the charts become local homeos, defining a genuine charted space structure. ## Implementation notes The atlas in a charted space is *not* a maximal atlas in general: the notion of maximality depends on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms between `M` and `M'` do *not* induce a bijection between the atlases of `M` and `M'`: the definition is only that, read in charts, the structomorphism locally belongs to the groupoid under consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas). A consequence is that the invariance under structomorphisms of properties defined in terms of the atlas is not obvious in general, and could require some work in theory (amounting to the fact that these properties only depend on the maximal atlas, for instance). In practice, this does not create any real difficulty. We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the model space is a half space. Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and sometimes as spaces with an atlas from which a topology is deduced. We use the former approach: otherwise, there would be an instance from manifolds to topological spaces, which means that any instance search for topological spaces would try to find manifold structures involving a yet unknown model space, leading to problems. However, we also introduce the latter approach, through a structure `charted_space_core` making it possible to construct a topology out of a set of local equivs with compatibility conditions (but we do not register it as an instance). In the definition of a charted space, the model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold modelled over `ℝ^(2n)`. ## Notations In the locale `manifold`, we denote the composition of local homeomorphisms with `≫ₕ`, and the composition of local equivs with `≫`. -/ noncomputable theory open_locale classical topological_space open filter universes u variables {H : Type u} {H' : Type*} {M : Type*} {M' : Type*} {M'' : Type*} /- Notational shortcut for the composition of local homeomorphisms and local equivs, i.e., `local_homeomorph.trans` and `local_equiv.trans`. Note that, as is usual for equivs, the composition is from left to right, hence the direction of the arrow. -/ localized "infixr ` ≫ₕ `:100 := local_homeomorph.trans" in manifold localized "infixr ` ≫ `:100 := local_equiv.trans" in manifold /- `simp` looks for subsingleton instances at every call. This turns out to be very inefficient, especially in `simp`-heavy parts of the library such as the manifold code. Disable two such instances to speed up things. NB: this is just a hack. TODO: fix `simp` properly. -/ localized "attribute [-instance] unique.subsingleton pi.subsingleton" in manifold open set local_homeomorph /-! ### Structure groupoids-/ section groupoid /-! One could add to the definition of a structure groupoid the fact that the restriction of an element of the groupoid to any open set still belongs to the groupoid. (This is in Kobayashi-Nomizu.) I am not sure I want this, for instance on `H × E` where `E` is a vector space, and the groupoid is made of functions respecting the fibers and linear in the fibers (so that a charted space over this groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always defined on sets of the form `s × E`. There is a typeclass `closed_under_restriction` for groupoids which have the restriction property. The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid around each point in its domain of definition, then it belongs to the groupoid. Without this requirement, the composition of structomorphisms does not have to be a structomorphism. Note that this implies that a local homeomorphism with empty source belongs to any structure groupoid, as it trivially satisfies this condition. There is also a technical point, related to the fact that a local homeomorphism is by definition a global map which is a homeomorphism when restricted to its source subset (and its values outside of the source are not relevant). Therefore, we also require that being a member of the groupoid only depends on the values on the source. We use primes in the structure names as we will reformulate them below (without primes) using a `has_mem` instance, writing `e ∈ G` instead of `e ∈ G.members`. -/ /-- A structure groupoid is a set of local homeomorphisms of a topological space stable under composition and inverse. They appear in the definition of the smoothness class of a manifold. -/ structure structure_groupoid (H : Type u) [topological_space H] := (members : set (local_homeomorph H H)) (trans' : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members) (symm' : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members) (id_mem' : local_homeomorph.refl H ∈ members) (locality' : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ members) → e ∈ members) (eq_on_source' : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members) variable [topological_space H] instance : has_mem (local_homeomorph H H) (structure_groupoid H) := ⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩ lemma structure_groupoid.trans (G : structure_groupoid H) {e e' : local_homeomorph H H} (he : e ∈ G) (he' : e' ∈ G) : e ≫ₕ e' ∈ G := G.trans' e e' he he' lemma structure_groupoid.symm (G : structure_groupoid H) {e : local_homeomorph H H} (he : e ∈ G) : e.symm ∈ G := G.symm' e he lemma structure_groupoid.id_mem (G : structure_groupoid H) : local_homeomorph.refl H ∈ G := G.id_mem' lemma structure_groupoid.locality (G : structure_groupoid H) {e : local_homeomorph H H} (h : ∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ G) : e ∈ G := G.locality' e h lemma structure_groupoid.eq_on_source (G : structure_groupoid H) {e e' : local_homeomorph H H} (he : e ∈ G) (h : e' ≈ e) : e' ∈ G := G.eq_on_source' e e' he h /-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/ instance structure_groupoid.partial_order : partial_order (structure_groupoid H) := partial_order.lift structure_groupoid.members (λa b h, by { cases a, cases b, dsimp at h, induction h, refl }) lemma structure_groupoid.le_iff {G₁ G₂ : structure_groupoid H} : G₁ ≤ G₂ ↔ ∀ e, e ∈ G₁ → e ∈ G₂ := iff.rfl /-- The trivial groupoid, containing only the identity (and maps with empty source, as this is necessary from the definition) -/ def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H := { members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅}, trans' := λe e' he he', begin cases he; simp at he he', { simpa only [he, refl_trans]}, { have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _, rw he at this, have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := disjoint_iff.1 this, exact (mem_union _ _ _).2 (or.inr this) }, end, symm' := λe he, begin cases (mem_union _ _ _).1 he with E E, { finish }, { right, simpa only [e.to_local_equiv.image_source_eq_target.symm] with mfld_simps using E}, end, id_mem' := mem_union_left _ rfl, locality' := λe he, begin cases e.source.eq_empty_or_nonempty with h h, { right, exact h }, { left, rcases h with ⟨x, hx⟩, rcases he x hx with ⟨s, open_s, xs, hs⟩, have x's : x ∈ (e.restr s).source, { rw [restr_source, open_s.interior_eq], exact ⟨hx, xs⟩ }, cases hs, { replace hs : local_homeomorph.restr e s = local_homeomorph.refl H, by simpa only using hs, have : (e.restr s).source = univ, by { rw hs, simp }, change (e.to_local_equiv).source ∩ interior s = univ at this, have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ }, have : s = univ, by rwa [open_s.interior_eq, univ_subset_iff] at this, simpa only [this, restr_univ] using hs }, { exfalso, rw mem_set_of_eq at hs, rwa hs at x's } }, end, eq_on_source' := λe e' he he'e, begin cases he, { left, have : e = e', { refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _; rw set.mem_singleton_iff.1 he ; refl }, rwa ← this }, { right, change (e.to_local_equiv).source = ∅ at he, rwa [set.mem_set_of_eq, he'e.source_eq] } end } /-- Every structure groupoid contains the identity groupoid -/ instance : order_bot (structure_groupoid H) := { bot := id_groupoid H, bot_le := begin assume u f hf, change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf, simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf, cases hf, { rw hf, apply u.id_mem }, { apply u.locality, assume x hx, rw [hf, mem_empty_eq] at hx, exact hx.elim } end, ..structure_groupoid.partial_order } instance (H : Type u) [topological_space H] : inhabited (structure_groupoid H) := ⟨id_groupoid H⟩ /-- To construct a groupoid, one may consider classes of local homeos such that both the function and its inverse have some property. If this property is stable under composition, one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the groupoid of smooth functions with smooth inverses as an application. -/ structure pregroupoid (H : Type*) [topological_space H] := (property : (H → H) → (set H) → Prop) (comp : ∀{f g u v}, property f u → property g v → is_open u → is_open v → is_open (u ∩ f ⁻¹' v) → property (g ∘ f) (u ∩ f ⁻¹' v)) (id_mem : property id univ) (locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u) (congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u) /-- Construct a groupoid of local homeos for which the map and its inverse have some property, from a pregroupoid asserting that this property is stable under composition. -/ def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H := { members := {e : local_homeomorph H H | PG.property e e.source ∧ PG.property e.symm e.target}, trans' := λe e' he he', begin split, { apply PG.comp he.1 he'.1 e.open_source e'.open_source, apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source }, { apply PG.comp he'.2 he.2 e'.open_target e.open_target, apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target } end, symm' := λe he, ⟨he.2, he.1⟩, id_mem' := ⟨PG.id_mem, PG.id_mem⟩, locality' := λe he, begin split, { apply PG.locality e.open_source (λx xu, _), rcases he x xu with ⟨s, s_open, xs, hs⟩, refine ⟨s, s_open, xs, _⟩, convert hs.1 using 1, dsimp [local_homeomorph.restr], rw s_open.interior_eq }, { apply PG.locality e.open_target (λx xu, _), rcases he (e.symm x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩, refine ⟨e.target ∩ e.symm ⁻¹' s, _, ⟨xu, xs⟩, _⟩, { exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open }, { rw [← inter_assoc, inter_self], convert hs.2 using 1, dsimp [local_homeomorph.restr], rw s_open.interior_eq } }, end, eq_on_source' := λe e' he ee', begin split, { apply PG.congr e'.open_source ee'.2, simp only [ee'.1, he.1] }, { have A := ee'.symm', apply PG.congr e'.symm.open_source A.2, convert he.2, rw A.1, refl } end } lemma mem_groupoid_of_pregroupoid {PG : pregroupoid H} {e : local_homeomorph H H} : e ∈ PG.groupoid ↔ PG.property e e.source ∧ PG.property e.symm e.target := iff.rfl lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H) (h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid := begin refine structure_groupoid.le_iff.2 (λ e he, _), rw mem_groupoid_of_pregroupoid at he ⊢, exact ⟨h _ _ he.1, h _ _ he.2⟩ end lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H} (he' : e ≈ e') (he : PG.property e e.source) : PG.property e' e'.source := begin rw ← he'.1, exact PG.congr e.open_source he'.eq_on.symm he, end /-- The pregroupoid of all local maps on a topological space `H` -/ @[reducible] def continuous_pregroupoid (H : Type*) [topological_space H] : pregroupoid H := { property := λf s, true, comp := λf g u v hf hg hu hv huv, trivial, id_mem := trivial, locality := λf u u_open h, trivial, congr := λf g u u_open hcongr hf, trivial } instance (H : Type*) [topological_space H] : inhabited (pregroupoid H) := ⟨continuous_pregroupoid H⟩ /-- The groupoid of all local homeomorphisms on a topological space `H` -/ def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H := pregroupoid.groupoid (continuous_pregroupoid H) /-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/ instance : order_top (structure_groupoid H) := { top := continuous_groupoid H, le_top := λ u f hf, by { split; exact dec_trivial }, ..structure_groupoid.partial_order } /-- A groupoid is closed under restriction if it contains all restrictions of its element local homeomorphisms to open subsets of the source. -/ class closed_under_restriction (G : structure_groupoid H) : Prop := (closed_under_restriction : ∀ {e : local_homeomorph H H}, e ∈ G → ∀ (s : set H), is_open s → e.restr s ∈ G) lemma closed_under_restriction' {G : structure_groupoid H} [closed_under_restriction G] {e : local_homeomorph H H} (he : e ∈ G) {s : set H} (hs : is_open s) : e.restr s ∈ G := closed_under_restriction.closed_under_restriction he s hs /-- The trivial restriction-closed groupoid, containing only local homeomorphisms equivalent to the restriction of the identity to the various open subsets. -/ def id_restr_groupoid : structure_groupoid H := { members := {e | ∃ {s : set H} (h : is_open s), e ≈ local_homeomorph.of_set s h}, trans' := begin rintros e e' ⟨s, hs, hse⟩ ⟨s', hs', hse'⟩, refine ⟨s ∩ s', is_open.inter hs hs', _⟩, have := local_homeomorph.eq_on_source.trans' hse hse', rwa local_homeomorph.of_set_trans_of_set at this, end, symm' := begin rintros e ⟨s, hs, hse⟩, refine ⟨s, hs, _⟩, rw [← of_set_symm], exact local_homeomorph.eq_on_source.symm' hse, end, id_mem' := ⟨univ, is_open_univ, by simp only with mfld_simps⟩, locality' := begin intros e h, refine ⟨e.source, e.open_source, by simp only with mfld_simps, _⟩, intros x hx, rcases h x hx with ⟨s, hs, hxs, s', hs', hes'⟩, have hes : x ∈ (e.restr s).source, { rw e.restr_source, refine ⟨hx, _⟩, rw hs.interior_eq, exact hxs }, simpa only with mfld_simps using local_homeomorph.eq_on_source.eq_on hes' hes, end, eq_on_source' := begin rintros e e' ⟨s, hs, hse⟩ hee', exact ⟨s, hs, setoid.trans hee' hse⟩, end } lemma id_restr_groupoid_mem {s : set H} (hs : is_open s) : of_set s hs ∈ @id_restr_groupoid H _ := ⟨s, hs, by refl⟩ /-- The trivial restriction-closed groupoid is indeed `closed_under_restriction`. -/ instance closed_under_restriction_id_restr_groupoid : closed_under_restriction (@id_restr_groupoid H _) := ⟨ begin rintros e ⟨s', hs', he⟩ s hs, use [s' ∩ s, is_open.inter hs' hs], refine setoid.trans (local_homeomorph.eq_on_source.restr he s) _, exact ⟨by simp only [hs.interior_eq] with mfld_simps, by simp only with mfld_simps⟩, end ⟩ /-- A groupoid is closed under restriction if and only if it contains the trivial restriction-closed groupoid. -/ lemma closed_under_restriction_iff_id_le (G : structure_groupoid H) : closed_under_restriction G ↔ id_restr_groupoid ≤ G := begin split, { introsI _i, apply structure_groupoid.le_iff.mpr, rintros e ⟨s, hs, hes⟩, refine G.eq_on_source _ hes, convert closed_under_restriction' G.id_mem hs, change s = _ ∩ _, rw hs.interior_eq, simp only with mfld_simps }, { intros h, split, intros e he s hs, rw ← of_set_trans (e : local_homeomorph H H) hs, refine G.trans _ he, apply structure_groupoid.le_iff.mp h, exact id_restr_groupoid_mem hs }, end /-- The groupoid of all local homeomorphisms on a topological space `H` is closed under restriction. -/ instance : closed_under_restriction (continuous_groupoid H) := (closed_under_restriction_iff_id_le _).mpr (by convert le_top) end groupoid /-! ### Charted spaces -/ /-- A charted space is a topological space endowed with an atlas, i.e., a set of local homeomorphisms taking value in a model space `H`, called charts, such that the domains of the charts cover the whole space. We express the covering property by chosing for each `x` a member `chart_at H x` of the atlas containing `x` in its source: in the smooth case, this is convenient to construct the tangent bundle in an efficient way. The model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over `ℂ^n`) will also be seen sometimes as a real manifold over `ℝ^(2n)`. -/ class charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] := (atlas [] : set (local_homeomorph M H)) (chart_at [] : M → local_homeomorph M H) (mem_chart_source [] : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas [] : ∀x, chart_at x ∈ atlas) export charted_space attribute [simp, mfld_simps] mem_chart_source chart_mem_atlas section charted_space /-- Any space is a charted_space modelled over itself, by just using the identity chart -/ instance charted_space_self (H : Type*) [topological_space H] : charted_space H H := { atlas := {local_homeomorph.refl H}, chart_at := λx, local_homeomorph.refl H, mem_chart_source := λx, mem_univ x, chart_mem_atlas := λx, mem_singleton _ } /-- In the trivial charted_space structure of a space modelled over itself through the identity, the atlas members are just the identity -/ @[simp, mfld_simps] lemma charted_space_self_atlas {H : Type*} [topological_space H] {e : local_homeomorph H H} : e ∈ atlas H H ↔ e = local_homeomorph.refl H := by simp [atlas, charted_space.atlas] /-- In the model space, chart_at is always the identity -/ lemma chart_at_self_eq {H : Type*} [topological_space H] {x : H} : chart_at H x = local_homeomorph.refl H := by simpa using chart_mem_atlas H x section variables (H) [topological_space H] [topological_space M] [charted_space H M] lemma mem_chart_target (x : M) : chart_at H x x ∈ (chart_at H x).target := (chart_at H x).map_source (mem_chart_source _ _) /-- If a topological space admits an atlas with locally compact charts, then the space itself is locally compact. -/ lemma charted_space.locally_compact [locally_compact_space H] : locally_compact_space M := begin have : ∀ (x : M), (𝓝 x).has_basis (λ s, s ∈ 𝓝 (chart_at H x x) ∧ is_compact s ∧ s ⊆ (chart_at H x).target) (λ s, (chart_at H x).symm '' s), { intro x, rw [← (chart_at H x).symm_map_nhds_eq (mem_chart_source H x)], exact ((compact_basis_nhds (chart_at H x x)).has_basis_self_subset (is_open.mem_nhds (chart_at H x).open_target (mem_chart_target H x))).map _ }, refine locally_compact_space_of_has_basis this _, rintro x s ⟨h₁, h₂, h₃⟩, exact h₂.image_of_continuous_on ((chart_at H x).continuous_on_symm.mono h₃) end open topological_space lemma charted_space.second_countable_of_countable_cover [second_countable_topology H] {s : set M} (hs : (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ) (hsc : countable s) : second_countable_topology M := begin haveI : ∀ x : M, second_countable_topology (chart_at H x).source := λ x, (chart_at H x).second_countable_topology_source, haveI := hsc.to_encodable, rw bUnion_eq_Union at hs, exact second_countable_topology_of_countable_cover (λ x : s, (chart_at H (x : M)).open_source) hs end lemma charted_space.second_countable_of_sigma_compact [second_countable_topology H] [sigma_compact_space M] : second_countable_topology M := begin obtain ⟨s, hsc, hsU⟩ : ∃ s, countable s ∧ (⋃ x (hx : x ∈ s), (chart_at H x).source) = univ := countable_cover_nhds_of_sigma_compact (λ x : M, is_open.mem_nhds (chart_at H x).open_source (mem_chart_source H x)), exact charted_space.second_countable_of_countable_cover H hsU hsc end end /-- Same thing as `H × H'`. We introduce it for technical reasons: a charted space `M` with model `H` is a set of local charts from `M` to `H` covering the space. Every space is registered as a charted space over itself, using the only chart `id`, in `manifold_model_space`. You can also define a product of charted space `M` and `M'` (with model space `H × H'`) by taking the products of the charts. Now, on `H × H'`, there are two charted space structures with model space `H × H'` itself, the one coming from `manifold_model_space`, and the one coming from the product of the two `manifold_model_space` on each component. They are equal, but not defeq (because the product of `id` and `id` is not defeq to `id`), which is bad as we know. This expedient of renaming `H × H'` solves this problem. -/ def model_prod (H : Type*) (H' : Type*) := H × H' section local attribute [reducible] model_prod instance model_prod_inhabited {α β : Type*} [inhabited α] [inhabited β] : inhabited (model_prod α β) := ⟨(default α, default β)⟩ instance (H : Type*) [topological_space H] (H' : Type*) [topological_space H'] : topological_space (model_prod H H') := by apply_instance /- Next lemma shows up often when dealing with derivatives, register it as simp. -/ @[simp, mfld_simps] lemma model_prod_range_prod_id {H : Type*} {H' : Type*} {α : Type*} (f : H → α) : range (λ (p : model_prod H H'), (f p.1, p.2)) = set.prod (range f) univ := by rw prod_range_univ_eq end /-- The product of two charted spaces is naturally a charted space, with the canonical construction of the atlas of product maps. -/ instance prod_charted_space (H : Type*) [topological_space H] (M : Type*) [topological_space M] [charted_space H M] (H' : Type*) [topological_space H'] (M' : Type*) [topological_space M'] [charted_space H' M'] : charted_space (model_prod H H') (M × M') := { atlas := {f : (local_homeomorph (M×M') (model_prod H H')) | ∃ g ∈ charted_space.atlas H M, ∃ h ∈ (charted_space.atlas H' M'), f = local_homeomorph.prod g h}, chart_at := λ x: (M × M'), (charted_space.chart_at H x.1).prod (charted_space.chart_at H' x.2), mem_chart_source := begin intro x, simp only with mfld_simps, end, chart_mem_atlas := begin intro x, use (charted_space.chart_at H x.1), split, { apply chart_mem_atlas _, }, { use (charted_space.chart_at H' x.2), simp only [chart_mem_atlas, and_self, true_and] } end } section prod_charted_space variables [topological_space H] [topological_space M] [charted_space H M] [topological_space H'] [topological_space M'] [charted_space H' M'] {x : M×M'} @[simp, mfld_simps] lemma prod_charted_space_chart_at : (chart_at (model_prod H H') x) = (chart_at H x.fst).prod (chart_at H' x.snd) := rfl end prod_charted_space end charted_space /-! ### Constructing a topology from an atlas -/ /-- Sometimes, one may want to construct a charted space structure on a space which does not yet have a topological structure, where the topology would come from the charts. For this, one needs charts that are only local equivs, and continuity properties for their composition. This is formalised in `charted_space_core`. -/ @[nolint has_inhabited_instance] structure charted_space_core (H : Type*) [topological_space H] (M : Type*) := (atlas : set (local_equiv M H)) (chart_at : M → local_equiv M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) (open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source) (continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → continuous_on (e.symm.trans e') (e.symm.trans e').source) namespace charted_space_core variables [topological_space H] (c : charted_space_core H M) {e : local_equiv M H} /-- Topology generated by a set of charts on a Type. -/ protected def to_topological_space : topological_space M := topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas) (s : set H) (s_open : is_open s), {e ⁻¹' s ∩ e.source} lemma open_source' (he : e ∈ c.atlas) : @is_open M c.to_topological_space e.source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨e, he, univ, is_open_univ, _⟩, simp only [set.univ_inter, set.preimage_univ] end lemma open_target (he : e ∈ c.atlas) : is_open e.target := begin have E : e.target ∩ e.symm ⁻¹' e.source = e.target := subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx, local_equiv.target_subset_preimage_source _ hx⟩), simpa [local_equiv.trans_source, E] using c.open_source e e he he end /-- An element of the atlas in a charted space without topology becomes a local homeomorphism for the topology constructed from this atlas. The `local_homeomorph` version is given in this definition. -/ protected def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) : @local_homeomorph M H c.to_topological_space _ := { open_source := by convert c.open_source' he, open_target := by convert c.open_target he, continuous_to_fun := begin letI : topological_space M := c.to_topological_space, rw continuous_on_open_iff (c.open_source' he), assume s s_open, rw inter_comm, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨e, he, ⟨s, s_open, rfl⟩⟩ end, continuous_inv_fun := begin letI : topological_space M := c.to_topological_space, apply continuous_on_open_of_generate_from (c.open_target he), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩, rw ts, let f := e.symm.trans e', have : is_open (f ⁻¹' s ∩ f.source), by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1 (c.continuous_to_fun e e' he e'_atlas) s s_open, have A : e' ∘ e.symm ⁻¹' s ∩ (e.target ∩ e.symm ⁻¹' e'.source) = e.target ∩ (e' ∘ e.symm ⁻¹' s ∩ e.symm ⁻¹' e'.source), by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ }, simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this end, ..e } /-- Given a charted space without topology, endow it with a genuine charted space structure with respect to the topology constructed from the atlas. -/ def to_charted_space : @charted_space H _ M c.to_topological_space := { atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he}, chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x), mem_chart_source := λx, c.mem_chart_source x, chart_mem_atlas := λx, begin simp only [mem_Union, mem_singleton_iff], exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩, end } end charted_space_core /-! ### Charted space with a given structure groupoid -/ section has_groupoid variables [topological_space H] [topological_space M] [charted_space H M] section set_option old_structure_cmd true /-- A charted space has an atlas in a groupoid `G` if the change of coordinates belong to the groupoid -/ class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M] [charted_space H M] (G : structure_groupoid H) : Prop := (compatible [] : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G) end /-- Reformulate in the `structure_groupoid` namespace the compatibility condition of charts in a charted space admitting a structure groupoid, to make it more easily accessible with dot notation. -/ lemma structure_groupoid.compatible {H : Type*} [topological_space H] (G : structure_groupoid H) {M : Type*} [topological_space M] [charted_space H M] [has_groupoid M G] {e e' : local_homeomorph M H} (he : e ∈ atlas H M) (he' : e' ∈ atlas H M) : e.symm ≫ₕ e' ∈ G := has_groupoid.compatible G he he' lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) : has_groupoid M G₂ := ⟨ λ e e' he he', hle ((h.compatible : _) he he') ⟩ lemma has_groupoid_of_pregroupoid (PG : pregroupoid H) (h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → PG.property (e.symm ≫ₕ e') (e.symm ≫ₕ e').source) : has_groupoid M (PG.groupoid) := ⟨assume e e' he he', mem_groupoid_of_pregroupoid.mpr ⟨h he he', h he' he⟩⟩ /-- The trivial charted space structure on the model space is compatible with any groupoid -/ instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) : has_groupoid H G := { compatible := λe e' he he', begin replace he : e ∈ atlas H H := he, replace he' : e' ∈ atlas H H := he', rw charted_space_self_atlas at he he', simp [he, he', structure_groupoid.id_mem] end } /-- Any charted space structure is compatible with the groupoid of all local homeomorphisms -/ instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) := ⟨begin assume e e' he he', rw [continuous_groupoid, mem_groupoid_of_pregroupoid], simp only [and_self] end⟩ section maximal_atlas variables (M) (G : structure_groupoid H) /-- Given a charted space admitting a structure groupoid, the maximal atlas associated to this structure groupoid is the set of all local charts that are compatible with the atlas, i.e., such that changing coordinates with an atlas member gives an element of the groupoid. -/ def structure_groupoid.maximal_atlas : set (local_homeomorph M H) := {e | ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G} variable {M} /-- The elements of the atlas belong to the maximal atlas for any structure groupoid -/ lemma structure_groupoid.mem_maximal_atlas_of_mem_atlas [has_groupoid M G] {e : local_homeomorph M H} (he : e ∈ atlas H M) : e ∈ G.maximal_atlas M := λ e' he', ⟨G.compatible he he', G.compatible he' he⟩ lemma structure_groupoid.chart_mem_maximal_atlas [has_groupoid M G] (x : M) : chart_at H x ∈ G.maximal_atlas M := G.mem_maximal_atlas_of_mem_atlas (chart_mem_atlas H x) variable {G} lemma mem_maximal_atlas_iff {e : local_homeomorph M H} : e ∈ G.maximal_atlas M ↔ ∀ e' ∈ atlas H M, e.symm ≫ₕ e' ∈ G ∧ e'.symm ≫ₕ e ∈ G := iff.rfl /-- Changing coordinates between two elements of the maximal atlas gives rise to an element of the structure groupoid. -/ lemma structure_groupoid.compatible_of_mem_maximal_atlas {e e' : local_homeomorph M H} (he : e ∈ G.maximal_atlas M) (he' : e' ∈ G.maximal_atlas M) : e.symm ≫ₕ e' ∈ G := begin apply G.locality (λ x hx, _), set f := chart_at H (e.symm x) with hf, let s := e.target ∩ (e.symm ⁻¹' f.source), have hs : is_open s, { apply e.symm.continuous_to_fun.preimage_open_of_open; apply open_source }, have xs : x ∈ s, by { dsimp at hx, simp [s, hx] }, refine ⟨s, hs, xs, _⟩, have A : e.symm ≫ₕ f ∈ G := (mem_maximal_atlas_iff.1 he f (chart_mem_atlas _ _)).1, have B : f.symm ≫ₕ e' ∈ G := (mem_maximal_atlas_iff.1 he' f (chart_mem_atlas _ _)).2, have C : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ∈ G := G.trans A B, have D : (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') ≈ (e.symm ≫ₕ e').restr s := calc (e.symm ≫ₕ f) ≫ₕ (f.symm ≫ₕ e') = e.symm ≫ₕ (f ≫ₕ f.symm) ≫ₕ e' : by simp [trans_assoc] ... ≈ e.symm ≫ₕ (of_set f.source f.open_source) ≫ₕ e' : by simp [eq_on_source.trans', trans_self_symm] ... ≈ (e.symm ≫ₕ (of_set f.source f.open_source)) ≫ₕ e' : by simp [trans_assoc] ... ≈ (e.symm.restr s) ≫ₕ e' : by simp [s, trans_of_set'] ... ≈ (e.symm ≫ₕ e').restr s : by simp [restr_trans], exact G.eq_on_source C (setoid.symm D), end variable (G) /-- In the model space, the identity is in any maximal atlas. -/ lemma structure_groupoid.id_mem_maximal_atlas : local_homeomorph.refl H ∈ G.maximal_atlas H := G.mem_maximal_atlas_of_mem_atlas (by simp) end maximal_atlas section singleton variables {α : Type*} [topological_space α] namespace local_homeomorph variable (e : local_homeomorph α H) /-- If a single local homeomorphism `e` from a space `α` into `H` has source covering the whole space `α`, then that local homeomorphism induces an `H`-charted space structure on `α`. (This condition is equivalent to `e` being an open embedding of `α` into `H`; see `open_embedding.singleton_charted_space`.) -/ def singleton_charted_space (h : e.source = set.univ) : charted_space H α := { atlas := {e}, chart_at := λ _, e, mem_chart_source := λ _, by simp only [h] with mfld_simps, chart_mem_atlas := λ _, by tauto } @[simp, mfld_simps] lemma singleton_charted_space_chart_at_eq (h : e.source = set.univ) {x : α} : @chart_at H _ α _ (e.singleton_charted_space h) x = e := rfl lemma singleton_charted_space_chart_at_source (h : e.source = set.univ) {x : α} : (@chart_at H _ α _ (e.singleton_charted_space h) x).source = set.univ := h lemma singleton_charted_space_mem_atlas_eq (h : e.source = set.univ) (e' : local_homeomorph α H) (h' : e' ∈ (e.singleton_charted_space h).atlas) : e' = e := h' /-- Given a local homeomorphism `e` from a space `α` into `H`, if its source covers the whole space `α`, then the induced charted space structure on `α` is `has_groupoid G` for any structure groupoid `G` which is closed under restrictions. -/ lemma singleton_has_groupoid (h : e.source = set.univ) (G : structure_groupoid H) [closed_under_restriction G] : @has_groupoid _ _ _ _ (e.singleton_charted_space h) G := { compatible := begin intros e' e'' he' he'', rw e.singleton_charted_space_mem_atlas_eq h e' he', rw e.singleton_charted_space_mem_atlas_eq h e'' he'', refine G.eq_on_source _ e.trans_symm_self, have hle : id_restr_groupoid ≤ G := (closed_under_restriction_iff_id_le G).mp (by assumption), exact structure_groupoid.le_iff.mp hle _ (id_restr_groupoid_mem _), end } end local_homeomorph namespace open_embedding variable [nonempty α] /-- An open embedding of `α` into `H` induces an `H`-charted space structure on `α`. See `local_homeomorph.singleton_charted_space` -/ def singleton_charted_space {f : α → H} (h : open_embedding f) : charted_space H α := (h.to_local_homeomorph f).singleton_charted_space (by simp) lemma singleton_charted_space_chart_at_eq {f : α → H} (h : open_embedding f) {x : α} : ⇑(@chart_at H _ α _ (h.singleton_charted_space) x) = f := rfl lemma singleton_has_groupoid {f : α → H} (h : open_embedding f) (G : structure_groupoid H) [closed_under_restriction G] : @has_groupoid _ _ _ _ h.singleton_charted_space G := (h.to_local_homeomorph f).singleton_has_groupoid (by simp) G end open_embedding end singleton namespace topological_space.opens open topological_space variables (G : structure_groupoid H) [has_groupoid M G] variables (s : opens M) /-- An open subset of a charted space is naturally a charted space. -/ instance : charted_space H s := { atlas := ⋃ (x : s), {@local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩}, chart_at := λ x, @local_homeomorph.subtype_restr _ _ _ _ (chart_at H x.1) s ⟨x⟩, mem_chart_source := λ x, by { simp only with mfld_simps, exact (mem_chart_source H x.1) }, chart_mem_atlas := λ x, by { simp only [mem_Union, mem_singleton_iff], use x } } /-- If a groupoid `G` is `closed_under_restriction`, then an open subset of a space which is `has_groupoid G` is naturally `has_groupoid G`. -/ instance [closed_under_restriction G] : has_groupoid s G := { compatible := begin rintros e e' ⟨_, ⟨x, hc⟩, he⟩ ⟨_, ⟨x', hc'⟩, he'⟩, haveI : nonempty s := ⟨x⟩, simp only [hc.symm, mem_singleton_iff, subtype.val_eq_coe] at he, simp only [hc'.symm, mem_singleton_iff, subtype.val_eq_coe] at he', rw [he, he'], convert G.eq_on_source _ (subtype_restr_symm_trans_subtype_restr s (chart_at H x) (chart_at H x')), apply closed_under_restriction', { exact G.compatible (chart_mem_atlas H x) (chart_mem_atlas H x') }, { exact preimage_open_of_open_symm (chart_at H x) s.2 }, end } end topological_space.opens /-! ### Structomorphisms -/ /-- A `G`-diffeomorphism between two charted spaces is a homeomorphism which, when read in the charts, belongs to `G`. We avoid the word diffeomorph as it is too related to the smooth category, and use structomorph instead. -/ @[nolint has_inhabited_instance] structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*) [topological_space M] [topological_space M'] [charted_space H M] [charted_space H M'] extends homeomorph M M' := (mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H, c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G) variables [topological_space M'] [topological_space M''] {G : structure_groupoid H} [charted_space H M'] [charted_space H M''] /-- The identity is a diffeomorphism of any charted space, for any groupoid. -/ def structomorph.refl (M : Type*) [topological_space M] [charted_space H M] [has_groupoid M G] : structomorph G M M := { mem_groupoid := λc c' hc hc', begin change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G, rw local_homeomorph.refl_trans, exact has_groupoid.compatible G hc hc' end, ..homeomorph.refl M } /-- The inverse of a structomorphism is a structomorphism -/ def structomorph.symm (e : structomorph G M M') : structomorph G M' M := { mem_groupoid := begin assume c c' hc hc', have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G := G.symm (e.mem_groupoid c' c hc' hc), rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc] at this, end, ..e.to_homeomorph.symm} /-- The composition of structomorphisms is a structomorphism -/ def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') : structomorph G M M'' := { mem_groupoid := begin /- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y. Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/ assume c c' hc hc', refine G.locality (λx hx, _), let f₁ := e.to_homeomorph.to_local_homeomorph, let f₂ := e'.to_homeomorph.to_local_homeomorph, let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph, have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _, -- define the atlas g around y let y := (c.symm ≫ₕ f₁) x, let g := chart_at H y, have hg₁ := chart_mem_atlas H y, have hg₂ := mem_chart_source H y, let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁) ⁻¹' g.source, have open_s : is_open s, by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source, have : x ∈ s, { split, { simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source], rw trans_source at hx, exact hx.1 }, { exact hg₂ } }, refine ⟨s, open_s, this, _⟩, let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'), have A : F₁ ∈ G := G.trans (e.mem_groupoid c g hc hg₁) (e'.mem_groupoid g c' hg₁ hc'), let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s, have : F₁ ≈ F₂ := calc F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc] ... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' : by simp [eq_on_source.trans', trans_self_symm g] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') : by simp [trans_assoc] ... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set'] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans] ... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source.restr, trans_assoc] ... ≈ F₂ : by simp [F₂, feq], have : F₂ ∈ G := G.eq_on_source A (setoid.symm this), exact this end, ..homeomorph.trans e.to_homeomorph e'.to_homeomorph } end has_groupoid
b31169b7e21e4fa1eef60b3eb41dbec828af3a3f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/imo/imo1977_q6.lean
d25483e0e534066f6023257b358574f8f3d5f906
[ "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
1,387
lean
/- Copyright (c) 2021 Tian Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tian Chen -/ import data.pnat.basic /-! # IMO 1977 Q6 Suppose `f : ℕ+ → ℕ+` satisfies `f(f(n)) < f(n + 1)` for all `n`. Prove that `f(n) = n` for all `n`. We first prove the problem statement for `f : ℕ → ℕ` then we use it to prove the statement for positive naturals. -/ theorem imo1977_q6_nat (f : ℕ → ℕ) (h : ∀ n, f (f n) < f (n + 1)) : ∀ n, f n = n := begin have h' : ∀ (k n : ℕ), k ≤ n → k ≤ f n, { intro k, induction k with k h_ind, { intros, exact nat.zero_le _ }, { intros n hk, apply nat.succ_le_of_lt, calc k ≤ f (f (n - 1)) : h_ind _ (h_ind (n - 1) (nat.le_sub_right_of_add_le hk)) ... < f n : nat.sub_add_cancel (le_trans (nat.succ_le_succ (nat.zero_le _)) hk) ▸ h _ } }, have hf : ∀ n, n ≤ f n := λ n, h' n n rfl.le, have hf_mono : strict_mono f := strict_mono.nat (λ _, lt_of_le_of_lt (hf _) (h _)), intro, exact nat.eq_of_le_of_lt_succ (hf _) (hf_mono.lt_iff_lt.mp (h _)) end theorem imo1977_q6 (f : ℕ+ → ℕ+) (h : ∀ n, f (f n) < f (n + 1)) : ∀ n, f n = n := begin intro n, simpa using imo1977_q6_nat (λ m, if 0 < m then f m.to_pnat' else 0) _ n, { intro x, cases x, { simp }, { simpa using h _ } } end
36e7be4ff62974b1674be765720d4b8eb7dc3ef9
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/continued_fractions/computation/default.lean
4bb62a79f1165becdfc7e8e1fa2e56e3e7f81d63
[ "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
339
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.basic import algebra.continued_fractions.computation.translations /-! # Default Exports for the Computation of Continued Fractions -/
2853b8efcbf0ba573e4d5402c058ecfecea577f2
8b9cc39aef95580045a98cd3aac5961a7611e7b8
/src/polytope.lean
96c1ea5ebe15c13c70b44686f8a53bcf3d4dc1cd
[]
no_license
vihdzp/polytope
de2202d393ca744cd879f3a316784dc67607af8f
c2c6ed3ace5fa6af0fac0c923bdf44a2d8c76a49
refs/heads/master
1,688,255,728,556
1,627,359,324,000
1,627,359,324,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,202
lean
import tactic set_theory.ordinal order.bounded_lattice order.zorn data.set.intervals.ord_connected order.rel_iso data.finset.preimage open_locale cardinal set_option old_structure_cmd true /-- A partial order with a least and greatest element. -/ class bounded_partial_order (α : Type*) extends order_top α, order_bot α namespace bounded_partial_order section parameters {α : Type*} [bl : bounded_lattice α] -- A bounded lattice is a bounded partial order. instance of_top_bot : bounded_partial_order α := { ..bl } end end bounded_partial_order /-- A face `c` covers `a` whenever `a < c` and no face `b` exists such that `a < b < c`. -/ def covers {α : Type*} [preorder α] (a c : α) : Prop := a < c ∧ ¬ ∃ b, a < b ∧ b < c /-- A graded poset has a function from elements to naturals that's compatible with the ordering, and consistent with the covering relation. -/ class graded (α : Type*) extends order_bot α := (grade : α → ℕ) (grade_bot_eq_zero : grade ⊥ = 0) (lt_grade_of_lt : ∀ {a b : α}, a < b → grade a < grade b) (eq_p1_of_cover : ∀ {a b : α}, covers a b → grade a + 1 = grade b) namespace graded section parameters {α : Type*} [graded α] /-- If `a ≤ b`, then `grade a ≤ grade b`. -/ theorem le_grade_of_le : ∀ {a b : α}, a ≤ b → graded.grade a ≤ graded.grade b := begin intros a b a_le_b, cases lt_or_eq_of_le a_le_b with a_lt_b a_eq_b, { exact le_of_lt (graded.lt_grade_of_lt a_lt_b), }, exact (congr_arg grade (eq.symm a_eq_b)).ge, end /-- If `grade a = 0`, then `a = ⊥`. -/ theorem eq_bot_of_grade_eq_zero {a : α} : grade a = 0 → a = ⊥ := begin contrapose, intro a_ne_bot, have h : grade a > grade (⊥ : α) := lt_grade_of_lt (lt_of_le_of_ne (bot_le a) (ne.symm a_ne_bot)), rw grade_bot_eq_zero at h, exact ne_of_gt h, end end end graded /-- A graded, bounded partial order. -/ class graded_bounded_partial_order (α : Type*) extends bounded_partial_order α, graded α namespace graded_bounded_partial_order section parameters {α : Type*} [graded_bounded_partial_order α] (a : α) /-- If `grade a = grade ⊤`, then `a = ⊤`. -/ theorem eq_top_of_grade_eq_grade_top : graded.grade a = graded.grade (⊤ : α) → a = ⊤ := begin contrapose, intro a_ne_bot, exact ne_of_lt ( lt_grade_of_lt (lt_of_le_of_ne (le_top a) a_ne_bot)), end /-- The grade of any face is in the interval `[0, grade ⊤]`. -/ theorem grade_mem_Iic : graded.grade a ∈ set.Iic (graded.grade (⊤ : α)) := graded.le_grade_of_le (le_top a) /-- The grade of a face as a member of a finite set. -/ def fin_grade : α → fin (grade (⊤ : α) + 1) := λ a, ⟨graded.grade a, nat.lt_succ_iff.mpr (graded.le_grade_of_le (le_top a))⟩ end end graded_bounded_partial_order namespace flag section variables {α : Type*} [graded_bounded_partial_order α] {f f' : set α} /-- A flag is a maximal chain. -/ def is_flag (c : set α) : Prop := @zorn.is_max_chain _ (<) c /-- Two flags are adjacent when they differ by exactly one element. -/ def flag_adj (f f' : set α) : Prop := is_flag f → is_flag f' → #(set.diff f f') = 1 /-- If one attempts to extend a flag `f` by an element `e` which is comparable to -- all other faces of the flag, we obtain a contradiction. -/ lemma flag_extend (e : α) : is_flag f → e ∉ f → ¬(∀ a ∈ f, a ≠ e → a < e ∨ e < a) := begin -- We define `f' = f ∪ {e}`. intros ff e_nmem_f h, let f' := f ∪ {e}, have hf' : ∀ a ∈ f', a ∈ f ∨ a = e := by simp, apply ff.right, use f', -- `f` is not equal to `f'`. have f_ne_f' : f ≠ f' := begin intro f_eq_f', rw f_eq_f' at e_nmem_f, exact e_nmem_f (set.mem_union_right f rfl), end, -- We prove that `f'` is a superchain of `f`, a contradiction! split, { intros a a_mem_f' b b_mem_f' a_ne_b, -- Cases depending on whether `a` or `b` equal `e`. cases hf' a a_mem_f' with a_mem_f a_eq_t, { cases hf' b b_mem_f' with b_mem_f b_eq_t, { exact ff.left a a_mem_f b b_mem_f a_ne_b, }, rw b_eq_t at *, exact h a a_mem_f a_ne_b, }, cases hf' b b_mem_f' with b_mem_f b_eq_t, { rw a_eq_t at *, exact or.swap (h b b_mem_f (ne.symm a_ne_b)), }, rw b_eq_t at *, exact false.elim (a_ne_b a_eq_t), }, exact set.ssubset_iff_subset_ne.mpr ⟨set.subset_union_left f {e}, f_ne_f'⟩, end -- Any flag contains the bottom face `⊥`. theorem bot_in_flag : is_flag f → ⊥ ∈ f := begin -- We use the `flag_extend` lemma. intro ff, by_contra bot_nmem_f, apply flag_extend ⊥ ff bot_nmem_f, -- The bottom face is less or equal to any other. intros a a_mem_f a_ne_bot, exact or.inr (lt_of_le_of_ne bot_le (ne.symm a_ne_bot)), end -- Any flag contains the top face `⊤`. theorem top_in_flag : is_flag f → ⊤ ∈ f := begin -- We use the `flag_extend` lemma. intro ff, by_contra top_nmem_f, apply flag_extend ⊤ ff top_nmem_f, -- The top face is greater or equal to any other. intros a a_mem_f a_ne_bot, exact or.inl (lt_of_le_of_ne le_top (a_ne_bot)), end end end flag -- The faces of a flag are merely its elements. def flag_faces {α : Type*} [graded_bounded_partial_order α] {f : set α} (ff : flag.is_flag f) : Type* := f namespace flag_faces section parameters {α : Type*} [graded_bounded_partial_order α] {f : set α} {ff : flag.is_flag f} (a b : flag_faces ff) -- Subtyping preserves equality and viceversa. @[simp] lemma eq_iff_subtype : a = b ↔ a.val = b.val := subtype.ext_iff_val -- Subtyping preserves inequality and viceversa. lemma ne_iff_subtype : a ≠ b ↔ a.val ≠ b.val := by simp -- Flag faces form a partial order. instance of_partial_order : partial_order (flag_faces ff) := { le := λ a b, a.val ≤ b.val, le_refl := λ a, le_refl a.val, le_trans := λ _ _ _ a_le_b b_le_c, le_trans a_le_b b_le_c, le_antisymm := λ _ _ a_le_b b_le_a, subtype.eq (le_antisymm a_le_b b_le_a), } -- Subtyping preserves order and viceversa. @[simp] lemma lt_iff_subtype : a < b ↔ a.val < b.val := iff.symm lt_iff_le_not_le -- Flag faces form a linear order. noncomputable instance of_linear_order : linear_order (flag_faces ff) := { le_total := begin intros a b, -- `a = b` is trivial. by_cases a_eq_b : a = b, { exact or.inl (eq.symm a_eq_b).ge, }, -- If `a ≠ b`, then either `a < b`... cases ff.left a.val (subtype.mem a) b.val (subtype.mem b) ((ne_iff_subtype a b).mp a_eq_b) with av_lt_bv bv_lt_av, { exact or.inl (le_of_lt ((lt_iff_subtype a b).mpr av_lt_bv)), }, -- ...or `b < a`. exact or.inr (le_of_lt ((lt_iff_subtype b a).mpr bv_lt_av)), end, decidable_le := classical.dec_rel _, ..of_partial_order } -- Flag faces form a graded bounded partial order. instance of_graded_bounded_partial_order : graded_bounded_partial_order (flag_faces ff) := { bot := ⟨⊥, flag.bot_in_flag ff⟩, bot_le := λ _, bot_le, top := ⟨⊤, flag.top_in_flag ff⟩, le_top := λ _, @le_top α _ _, grade := λ a, graded.grade a.val, grade_bot_eq_zero := graded.grade_bot_eq_zero, lt_grade_of_lt := begin intros _ _ a_lt_b, exact graded.lt_grade_of_lt ((lt_iff_subtype _ _).mp a_lt_b), end, eq_p1_of_cover := begin -- It suffices to prove that `a` covers `c`. rintros a c ⟨a_lt_c, hne⟩, apply graded.eq_p1_of_cover, use (lt_iff_subtype a c).mp a_lt_c, -- To do this, we prove that any element between `a` and `c` must be in `f`. by_contra he, rcases he with ⟨bv, av_lt_bv, bv_lt_cv⟩, apply hne, -- To use the `flag_extend` lemma, we must prove that any `x ∈ f` is comparable to `b`. have bv_mem_f : bv ∈ f := begin by_contra b_nmem_f, apply flag.flag_extend bv ff b_nmem_f, intros xv x_mem_f _, let x : flag_faces ff := ⟨xv, x_mem_f⟩, -- `x` must be below `a` or above `c` (since there's no elements in between). have x_le_a_or_c_le_x : x ≤ a ∨ c ≤ x := begin by_cases x_le_a : x ≤ a, { exact or.inl x_le_a, }, by_cases c_le_x : c ≤ x, { exact or.inr c_le_x, }, exfalso, exact hne ⟨x, not_le.mp x_le_a, not_le.mp c_le_x⟩, end, -- We finish by transitivity. cases x_le_a_or_c_le_x with x_le_a c_le_x, { exact or.inl (lt_of_le_of_lt x_le_a av_lt_bv), }, exact or.inr (lt_of_lt_of_le bv_lt_cv c_le_x), end, let b : flag_faces ff := ⟨bv, bv_mem_f⟩, exact ⟨b, (lt_iff_subtype a b).mpr av_lt_bv, (lt_iff_subtype b c).mpr bv_lt_cv⟩, end, ..of_partial_order, } end end flag_faces namespace flag section variables {α : Type*} [graded_bounded_partial_order α] {f f' : set α} /-- Casts a flag into a set of its own faces. -/ def to_flag_faces (ff : is_flag f) : set (flag_faces ff) := subtype.val ⁻¹' f /-- Every set of faces in a flag is a subset of the entire set. -/ lemma ssubset_flag_faces {ff : is_flag f} (s : set (flag_faces ff)) : s ⊆ to_flag_faces ff := λ s _, subtype.mem s /-- If `s` contains all faces of a flag, it must be the set of all faces. -/ lemma eq_of_ssubset_flag_faces (ff : is_flag f) (s : set (flag_faces ff)) : to_flag_faces ff ⊆ s → s = to_flag_faces ff := begin intro ff_subset_s, refine set.eq_of_subset_of_subset _ ff_subset_s, exact ssubset_flag_faces s, end /-- Applying `to_flag_faces` to a flag does not change the fact that it is a flag. -/ theorem to_flag_faces_is_flag (ff : is_flag f) : is_flag (to_flag_faces ff) := begin split, { intros _ _ _ _ a_ne_b, exact ne.lt_or_lt a_ne_b, }, by_contra h, rcases h with ⟨ch, _, sch⟩, rw set.ssubset_def at sch, exact sch.right (ssubset_flag_faces ch), end /-- The subtypes of all elements of a flag form the original set. -/ lemma subtype_of_flag_faces_eq_flag (ff : is_flag f) : subtype.val '' to_flag_faces ff = f := begin apply set.ext, intro x, split, { intro h, rcases h with ⟨_, a_mem_ff, av_eq_x⟩, exact set.mem_of_eq_of_mem (eq.symm av_eq_x) a_mem_ff, }, intro x_mem_f, use ⟨x, x_mem_f⟩, use x_mem_f, end /-- The set of grades of a flag. -/ def flag_grades (f : set α): set ℕ := {n | ∃ a ∈ f, graded.grade a = n} /-- In a flag, `grade a < grade b` implies `a < b`. -/ theorem grade_lt_of_lt {ff : is_flag f} {a b : flag_faces ff} : graded.grade a < graded.grade b → a < b := begin rintros ga_lt_gb, cases lt_trichotomy a b with a_lt_b a_nlt_b, { exact a_lt_b, }, cases a_nlt_b with a_eq_b a_gt_b, { rw a_eq_b at ga_lt_gb, exact false.elim (nat.lt_asymm ga_lt_gb ga_lt_gb), }, exact false.elim (nat.lt_asymm ga_lt_gb (graded.lt_grade_of_lt a_gt_b)), end /-- No two elements in a flag have the same grade. -/ theorem grade_eq_of_eq {ff : is_flag f} {a b : flag_faces ff} : graded.grade a = graded.grade b → a = b := begin rintros ga_eq_gb, cases lt_trichotomy a b with a_lt_b a_nlt_b, { exact false.elim (ne_of_lt (graded.lt_grade_of_lt a_lt_b) ga_eq_gb), }, cases a_nlt_b with a_eq_b a_gt_b, { exact a_eq_b, }, exact false.elim (ne_of_gt (graded.lt_grade_of_lt a_gt_b) ga_eq_gb), end /-- Flag grades on a flag are sent to the interval `[0, grade ⊤]`. -/ theorem flag_grades_maps_to (ff : is_flag f) : set.maps_to graded.grade f (set.Iic (graded.grade (⊤ : α))) := λ _ _, graded.le_grade_of_le le_top /-- Flag grades are injective on a flag. -/ theorem flag_grades_inj_on (ff : is_flag f) : set.inj_on graded.grade f := begin intros a a_mem_f b b_mem_f ga_eq_gb, apply (flag_faces.eq_iff_subtype ⟨a, a_mem_f⟩ ⟨b, b_mem_f⟩).mp, apply grade_eq_of_eq, exact ga_eq_gb, exact ff, end /-- `fin_grade` is an embedding from `flag_faces ff` into `fin (grade ⊤ + 1)`. -/ def fin_grade_inj (ff : is_flag f) : flag_faces ff ↪ fin (graded.grade (⊤ : α) + 1) := begin use graded_bounded_partial_order.fin_grade, intros a b fga_eq_fgb, exact grade_eq_of_eq (fin.mk.inj_iff.mp fga_eq_fgb), end /-- Flag grades are injective on a flag. -/ theorem flag_grades_inj_on' (ff : is_flag f) : set.inj_on graded.grade (to_flag_faces ff) := begin apply flag_grades_inj_on, exact to_flag_faces_is_flag ff, end /-- The faces of a flag have a fintype, i.e. every flag is finite. -/ noncomputable theorem flag_fintype (ff : is_flag f) : fintype (flag_faces ff) := begin -- We define the interval `[0, grade ⊤]` and its inverse image under `grade`, onto `f`. let I := set.Iic (graded.grade (⊤ : α)), let I_fin := set.finite_le_nat (graded.grade (⊤ : α)), let f' : set (flag_faces ff) := graded.grade ⁻¹' I, have f'_eq_to_flag_faces_ff : f' = to_flag_faces ff := begin apply eq_of_ssubset_flag_faces, intros a _, exact graded_bounded_partial_order.grade_mem_Iic a, end, -- The `grade` function is injective on the flag. have flag_grades_inj_on_ff : @set.inj_on (flag_faces ff) ℕ graded.grade f' := begin rw f'_eq_to_flag_faces_ff, apply flag_grades_inj_on', end, -- Since `I` is finite, so are `f'` and `f`. have f'_fin : f'.finite := @set.finite.preimage (flag_faces ff) ℕ I graded.grade flag_grades_inj_on_ff I_fin, rw f'_eq_to_flag_faces_ff at f'_fin, have f_fin : f.finite := begin have h := set.finite.image subtype.val f'_fin, rw subtype_of_flag_faces_eq_flag at h, exact h, end, exact set.finite.fintype f_fin, end /-- The assertion that a flag is finite. -/ def flag_finite (ff : is_flag f) : f.finite := ⟨flag_fintype ff⟩ /-- A flag contains faces of each grade up to the grade of its topmost face. -/ theorem flag_grades_Iic (ff : is_flag f) : flag_grades f = set.Iic (graded.grade (⊤ : α)) := begin let G := flag_grades f, let N := graded.grade (⊤ : α), let I := set.Iic N, -- Every flag grade is between `0` and `N`. have G_in_I : G ⊆ I := begin rintros _ ⟨_, a_mem_f, ga_eq_f⟩, rw ←ga_eq_f, exact flag_grades_maps_to ff a_mem_f, end, -- Every number between `0` and `N` is a flag grade. have I_in_G : I ⊆ G := begin -- We suppose, by contradiction, that we're missing a number `n`. intros n n_mem_I, by_contra n_nmem_G, -- We build the intersection `[0, n] ∩ G` and prove that it's finite and non-empty. let Sm := (set.Iic n) ∩ G, let Sm_finite : Sm.finite := set.finite.inf_of_left (set.finite_le_nat n) G, let Sm_finset := set.finite.to_finset Sm_finite, have Sm_finset_non : Sm_finset.nonempty := begin use 0, rw set.finite.mem_to_finset, exact ⟨zero_le n, ⟨⊥, bot_in_flag ff, graded.grade_bot_eq_zero⟩⟩, end, -- We build the largest grade in `G` that's lesser than `n`. let m := Sm_finset.max' Sm_finset_non, have m_mem_Sm := (set.finite.mem_to_finset Sm_finite).mp (Sm_finset.max'_mem Sm_finset_non), cases m_mem_Sm with m_le_n m_mem_G, have m_lt_n : m < n := begin apply lt_of_le_of_ne, apply m_le_n, by_contra m_eq_n, have h : m = n ↔ ¬ m ≠ n := not_not.symm, rw ←h at m_eq_n, rw ←m_eq_n at n_nmem_G, exact n_nmem_G m_mem_G, end, -- We prove that no grades in `(m, n)` may appear in `G`. have hm : ∀ k : ℕ, k ∈ set.Ioo m n → k ∉ G := begin intros k k_mem_i, by_contra k_mem_G, have k_le_m : k ≤ m := begin apply finset.le_max', apply set.mem_to_finset.mpr, exact set.mem_sep (set.mem_Iic.mpr (le_of_lt k_mem_i.right)) k_mem_G, end, exact false.elim (not_lt.mpr k_le_m k_mem_i.left), end, -- We build the intersection `[n, ∞] ∩ G`. let SM := (set.Ici n) ∩ G, have SM_non : SM.nonempty := ⟨N, set.mem_inter n_mem_I ⟨⊤, top_in_flag ff, rfl⟩⟩, -- We build the smallest grade in `G` that's greater than `N`. let M : ℕ := well_founded.min nat.lt_wf SM SM_non, have M_mem_SM := nat.lt_wf.min_mem SM SM_non, cases M_mem_SM with n_le_M M_mem_G, have n_lt_M : n < M := begin apply lt_of_le_of_ne, apply n_le_M, by_contra n_eq_M, have h : n = M ↔ ¬ n ≠ M := not_not.symm, rw ←h at n_eq_M, rw n_eq_M at n_nmem_G, exact n_nmem_G M_mem_G, end, -- We prove that no grades in `[n, M)` may appear in `G`. have hM : ∀ k : ℕ, k ∈ set.Ico n M → k ∉ G := begin intros k k_mem_i, by_contra k_mem_G, have k_ge_m : k ≥ M := begin apply le_of_not_lt, apply well_founded.not_lt_min nat.lt_wf SM SM_non, exact set.mem_sep (set.mem_Ici.mpr k_mem_i.left) k_mem_G, end, exact false.elim (not_lt.mpr k_ge_m k_mem_i.right), end, -- `m < M`, obviously. have m_lt_M : m < M := lt_trans m_lt_n n_lt_M, -- We build faces `a` and `c` in the flag with grades `m` and `M`. cases m_mem_G with a ea, cases M_mem_G with c ec, cases ea with a_mem_f ga_eq_m, cases ec with c_mem_f gc_eq_M, let a : flag_faces ff := ⟨a, a_mem_f⟩, let c : flag_faces ff := ⟨c, c_mem_f⟩, -- `a` must be less than `c`. have ga_eq_m : graded.grade a = m := ga_eq_m, have gc_eq_M : graded.grade c = M := gc_eq_M, have a_lt_c : a < c := begin rw ←ga_eq_m at m_lt_M, rw ←gc_eq_M at m_lt_M, exact grade_lt_of_lt m_lt_M, end, -- There can't exist any face in the flag that's between `a` and `c`. have C : ¬ ∃ b, a < b ∧ b < c := begin intro he, cases he with b he, cases he with a_lt_b b_lt_c, let g := graded.grade b, have m_lt_g : m < g := begin rw ←ga_eq_m, exact graded.lt_grade_of_lt a_lt_b, end, have g_lt_M : g < M := begin rw ←gc_eq_M, exact graded.lt_grade_of_lt b_lt_c, end, have g_mem_G : g ∈ G := ⟨b.val, subtype.mem b, rfl⟩, by_cases g_lt_n : g < n, { exact hm g (set.mem_inter m_lt_g g_lt_n) g_mem_G, }, exact hM g (set.mem_inter (le_of_not_gt g_lt_n) g_lt_M) g_mem_G, end, -- As a consequence, `m + 1 = M`. have ga_p1_eq_gc : graded.grade a + 1 = graded.grade c := graded.eq_p1_of_cover ⟨a_lt_c, C⟩, have m_p1_eq_M : m + 1 = M := begin rw ga_eq_m at ga_p1_eq_gc, rw gc_eq_M at ga_p1_eq_gc, exact ga_p1_eq_gc, end, -- But then, the existence of `n` such that `m < n < M` is impossible! linarith, end, exact set.subset.antisymm G_in_I I_in_G, end /-- Flag grades are surjective from a flag onto `[0, grade ⊤]`. -/ theorem flag_grades_surj_on (ff : is_flag f) : set.surj_on graded.grade f (set.Iic (graded.grade (⊤ : α))) := begin intros n n_mem_Iic, have h : graded.grade '' f = flag_grades f := set.image_eq graded.grade f, rw h, rw flag_grades_Iic ff, exact n_mem_Iic, end /-- Flag grades are surjective from a flag onto `[0, grade ⊤]`. -/ theorem flag_grades_surj_on' (ff : is_flag f) : set.surj_on graded.grade (to_flag_faces ff) (set.Iic (graded.grade (⊤ : α))) := begin apply flag_grades_surj_on, exact to_flag_faces_is_flag ff, end /-- Flag grades are bijective from a flag onto `[0, grade ⊤]`. -/ theorem flag_grades_bij_on (ff : is_flag f) : set.bij_on graded.grade f (set.Iic (graded.grade (⊤ : α))) := ⟨flag_grades_maps_to ff, flag_grades_inj_on ff, flag_grades_surj_on ff⟩ /-- Flag grades are bijective from a flag onto `[0, grade ⊤]`. -/ theorem flag_grades_bij_on' (ff : is_flag f) : set.bij_on graded.grade (to_flag_faces ff) (set.Iic (graded.grade (⊤ : α))) := begin apply flag_grades_bij_on, exact to_flag_faces_is_flag ff, end def fin_grade_inv (ff : is_flag f) : fin (graded.grade (⊤ : α) + 1) → flag_faces ff := begin --have h := function.embedding.inv_of_mem_range graded_bounded_partial_order.fin_grade, sorry, end def faces_equiv_grades (ff : is_flag f) : flag_faces ff ≃ fin (graded.grade (⊤ : α) + 1) := begin use graded_bounded_partial_order.fin_grade, sorry, sorry, sorry, end /-- The cardinality of a flag. -/ def flag_card (ff : is_flag f) [fintype (flag_faces ff)] : ℕ := fintype.card (flag_faces ff) /-- Any flag's cardinality equals the grade of the top face, plus one. -/ theorem flag_card_eq_grade_top_p1 (ff : is_flag f) [fintype (flag_faces ff)] : flag_card ff = graded.grade (⊤ : α) + 1 := begin let N := graded.grade (⊤ : α), rw ←fintype.card_fin (N + 1), apply fintype.card_congr, split, rotate, rotate, { intro a, use graded.grade a, }, { sorry, }, { sorry, }, sorry, end /-- All flags have the same cardinality. -/ theorem all_flags_same_card (ff : is_flag f) (ff' : is_flag f') [fintype (flag_faces ff)] [fintype (flag_faces ff')] : flag_card ff = flag_card ff' := begin have h₁ := flag_card_eq_grade_top_p1 ff, rw ←(flag_card_eq_grade_top_p1 ff') at h₁, exact h₁, end /-- Flag adjacency in an abstract polytope is commutative. -/ theorem flag_adj_comm : flag.is_flag f → flag.is_flag f' → flag.flag_adj f f' → flag.flag_adj f' f := begin intros ff ff', sorry, end end end flag namespace flag_faces section parameters {α : Type*} [graded_bounded_partial_order α] {f : set α} {ff : flag.is_flag f} instance of_well_order : is_well_order (flag_faces ff) (<) := { wf := begin apply well_founded.intro, have h : ∀ {n : ℕ} (a : flag_faces ff), graded.grade a ≤ n → acc (<) a := begin intro n, induction n with n hn, { intros a ga_le_zero, apply acc.intro, intros y y_lt_a, rw (graded.eq_bot_of_grade_eq_zero (nat.le_zero_iff.mp ga_le_zero)) at y_lt_a, have bot_le_y : ⊥ ≤ y := bot_le, exact false.elim ((not_lt.mpr bot_le_y) y_lt_a), }, intros a ga_le_ns, apply acc.intro, intros y y_lt_a, exact hn y (nat.lt_succ_iff.mp (lt_of_lt_of_le (graded.lt_grade_of_lt y_lt_a) ga_le_ns)), end, intro a, exact h a rfl.ge, end } end end flag_faces set_option old_structure_cmd false class abstract_polytope (α : Type*) extends (graded_bounded_partial_order α) := (diamond : ∀ {a b : α}, grade a + 2 = grade b → #(set.Ioo a b) = 2) set_option old_structure_cmd true namespace abstract_polytope variables {α : Type*} [abstract_polytope α] {f f' : set α} def grade : ℕ := graded.grade (⊤ : α) -- Any nontrivial section contains a vertex. theorem section_vertex (a b : α) : b < a → ∃ c ∈ set.Icc b a, covers b c := begin -- Set up an induction on (grade a), which can almost certainly be done more elegantly let m := nat.succ (graded.grade a), have grade_a_m_succ : graded.grade a < m, { apply lt_add_one, }, revert grade_a_m_succ, generalize : m = n, clear m, revert a b, induction n with n ih, { intros a b grade_a_lt_zero, cases nat.not_lt_zero _ grade_a_lt_zero, }, intros a b grade_a_n_succ b_lt_a, -- Is there something between a and b? by_cases ∃ c : α, b < c ∧ c < a, { -- Yes, try to find a cover between that and b. cases h with c h, cases h with b_lt_c c_lt_a, have h : ∃ (d ∈ set.Icc b c), covers b d, { apply ih, { let grade_c_lt_grade_a := graded.lt_grade_of_lt c_lt_a, have grade_a_le_n : graded.grade a ≤ n, { exact nat.le_of_lt_succ grade_a_n_succ, }, exact nat.lt_of_lt_of_le grade_c_lt_grade_a grade_a_le_n, }, exact b_lt_c, }, cases h with d h, use d, cases h with d_between_b_a covers_b_d, split, { rewrite set.mem_Icc, rewrite set.mem_Icc at d_between_b_a, cases d_between_b_a with b_le_d d_le_c, split, { exact b_le_d, }, exact le_trans d_le_c (le_of_lt c_lt_a), }, exact covers_b_d, }, -- No, so a is covering. use a, split, { rewrite set.mem_Icc, split, { exact le_of_lt b_lt_a, }, apply le_refl, }, split, { exact b_lt_a, }, exact h, end end abstract_polytope #lint
75cc6ae90a1aaae2b6bb71729188c348a86ed9fe
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/data/seq/wseq.lean
8f1e9962b0df2a986ae5aec5525eb6dd07bc4213
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
51,748
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.seq.seq data.seq.computation data.dlist universes u v w -- While the `seq` structure allows for lists which may not be finite, -- a weak sequence also allows the computation of each element to -- involve an indeterminate amount of computation, including possibly -- an infinite loop. This is represented as a regular `seq` interspersed -- with `none` elements to indicate that computation is ongoing. -- -- This model is appropriate for Haskell style lazy lists, and is closed -- under most interesting computation patterns on infinite lists, -- but conversely it is difficult to extract elements from it. /- coinductive wseq (α : Type u) : Type u | nil : wseq α | cons : α → wseq α → wseq α | think : wseq α → wseq α -/ def wseq (α) := seq (option α) namespace wseq variables {α : Type u} {β : Type v} {γ : Type w} def of_seq : seq α → wseq α := (<$>) some def of_list (l : list α) : wseq α := of_seq l def of_stream (l : stream α) : wseq α := of_seq l instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩ instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩ instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩ def nil : wseq α := seq.nil def cons (a : α) : wseq α → wseq α := seq.cons (some a) def think : wseq α → wseq α := seq.cons none def destruct : wseq α → computation (option (α × wseq α)) := computation.corec (λs, match seq.destruct s with | none := sum.inl none | some (none, s') := sum.inr s' | some (some a, s') := sum.inl (some (a, s')) end) def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := seq.cases_on s h1 (λ o, option.cases_on o h3 h2) protected def mem (a : α) (s : wseq α) := seq.mem (some a) s instance : has_mem α (wseq α) := ⟨wseq.mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a def head (s : wseq α) : computation (option α) := computation.map ((<$>) prod.fst) (destruct s) def flatten : computation (wseq α) → wseq α := seq.corec (λc, match computation.destruct c with | sum.inl s := seq.omap return (seq.destruct s) | sum.inr c' := some (none, c') end) def tail (s : wseq α) : wseq α := flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s def drop (s : wseq α) : ℕ → wseq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n) def to_list (s : wseq α) : computation (list α) := @computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩, match seq.destruct s with | none := sum.inl l.reverse | some (none, s') := sum.inr (l, s') | some (some a, s') := sum.inr (a::l, s') end) ([], s) def length (s : wseq α) : computation ℕ := @computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s with | none := sum.inl n | some (none, s') := sum.inr (n, s') | some (some a, s') := sum.inr (n+1, s') end) (0, s) @[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h def get (s : wseq α) [is_finite s] : list α := (to_list s).get @[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0 def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (some a, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) def remove_nth (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (none, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) def filter_map (f : α → option β) : wseq α → wseq β := seq.corec (λs, match seq.destruct s with | none := none | some (none, s') := some (none, s') | some (some a, s') := some (f a, s') end) def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α := filter_map (λa, if p a then some a else none) -- example of infinite list manipulations def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) := head $ filter p s def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ := @seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (none, s1, s2') | some (none, s1'), some (some a2, s2') := some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2') | _, _ := none end) (s1, s2) def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ := (zip s (stream.nats : wseq ℕ)).filter_map (λ ⟨a, n⟩, if p a then some n else none) def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ := (λ o, option.get_or_else o 0) <$> head (find_indexes p s) def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a) def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a) -- nondeterministic def union (s1 s2 : wseq α) : wseq α := @seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | none, none := none | some (a1, s1'), none := some (a1, s1', nil) | none, some (a2, s2') := some (a2, nil, s2') | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') := some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2') end) (s1, s2) def is_empty (s : wseq α) : computation bool := computation.map option.is_none $ head s -- Calculate one step of computation def compute (s : wseq α) : wseq α := match seq.destruct s with | some (none, s') := s' | _ := s end def take (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match n, seq.destruct s with | 0, _ := none | m+1, none := none | m+1, some (none, s') := some (none, m+1, s') | m+1, some (some a, s') := some (some a, m, s') end) (n, s) def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) := @computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩, match n, seq.destruct s with | 0, _ := sum.inl (l.reverse, s) | m+1, none := sum.inl (l.reverse, s) | m+1, some (none, s') := sum.inr (n, l, s') | m+1, some (some a, s') := sum.inr (m, a::l, s') end) (n, [], s) def any (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl ff | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inl tt else sum.inr s' end) s def all (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl tt | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inr s' else sum.inl ff end) s def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α := cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, a, s') | some (some b, s') := let a' := f a b in some (some a', a', s') end) (a, s) def inits (s : wseq α) : wseq (list α) := cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, l, s') | some (some a, s') := let l' := l.concat a in some (some l'.to_list, l', s') end) (dlist.empty, s) -- Like take, but does not wait for a result def collect (s : wseq α) (n : ℕ) : list α := (seq.take n s).filter_map id def append : wseq α → wseq α → wseq α := seq.append def map (f : α → β) : wseq α → wseq β := seq.map (option_map f) def join (S : wseq (wseq α)) : wseq α := seq.join ((λo : option (wseq α), match o with | none := seq1.ret none | some s := (none, s) end) <$> S) def bind (s : wseq α) (f : α → wseq β) : wseq β := join (map f s) def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) : option (α × wseq α) → option (β × wseq β) → Prop | none none := true | (some (a, s)) (some (b, t)) := R a b ∧ C s t | _ _ := false attribute [simp] lift_rel_o theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p | none none h := trivial | (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h | none (some _) h := false.elim h | (some (_, _)) none h := false.elim h theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p := lift_rel_o.imp (λ _ _, id) H def bisim_o (R : wseq α → wseq α → Prop) : option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R attribute [simp] bisim_o theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : bisim_o R o p → bisim_o S o p := lift_rel_o.imp_right _ H def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop := ∃ C : wseq α → wseq β → Prop, C s t ∧ ∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t) -- If two sequences are equivalent, then they have the same values and -- the same computational behavior (i.e. if one loops forever then so does -- the other), although they may differ in the number of `think`s needed to -- arrive at the answer. def equiv : wseq α → wseq α → Prop := lift_rel (=) theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ := by refine computation.lift_rel.imp _ _ _ (h2 h1); apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩ theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) := ⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), or.inr h, λ s t h, begin have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), { cases h with h h, exact lift_rel_destruct h, assumption }, apply computation.lift_rel.imp _ _ _ h, intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end⟩⟩ infix ~ := equiv theorem destruct_congr {s t : wseq α} : s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct theorem destruct_congr_iff {s t : wseq α} : s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct_iff def lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, begin refine ⟨(=), rfl, λ s t (h : s = t), _⟩, rw ←h, apply computation.lift_rel.refl, intro a, cases a with a, simp, cases a; simp, apply H end def lift_rel_o.swap (R : α → β → Prop) (C) : function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) := funext $ λ x, funext $ λ y, by cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl } def lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) : lift_rel (function.swap R) s2 s1 := begin refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩, rw [←lift_rel_o.swap, computation.lift_rel.swap], apply lift_rel_destruct h end def lift_rel.swap (R : α → β → Prop) : function.swap (lift_rel R) = lift_rel (function.swap R) := funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩ def lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 (h : function.swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show function.swap R = R, from funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h def lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s t u h1 h2, begin refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩, cases h with t h, cases h with h1 h2, have h1 := lift_rel_destruct h1, have h2 := lift_rel_destruct h2, refine computation.lift_rel_def.2 ⟨(computation.terminates_of_lift_rel h1).trans (computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩, cases h1.left ha with b hb, cases hb with hb t1, have t2 := computation.rel_of_lift_rel h2 hb hc, cases a with a; cases c with c, { trivial }, { cases b, {cases t2}, {cases t1} }, { cases a, cases b with b, {cases t1}, {cases b, cases t2} }, { cases a with a s, cases b with b, {cases t1}, cases b with b t, cases c with c u, cases t1 with ab st, cases t2 with bc tu, exact ⟨H ab bc, t, st, tu⟩ } end def lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ @[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s := lift_rel.refl (=) eq.refl @[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s := lift_rel.symm (=) (@eq.symm _) @[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u := lift_rel.trans (=) (@eq.trans _) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ open computation local notation `return` := computation.return @[simp] theorem destruct_nil : destruct (nil : wseq α) = return none := computation.destruct_eq_ret rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) := computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap] @[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think := computation.destruct_eq_think $ by simp [destruct, think, computation.rmap] @[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none := seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) := seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) := seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl @[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl @[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s := begin refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl, intros s' s h, rw ←h, simp [flatten], cases seq.destruct s, { simp }, { cases a with o s', simp } end @[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) := seq.destruct_eq_cons $ by simp [flatten, think] @[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct := begin refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | c, ._, (or.inl rfl) := by cases c.destruct; simp | ._, ._, (or.inr ⟨c, rfl, rfl⟩) := begin apply c.cases_on (λa, _) (λc', _); repeat {simp}, { cases (destruct a).destruct; simp }, { exact or.inr ⟨c', rfl, rfl⟩ } end end end theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : wseq α) n = nil := by induction n; simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop] @[simp] theorem dropn_think (s : wseq α) (n) : drop (think s) n = (drop s n).think := by induction n; simp [*, drop] theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n := congr_arg head (dropn_add _ _ _) theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] def join_nil : join nil = (nil : wseq α) := seq.join_nil @[simp] def join_think (S : wseq (wseq α)) : join (think S) = think (join S) := by { simp [think, join], unfold has_map.map, simp [join, seq1.ret] } @[simp] def join_cons (s : wseq α) (S) : join (cons s S) = think (append s (join S)) := by { simp [think, join], unfold has_map.map, simp [join, cons, append] } @[simp] lemma nil_append (s : wseq α) : append nil s = s := seq.nil_append _ @[simp] lemma cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _ @[simp] lemma think_append (s t : wseq α) : append (think s) t = think (append s t) := seq.cons_append _ _ _ @[simp] lemma append_nil (s : wseq α) : append s nil = s := seq.append_nil _ @[simp] lemma append_assoc (s t u : wseq α) : append (append s t) u = append s (append t u) := seq.append_assoc _ _ _ def tail.aux : option (α × wseq α) → computation (option (α × wseq α)) | none := return none | (some (a, s)) := destruct s attribute [simp] tail.aux theorem destruct_tail (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux := begin dsimp [tail], simp, rw [←monad.bind_pure_comp_eq_map, monad.bind_assoc], apply congr_arg, apply funext, intro o, cases o; [skip, cases a with a s]; apply (monad.pure_bind _ _).trans _; simp end def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α)) | 0 := return | (n+1) := λ a, tail.aux a >>= drop.aux n attribute [simp] drop.aux def drop.aux_none : ∀ n, @drop.aux α n none = return none | 0 := rfl | (n+1) := show computation.bind (return none) (drop.aux n) = return none, by rw [ret_bind, drop.aux_none] attribute [simp] drop.aux theorem destruct_dropn : ∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n | s 0 := (bind_ret' _).symm | s (n+1) := by rw [←dropn_tail, destruct_dropn _ n, destruct_tail, monad.bind_assoc]; refl theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] : terminates (head s) := (head_terminates_iff _).2 $ begin cases (head_terminates_iff _).1 T with a h, simp [tail] at h, cases exists_of_mem_bind h with s' h1, cases h1 with h1 h2, unfold has_map.map at h1, exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3 end theorem destruct_some_of_destruct_tail_some {s : wseq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := begin unfold tail has_map.map at h, simp at h, cases exists_of_mem_bind h with t ht, cases ht with tm td, clear h, cases exists_of_mem_map tm with t' ht', cases ht' with ht' ht2, clear tm, cases t' with t'; rw ←ht2 at td; simp at td, { have := mem_unique td (ret_mem _), contradiction }, { exact ⟨_, ht'⟩ } end theorem head_some_of_head_tail_some {s : wseq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := begin unfold head at h, cases exists_of_mem_map h with o ho, cases ho with md e, clear h, cases o with o; injection e, clear e h, cases destruct_some_of_destruct_tail_some md with a am, exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩ end theorem head_some_of_nth_some {s : wseq α} {a n} (h : some a ∈ nth s n) : ∃ a', some a' ∈ head s := begin revert a, induction n with n IH; intros, exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h'] end instance productive_tail (s : wseq α) [productive s] : productive (tail s) := λ n, by rw [nth_tail]; apply_instance instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) := λ m, by rw [←nth_add]; apply_instance def to_seq (s : wseq α) [productive s] : seq α := ⟨λ n, (nth s n).get, λn h, begin ginduction computation.get (nth s (n + 1)) with e, {trivial}, have := mem_of_get_eq _ e, simp [nth] at this h, cases head_some_of_head_tail_some this with a' h', have := mem_unique h' (@mem_of_get_eq _ _ _ _ h), contradiction end⟩ theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) := by induction h with m' h IH; [exact id, exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) := nth_terminates_le (nat.zero_le n) theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) := (head_terminates_iff _).1 $ head_terminates_of_nth_terminates T theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := begin apply seq.mem_rec_on M, intros o s' h, cases o with b, { apply h2, cases h, {contradiction}, {assumption} }, { apply h1, apply or.imp_left _ h, intro h, injection h } end @[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s := begin cases s with f al, change some (some a) ∈ some none :: f ↔ some (some a) ∈ f, constructor; intro h, { apply (stream.eq_or_mem_of_mem_cons h).resolve_left, intro, injections }, { apply stream.mem_cons_of_mem _ h } end theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := begin generalize e : destruct s = c, intro h, revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s; apply s.cases_on _ (λ x s, _) (λ s, _); intros m; have := congr_arg computation.destruct m; simp at this; injections with i1 i2 i3 i4 i5, { rw [i4, i5], cases s' with f al, unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp, rw [show a = a' ↔ some (some a) = some (some a'), by constructor; intro h; [rw h, repeat {injection h}]], refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩, { cases o with e m, { rw e, apply stream.mem_cons }, { exact stream.mem_cons_of_mem _ m } } }, { simp, exact IH i2 } end @[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem $ by simp [ret_mem] theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (or.inr h) theorem mem_cons (s : wseq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (or.inl rfl) theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s := begin intro h, have := h, cases h with n e, revert s, simp [stream.nth], induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _); repeat{simp}; intros m e; injections, { exact or.inr m }, { exact or.inr m }, { apply IH m, rw e, cases tail s, refl } end theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0 h := h | (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h) theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s := begin revert s, induction n with n IH; intros s h, { cases exists_of_mem_map h with o h, cases h with h1 h2, cases o with o; injection h2, cases o with a' s', exact (eq_or_mem_iff_mem h1).2 (or.inl h.symm) }, { have := @IH (tail s), rw nth_tail at this, exact mem_of_mem_tail (this h) } end theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n := begin apply mem_rec_on h, { intros a' s' h, cases h with h h, { existsi 0, simp [nth], rw h, apply ret_mem }, { cases h with n h, existsi n+1, simp [nth], exact h } }, { intros s' h, cases h with n h, existsi n, simp [nth], apply think_mem h } end theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin cases (head_terminates_iff _).1 ⟨_, h⟩ with o om, have := mem_unique (mem_map _ om) h, cases o with o; injection this with i, cases o with a' s', dsimp at i, rw i at om, exact ⟨_, om⟩ end⟩ theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) : ∀ n, computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 := lift_rel_destruct H | (n+1) := begin simp [destruct_tail], apply lift_rel_bind, apply lift_rel_dropn_destruct n, exact λ a b o, match a, b, o with | none, none, _ := by simp | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2 end end theorem exists_of_lift_rel_left {R : α → β → Prop} {s t} (H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b := /-let ⟨n, h⟩ := exists_nth_of_mem h, ⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h, ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in ⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩-/ sorry -- TODO(Mario): This proof causes an unknown type-checking error theorem exists_of_lift_rel_right {R : α → β → Prop} {s t} (H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b := by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) := let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩ def of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := seq.of_mem_append def mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := seq.mem_append_left lemma exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in by cases o; injection oe; exact ⟨a, om, h⟩ @[simp] def lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil := by rw [lift_rel_destruct_iff]; simp @[simp] def lift_rel_cons (R : α → β → Prop) (a b s t) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t := by rw [lift_rel_destruct_iff]; simp @[simp] def lift_rel_think_left (R : α → β → Prop) (s t) : lift_rel R (think s) t ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp @[simp] def lift_rel_think_right (R : α → β → Prop) (s t) : lift_rel R s (think t) ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t := by unfold equiv; simp; exact h theorem think_equiv (s : wseq α) : think s ~ s := by unfold equiv; simp; apply equiv.refl theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t := by unfold equiv; simp; exact h theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t := suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from λ s t h o, ⟨this h, this h.symm⟩, begin intros s t h o ho, cases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ds dsm, cases dsm with dsm dse, rw ←dse, cases destruct_congr h with l r, cases l dsm with dt dtm, cases dtm with dtm dst, cases ds with a; cases dt with b, { apply mem_map _ dtm }, { cases b, cases dst }, { cases a, cases dst }, { cases a with a s', cases b with b t', rw dst.left, exact @mem_map _ _ (@has_map.map _ _ (α × wseq α) _ prod.fst) _ (destruct t) dtm } end theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s := begin apply computation.mem_rec_on h, { simp }, { intro s', apply equiv.trans, simp [think_equiv] } end theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)} (h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) := let S := λ s t, ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in ⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h, match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin simp, apply lift_rel_bind _ _ h, intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab), intros a b, apply lift_rel_o.imp_right, intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h] end end⟩ theorem flatten_congr {c1 c2 : computation (wseq α)} : computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t := begin apply flatten_congr, unfold has_map.map, rw [←bind_ret, ←bind_ret], apply lift_rel_bind _ _ (destruct_congr h), intros a b h, simp, cases a with a; cases b with b, { trivial }, { cases h }, { cases a, cases h }, { cases a with a s', cases b with b t', exact h.right } end theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n := by induction n; simp [*, tail_congr] theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n := head_congr (dropn_congr h _) theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩, λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in nth_mem ((nth_congr h _ _).1 hn) theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t := forall_congr $ λn, terminates_congr $ nth_congr h _ theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t := ⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin refine lift_rel_def.2 ⟨_, _⟩, { rw [←head_terminates_iff, ←head_terminates_iff], exact terminates_congr (h 0) }, { intros a b ma mb, cases a with a; cases b with b, { trivial }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { cases a with a s', cases b with b t', injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab, refine ⟨ab, λ n, _⟩, refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans ((_ : nth (tail s) n ~ nth (tail t) n).trans (nth_congr (flatten_equiv (mem_map _ mb)) n)), rw [nth_tail, nth_tail], apply h } } end⟩ theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) := begin refine eq_of_bisim (λ c1 c2, ∃ (l : list α) (s : wseq α), c1 = corec length._match_2 (l.length, s) ∧ c2 = computation.map list.length (corec to_list._match_2 (l, s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, cases h with l h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l, s, _, _⟩; simp }, { refine ⟨l, s, _, _⟩; simp } end @[simp] def of_list_nil : of_list [] = (nil : wseq α) := rfl @[simp] def of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := show seq.map some (seq.of_list (a :: l)) = seq.cons (some a) (seq.map some (seq.of_list l)), by simp @[simp] def to_list'_nil (l : list α) : corec to_list._match_2 (l, nil) = return l.reverse := destruct_eq_ret rfl @[simp] def to_list'_cons (l : list α) (s : wseq α) (a : α) : corec to_list._match_2 (l, cons a s) = (corec to_list._match_2 (a::l, s)).think := destruct_eq_think $ by simp [to_list, cons] @[simp] def to_list'_think (l : list α) (s : wseq α) : corec to_list._match_2 (l, think s) = (corec to_list._match_2 (l, s)).think := destruct_eq_think $ by simp [to_list, think] def to_list'_map (l : list α) (s : wseq α) : corec to_list._match_2 (l, s) = ((++) l.reverse) <$> to_list s := begin refine eq_of_bisim (λ c1 c2, ∃ (l' : list α) (s : wseq α), c1 = corec to_list._match_2 (l' ++ l, s) ∧ c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, cases h with l' h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l', s, _, _⟩; simp }, { refine ⟨l', s, _, _⟩; simp } end @[simp] def to_list_cons (a : α) (s) : to_list (cons a s) = (list.cons a <$> to_list s).think := destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl @[simp] def to_list_nil : to_list (nil : wseq α) = return [] := destruct_eq_ret rfl theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) := by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH) @[simp] theorem destruct_of_seq (s : seq α) : destruct (of_seq s) = return (option_map (λ a, (a, of_seq s.tail)) s.head) := destruct_eq_ret $ begin simp [of_seq, head, destruct, seq.destruct, seq.head], rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth], cases seq.nth s 0 with a, { refl }, unfold has_map.map, simp [option_map, option_bind, destruct] end @[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head := by simp [head]; cases seq.head s; refl @[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail := begin simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl}, rw [seq.head_cons, seq.tail_cons], refl end @[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n) | 0 := rfl | (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq] theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) := by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn] instance productive_of_seq (s : seq α) : productive (of_seq s) := λ n, by rw nth_of_seq; apply_instance theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s := begin apply subtype.eq, apply funext, intro n, dsimp [to_seq], apply get_eq_of_mem, rw nth_of_seq, apply ret_mem end def ret (a : α) : wseq α := of_list [a] @[simp] lemma map_nil (f : α → β) : map f nil = nil := rfl @[simp] lemma map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _ @[simp] lemma map_think (f : α → β) (s) : map f (think s) = think (map f s) := seq.map_cons _ _ _ @[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := seq.map_append _ _ _ lemma map_comp (f : α → β) (g : β → γ) (s : wseq α) : map (g ∘ f) s = map g (map f s) := begin dsimp [map], rw ←seq.map_comp, apply congr_fun, apply congr_arg, apply funext, intro o, cases o; refl end theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s := seq.mem_map (option_map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h, (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _), begin intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; injections with i1 i2 i3 i4, simp at m, simp, cases o with e IH, { apply or.inl, rwa i4 }, apply or.imp_right (λ m, _) m, simp at IH, apply IH _ _ i3 m }, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; injections with i1 i2 i3 i4, { apply or.inr, simp at m, cases IH s S i3 m with as ex, { exact ⟨s, mem_cons _ _, as⟩ }, { cases ex with s' h, cases h with sS as, exact ⟨s', mem_cons_of_mem _ sS, as⟩ } }, { apply or.inr, simp at m, cases (IH nil S (by simp [i3]) (by simp [m])).resolve_left (not_mem_nil _) with s h, cases h with sS as, exact ⟨s, by simp [sS], as⟩ }, { rw [mem_think], simp at m, apply IH _ _ i3 m } } end theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h, ⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩ lemma destruct_map (f : α → β) (s : wseq α) : destruct (map f s) = computation.map (option_map (prod.map f (map f))) (destruct s) := begin apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧ c2 = computation.map (option_map (prod.map f (map f))) (destruct s)), { intros c1 c2 h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp, { refl }, { refl }, { exact ⟨s, rfl, rfl⟩ } }, { exact ⟨s, rfl, rfl⟩ } end theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := ⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t, ⟨s1, s2, rfl, rfl, h1⟩, λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b; simp [option_map, option_bind], { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, exact ⟨h2 r, s, t, h, rfl, rfl⟩ } end end⟩ theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t := lift_rel_map _ _ h (λ _ _, congr_arg _) def destruct_append.aux (t : wseq α) : option (α × wseq α) → computation (option (α × wseq α)) | none := destruct t | (some (a, s)) := return (some (a, append s t)) attribute [simp] destruct_append.aux lemma destruct_append (s t : wseq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := begin apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩, intros c1 c2 h, cases h with s h, cases h with t h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp, { apply t.cases_on _ (λ b t, _) (λ t, _); simp; simp, { refine ⟨nil, t, _, _⟩; simp } }, { exact ⟨s, t, rfl, rfl⟩ } end def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α)) | none := return none | (some (s, S)) := (destruct (append s (join S))).think attribute [simp] destruct_join.aux lemma destruct_join (S : wseq (wseq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := begin apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | c, ._, or.inl rfl := by cases c.destruct; simp | ._, ._, or.inr ⟨S, rfl, rfl⟩ := begin apply S.cases_on _ (λ s S, _) (λ S, _); simp; simp, { refine or.inr ⟨S, rfl, rfl⟩ } end end end theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) : lift_rel R (append s1 s2) (append t1 t2) := ⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1, or.inr ⟨s1, t1, rfl, rfl, h1⟩, λ s t h, match s, t, h with | s, t, or.inl h := begin apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end | ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin simp [destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b, { simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl }, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, simp, exact ⟨r, or.inr ⟨s, t, h, rfl, rfl⟩⟩ } end end⟩ theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b := begin cases exists_results_of_mem ma with n h, clear ma, revert a S T, apply nat.strong_induction_on n _, intros n IH a S T ST ra, simp [destruct_join] at ra, exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra, ⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in by exact match o, p, rop, rs1, rs2, mT with | none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact ⟨none, by rw eq_of_ret_mem rs2.mem; trivial, mem_bind mT (ret_mem _)⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT := by simp [destruct_append] at rs2; exact let ⟨k1, rs3, ek⟩ := of_results_think rs2, ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3, ⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in by exact match o', p', rop', rs4, rs5, mt with | none, none, _, rs4, rs5', mt := have n1 < n, begin rw [en, ek, ek1], apply lt_of_lt_of_le _ (nat.le_add_right _ _), apply nat.lt_succ_of_le (nat.le_add_right _ _) end, let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩; { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, exact mb } | some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin simp at rs5, refine ⟨some (b, append t' (join T')), _, _⟩, { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, apply ret_mem }, rw eq_of_ret_mem rs5.mem, exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ end end end end theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) := ⟨λ s1 s2, ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin clear _fun_match _x, rw [h1, h2], rw [destruct_append, destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct st), exact λ o p h, match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp; exact ⟨h1, s, t, h2, S, rfl, T, ST, rfl⟩ | none, none, _ := begin dsimp [destruct_append.aux, computation.lift_rel], constructor, { intro, apply lift_rel_join.lem _ ST (λ _ _, id) }, { intros b mb, rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R), { rw [←lift_rel.swap R, ←lift_rel.swap], apply ST }, { rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)], exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, ⟨t, s, T, S, h2, h1, st, ST⟩ }, { exact mb } } end end end⟩ theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T := lift_rel_join _ h theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := lift_rel_join _ (lift_rel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2) @[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s := by simp [ret]; apply think_equiv @[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s := begin refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩, intros s' s h, rw ←h, apply lift_rel_rec (λ c1 c2, ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s), { exact λ c1 c2 h, match c1, c2, h with | ._, ._, ⟨s, rfl, rfl⟩ := begin clear h _match, apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret]; simp [ret], { refine ⟨_, _, ret_mem _⟩, simp }, { exact ⟨s, rfl, rfl⟩ } end end }, { exact ⟨s, rfl, rfl⟩ } end @[simp] lemma join_append (S T : wseq (wseq α)) : join (append S T) ~ append (join S) (join T) := begin refine ⟨λ s1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T, c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h in ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp, { apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp; simp, { refine ⟨s, nil, T, _, _⟩; simp }, { refine ⟨nil, nil, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { refine ⟨nil, S, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { exact ⟨s, S, T, rfl, rfl⟩ } end end end @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s := begin dsimp [bind], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], apply join_map_ret end @[simp] theorem ret_bind (a : α) (f : α → wseq β) : bind (ret a) f ~ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := begin apply seq.eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp, { exact ⟨map f s, S, rfl, rfl⟩ }, { refine ⟨nil, S, _, _⟩; simp } }, { exact ⟨_, _, rfl, rfl⟩ }, { exact ⟨_, _, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem join_join (SS : wseq (wseq (wseq α))) : join (join SS) ~ join (map join SS) := begin refine ⟨λ s1 s2, ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp, { apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp; simp, { refine ⟨nil, S, SS, _, _⟩; simp }, { refine ⟨nil, nil, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { refine ⟨nil, S, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { exact ⟨s, S, SS, rfl, rfl⟩ } end end end @[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) : bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) := begin simp [bind], rw [←map_comp f (map g), map_comp (map g ∘ f) join], apply join_join end /- Unfortunately, wseq is not a monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance : monad wseq := { map := @map, pure := @ret, bind := @bind, id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq
6d267b65843415ab4d1232dc46bde8a5bf3ce4cd
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/order/complete_lattice.lean
661c44ec5c255b91437fcefc2dfc33b96d0a0e12
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
52,531
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.bounds import data.set.bool /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded" supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ /-- Note that we rarely use `complete_semilattice_Sup` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) section variables [complete_semilattice_Sup α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) lemma le_Sup_iff : a ≤ Sup s ↔ (∀ b, (∀ x ∈ s, x ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩ theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_of_forall_le' begin simp only [Sup_le_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans hy'] end -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq end /-- Note that we rarely use `complete_semilattice_Inf` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α := (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) section variables [complete_semilattice_Inf α] {s t : set α} {a b : α} @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) lemma Inf_le_iff : Inf s ≤ a ↔ (∀ b, (∀ x ∈ s, b ≤ x) → b ≤ a) := ⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩ theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le begin simp only [le_Inf_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y,hy,hy'⟩, solve_by_elim [le_trans _ hy'] end -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq end /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj] class complete_lattice (α : Type*) extends bounded_lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α. /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Inf` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Inf`. -/ def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] : complete_lattice α := complete_lattice_of_Inf α (λ s, is_glb_Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Sup` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Sup`. -/ def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] : complete_lattice α := complete_lattice_of_Sup α (λ s, is_lub_Sup s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le (order_dual α) _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := (@is_lub_empty α _).Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := (@is_glb_univ α _).Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_insert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α} (h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, } @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := @Inf_eq_top (order_dual α) _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } /--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 `cSup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem Sup_eq_of_forall_le_of_forall_lt_exists_gt (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (Sup_le ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_Sup ‹a ∈ s›), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--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 `cInf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem Inf_eq_of_forall_ge_of_forall_gt_exists_lt (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b := @Sup_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ ‹_› ‹_› ‹_› end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := @Sup_eq_top (order_dual α) _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem le_bsupr_of_le {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) (h : a ≤ f i hi) : a ≤ ⨆ i hi, f i hi := le_trans h (le_bsupr i hi) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem bsupr_le_supr (p : ι → Prop) (f : ι → α) : (⨆ i (H : p i), f i) ≤ ⨆ i, f i := bsupr_le (λ i hi, le_supr f i) theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h theorem bsupr_le_bsupr' {p q : ι → Prop} (hpq : ∀ i, p i → q i) {f : ι → α} : (⨆ i (hpi : p i), f i) ≤ ⨆ i (hqi : q i), f i := supr_le_supr $ λ i, supr_le_supr_const (hpq i) @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem supr_lt_iff : supr s < a ↔ ∃ b < a, ∀ i, s i ≤ b := ⟨λ h, ⟨supr s, h, λ i, le_supr s i⟩, λ ⟨b, hba, hsb⟩, (supr_le hsb).trans_lt hba⟩ theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_eq_supr' {α} [has_Sup α] (s : set α) : Sup s = ⨆ x : s, (x : α) := by rw [supr, subtype.range_coe] lemma Sup_sUnion {s : set (set α)} : Sup (⋃₀ s) = ⨆ (t ∈ s), Sup t := begin apply le_antisymm, { apply Sup_le (λ b hb, _), rcases hb with ⟨t, ts, bt⟩, apply le_trans _ (le_supr _ t), exact le_trans (le_Sup bt) (le_supr _ ts), }, { apply supr_le (λ t, _), exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) } end lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma function.surjective.supr_comp {α : Type*} [has_Sup α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] lemma supr_congr {α : Type*} [has_Sup α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin have := propext pq, subst this, congr' with x, apply f end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem binfi_le_of_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) (h : f i hi ≤ a) : (⨅ i hi, f i hi) ≤ a := le_trans (binfi_le i hi) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_binfi (p : ι → Prop) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (H : p i), f i := le_binfi (λ i hi, infi_le f i) theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := @Sup_eq_supr (order_dual α) _ _ theorem Inf_eq_infi' {α} [has_Inf α] (s : set α) : Inf s = ⨅ a : s, a := @Sup_eq_supr' (order_dual α) _ _ lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := @monotone.le_map_supr2 (order_dual α) (order_dual β) _ _ _ f hf.order_dual _ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma function.surjective.infi_comp {α : Type*} [has_Inf α] {f : ι → ι₂} (hf : function.surjective f) (g : ι₂ → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp _ _ (order_dual α) _ f hf g lemma infi_congr {α : Type*} [has_Inf α] {f : ι → α} {g : ι₂ → α} (h : ι → ι₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @supr_congr _ _ (order_dual α) _ _ _ h h1 h2 @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop (order_dual α) _ p q f₁ f₂ pq f lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x := supr_le (λ _, le_rfl) lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) := le_infi (λ _, le_rfl) -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := @infi_const (order_dual α) _ _ _ _ @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := @infi_top (order_dual α) _ _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := Inf_eq_top.trans forall_range_iff @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le /--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 `csupr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem supr_eq_of_forall_le_of_forall_lt_exists_gt {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := Sup_eq_of_forall_le_of_forall_lt_exists_gt (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 `cinfi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem infi_eq_of_forall_ge_of_forall_gt_exists_lt {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @supr_eq_of_forall_le_of_forall_lt_exists_gt (order_dual α) _ _ _ ‹_› ‹_› ‹_› lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := @supr_eq_dif (order_dual α) _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := @infi_comm (order_dual α) _ _ _ _ @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := @infi_infi_eq_left (order_dual α) _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := @infi_infi_eq_right (order_dual α) _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_of_left_le $ infi_le _ _) (inf_le_of_right_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅i (h : p i), f i h) = (⨅ i (h : p i), a ⊓ f i h) := by simpa only [inf_comm] using binfi_inf h theorem supr_sup_eq {f g : ι → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq (order_dual α) ι _ _ _ lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) := @infi_inf (order_dual α) _ _ _ _ _ lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) := @inf_infi (order_dual α) _ _ _ _ _ /-! ### `supr` and `infi` under `Prop` -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le theorem infi_true {s : true → α} : infi s = s trivial := infi_pos trivial theorem supr_true {s : true → α} : supr s = s trivial := supr_pos trivial @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := @infi_exists (order_dual α) _ _ _ _ theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := @infi_and (order_dual α) _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_of_left_le $ infi_le _ _ | or.inr j := inf_le_of_right_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or (order_dual α) _ _ _ _ lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range' {α} [has_Sup α] (g : β → α) (f : ι → β) : (⨆ b : range f, g b) = ⨆ i, g (f i) := by rw [supr, supr, ← image_eq_range, ← range_comp] lemma infi_range' {α} [has_Inf α] (g : β → α) (f : ι → β) : (⨅ b : range f, g b) = ⨅ i, g (f i) := @supr_range' _ _ (order_dual α) _ _ _ lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := by rw [← infi_subtype'', infi_range'] lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := @infi_range (order_dual α) _ _ _ _ _ theorem Inf_image' {α} [has_Inf α] {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a : s, f a) := by rw [infi, image_eq_range] theorem Sup_image' {α} [has_Sup α] {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a : s, f a) := @Inf_image' _ (order_dual α) _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', Inf_image'] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := @Inf_image (order_dual α) _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := @infi_union (order_dual α) _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split (order_dual α) _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single (order_dual α) _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset (order_dual α) _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton (order_dual α) _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image (order_dual α) _ _ _ _ _ _ /-! ### `supr` and `infi` under `Type` -/ theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ := top_unique (le_infi $ assume i, (h i).elim) theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ := bot_unique (supr_le $ assume i, (h i).elim) theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ := infi_of_empty' (λ i, h ⟨i⟩) theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ := supr_of_empty' (λ i, h ⟨i⟩) @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := infi_of_empty nonempty_empty @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := supr_of_empty nonempty_empty lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := by rw [supr, bool.range_eq, Sup_pair, sup_comm] lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (order_dual α) _ _ lemma sup_eq_supr (x y : α) : x ⊔ y = ⨆ b : bool, cond b x y := by rw [supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma inf_eq_infi (x y : α) : x ⊓ y = ⨅ b : bool, cond b x y := @sup_eq_supr (order_dual α) _ _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype (order_dual α) _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma supr_subtype'' {ι} (s : set ι) (f : ι → α) : (⨆ i : s, f i) = ⨆ (t : ι) (H : t ∈ s), f t := supr_subtype lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, sigma.forall] theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_sigma (order_dual α) _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, prod.forall] theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod (order_dual α) _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff, le_infi_iff, sum.forall] theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum (order_dual α) _ _ _ _ theorem supr_option (f : option β → α) : (⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall] theorem infi_option (f : option β → α) : (⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) := @supr_option (order_dual α) _ _ _ /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw nat.sub_add_cancel hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add (order_dual α) _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le (λ i, (le_refl _).trans (le_supr _ (i + k)))) (supr_le_supr (λ i, hf (nat.le_add_right i k))) @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i), from λ n m hnm, le_infi (λ i, (infi_le _ i).trans (le_infi (λ h, infi_le _ (hnm.trans h)))), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end lemma sup_supr_nat_succ (u : ℕ → α) : u 0 ⊔ (⨆ i, u (i + 1)) = ⨆ i, u i := begin refine eq_of_forall_ge_iff (λ c, _), simp only [sup_le_iff, supr_le_iff], refine ⟨λ h, _, λ h, ⟨h _, λ i, h _⟩⟩, rintro (_|i), exacts [h.1, h.2 i] end lemma inf_infi_nat_succ (u : ℕ → α) : u 0 ⊓ (⨅ i, u (i + 1)) = ⨅ i, u i := @sup_supr_nat_succ (order_dual α) _ u end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance Prop.complete_lattice : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. Prop.bounded_distrib_lattice } @[simp] lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl @[simp] lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl @[simp] lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) @[simp] lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl @[simp] lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma unary_relation_Sup_iff {α : Type*} (s : set (α → Prop)) {a : α} : Sup s a ↔ ∃ (r : α → Prop), r ∈ s ∧ r a := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } lemma binary_relation_Sup_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} : Sup s a b ↔ ∃ (r : α → β → Prop), r ∈ s ∧ r a b := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } @[simp] lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.bounded_lattice α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ (⨅ b ∈ s, a ⊔ b) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ (⨅ b ∈ s, b ⊔ a) := le_infi $ assume i, le_infi $ assume h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h) /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := supr_le $ assume i, supr_le $ assume h, inf_le_inf_right _ (le_Sup h) lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_Sup_inf.trans (d : _)) i : _) hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr_le_iff.mp (supr_le_iff.mp (supr_inf_le_inf_Sup.trans (d : _)) i : _) hi : _) end complete_lattice namespace complete_lattice variables [complete_lattice α] /-- An independent set of elements in a complete lattice is one in which every element is disjoint from the `Sup` of the rest. -/ def set_independent (s : set α) : Prop := ∀ ⦃a⦄, a ∈ s → disjoint a (Sup (s \ {a})) variables {s : set α} (hs : set_independent s) @[simp] lemma set_independent_empty : set_independent (∅ : set α) := λ x hx, (set.not_mem_empty x hx).elim theorem set_independent.mono {t : set α} (hst : t ⊆ s) : set_independent t := λ a ha, (hs (hst ha)).mono_right (Sup_le_Sup (diff_subset_diff_left hst)) /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma set_independent.disjoint {x y : α} (hx : x ∈ s) (hy : y ∈ s) (h : x ≠ y) : disjoint x y := disjoint_Sup_right (hs hx) ((mem_diff y).mpr ⟨hy, by simp [h.symm]⟩) include hs /-- If the elements of a set are independent, then any element is disjoint from the `Sup` of some subset of the rest. -/ lemma set_independent.disjoint_Sup {x : α} {y : set α} (hx : x ∈ s) (hy : y ⊆ s) (hxy : x ∉ y) : disjoint x (Sup y) := begin have := (hs.mono $ insert_subset.mpr ⟨hx, hy⟩) (mem_insert x _), rw [insert_diff_of_mem _ (mem_singleton _), diff_singleton_eq_self hxy] at this, exact this, end omit hs /-- An independent indexed family of elements in a complete lattice is one in which every element is disjoint from the `supr` of the rest. Example: an indexed family of non-zero elements in a vector space is linearly independent iff the indexed family of subspaces they generate is independent in this sense. Example: an indexed family of submodules of a module is independent in this sense if and only the natural map from the direct sum of the submodules to the module is injective. -/ def independent {ι : Sort*} {α : Type*} [complete_lattice α] (t : ι → α) : Prop := ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) lemma set_independent_iff {α : Type*} [complete_lattice α] (s : set α) : set_independent s ↔ independent (coe : s → α) := begin simp_rw [independent, set_independent, set_coe.forall, Sup_eq_supr], apply forall_congr, intro a, apply forall_congr, intro ha, congr' 2, convert supr_subtype.symm, simp [supr_and], end variables {t : ι → α} (ht : independent t) theorem independent_def : independent t ↔ ∀ i : ι, disjoint (t i) (⨆ (j ≠ i), t j) := iff.rfl theorem independent_def' {ι : Type*} {t : ι → α} : independent t ↔ ∀ i, disjoint (t i) (Sup (t '' {j | j ≠ i})) := by {simp_rw Sup_image, refl} theorem independent_def'' {ι : Type*} {t : ι → α} : independent t ↔ ∀ i, disjoint (t i) (Sup {a | ∃ j ≠ i, t j = a}) := by {rw independent_def', tidy} @[simp] lemma independent_empty (t : empty → α) : independent t. @[simp] lemma independent_pempty (t : pempty → α) : independent t. /-- If the elements of a set are independent, then any pair within that set is disjoint. -/ lemma independent.disjoint {x y : ι} (h : x ≠ y) : disjoint (t x) (t y) := disjoint_Sup_right (ht x) ⟨y, by simp [h.symm]⟩ lemma independent.mono {ι : Type*} {α : Type*} [complete_lattice α] {s t : ι → α} (hs : independent s) (hst : t ≤ s) : independent t := λ i, (hs i).mono (hst i) (supr_le_supr $ λ j, supr_le_supr $ λ _, hst j) /-- Composing an indepedent indexed family with an injective function on the index results in another indepedendent indexed family. -/ lemma independent.comp {ι ι' : Sort*} {α : Type*} [complete_lattice α] {s : ι → α} (hs : independent s) (f : ι' → ι) (hf : function.injective f) : independent (s ∘ f) := λ i, (hs (f i)).mono_right begin refine (supr_le_supr $ λ i, _).trans (supr_comp_le _ f), exact supr_le_supr_const hf.ne, end /-- If the elements of a set are independent, then any element is disjoint from the `supr` of some subset of the rest. -/ lemma independent.disjoint_bsupr {ι : Type*} {α : Type*} [complete_lattice α] {t : ι → α} (ht : independent t) {x : ι} {y : set ι} (hx : x ∉ y) : disjoint (t x) (⨆ i ∈ y, t i) := disjoint.mono_right (bsupr_le_bsupr' $ λ i hi, (ne_of_mem_of_not_mem hi hx : _)) (ht x) end complete_lattice
9e28e2ba1a465ce1c425ceaa9f275fe6182abb89
4c630d016e43ace8c5f476a5070a471130c8a411
/category_theory/examples/topological_spaces.lean
fe99b8c457290b748b14145142c3b2bf4548284b
[ "Apache-2.0" ]
permissive
ngamt/mathlib
9a510c391694dc43eec969914e2a0e20b272d172
58909bd424209739a2214961eefaa012fb8a18d2
refs/heads/master
1,585,942,993,674
1,540,739,585,000
1,540,916,815,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,535
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Scott Morrison, Mario Carneiro import category_theory.full_subcategory import category_theory.functor_category import category_theory.natural_isomorphism import analysis.topology.topological_space import analysis.topology.continuity open category_theory open category_theory.nat_iso universe u namespace category_theory.examples /-- The category of topological spaces and continuous maps. -/ @[reducible] def Top : Type (u+1) := bundled topological_space instance (x : Top) : topological_space x := x.str namespace Top instance : concrete_category @continuous := ⟨@continuous_id, @continuous.comp⟩ -- local attribute [class] continuous -- instance {R S : Top} (f : R ⟶ S) : continuous (f : R → S) := f.2 end Top structure open_set (X : Top.{u}) : Type u := (s : set X.α) (is_open : topological_space.is_open X.str s) variables {X : Top.{u}} namespace open_set instance : has_coe (open_set X) (set X.α) := { coe := λ U, U.s } instance : has_subset (open_set X) := { subset := λ U V, U.s ⊆ V.s } instance : preorder (open_set X) := by refine { le := (⊆), .. } ; tidy instance open_sets : small_category (open_set X) := by apply_instance instance : has_mem X.α (open_set X) := { mem := λ a V, a ∈ V.s } def nbhd (x : X.α) := { U : open_set X // x ∈ U } def nbhds (x : X.α) : small_category (nbhd x) := begin unfold nbhd, apply_instance end /-- `open_set.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map {X Y : Top.{u}} (f : X ⟶ Y) : open_set Y ⥤ open_set X := { obj := λ U, ⟨ f.val ⁻¹' U.s, f.property _ U.is_open ⟩, map' := λ U V i, ⟨ ⟨ λ a b, i.down.down b ⟩ ⟩ }. @[simp] lemma map_id_obj (X : Top.{u}) (U : open_set X) : map (𝟙 X) U = U := begin cases U, tidy end @[simp] def map_id (X : Top.{u}) : map (𝟙 X) ≅ functor.id (open_set X) := { hom := { app := λ U, 𝟙 U }, inv := { app := λ U, 𝟙 U } } -- We could make f g implicit here, but it's nice to be able to see when they are the identity (often!) def map_iso {X Y : Top.{u}} (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg _ (congr_arg _ h)) _) ) (by obviously) @[simp] def map_iso_id {X : Top.{u}} (h) : map_iso (𝟙 X) (𝟙 X) h = iso.refl (map _) := rfl end open_set end category_theory.examples
18203c8b3e12fc77350570fa566fc17943fec7f3
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep_2/Tools/diagonal_sum.lean
f11f411d6542698b24c3a9814170a663afdb0e56
[]
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,438
lean
import data.fintype.basic import algebra.big_operators open_locale big_operators open_locale classical open finset universes u v variables (X : Type u)[fintype X][decidable_eq X](R : Type v) [ add_comm_group R] (Y: Type )[fintype Y][decidable_eq Y] /-- # But :: ∑ (x : X × X), ite (x.snd = x.fst) (1 : R) 0 = fintype.card X -/ def f : X → {y : X × X | y.snd = y.fst} := λ x, begin exact ⟨ (x,x), rfl ⟩ , end lemma f_ext (x : X) : (f X x).val = (x,x) := rfl def g : {y : X × X | y.snd = y.fst} → X := begin intros, rcases a, exact a_val.fst, end def G : X ≃ {y : X × X | y.snd = y.fst} := { to_fun := f X, inv_fun := g X, left_inv := begin intro, exact rfl, end, right_inv := begin intro, unfold g, unfold f, rcases x, dsimp, congr,ext, exact rfl, exact symm (x_property), end } lemma sum_diagonal_one_eq_cardinal (R : Type v) [comm_ring R] : (∑ (x : X × X), ite (x.snd = x.fst) (1 : R) 0) = fintype.card X := begin rw finset.sum_ite, rw finset.sum_const_zero,rw add_zero, rw finset.sum_const, erw add_monoid.smul_eq_mul,rw mul_one, unfold_coes, apply congr_arg nat.cast _, rw fintype.card_congr (G X), erw fintype.card_of_subtype _, intros, split, {intros,rw finset.mem_filter at a, exact a.2}, {intros, rw finset.mem_filter, split, exact finset.mem_univ x, exact a}, end
57b60e99ff83c81a9acb7de78e22a8eedd85303c
1789ef53372ad44b5ce5db2341556f91c8c31395
/src/Mermin_Peres.lean
d0bcbabbfa4c8acbb313eddda5479c486bb95c42
[]
no_license
iceplant/Mermin_Peres
d0a0f4c9f27111b3fee4e0ab5119ef1eafc59dc2
d7ea59b5767157420b0fae9dfc09f22ad2826564
refs/heads/master
1,609,583,206,767
1,582,220,678,000
1,582,220,678,000
239,577,114
1
1
null
null
null
null
UTF-8
Lean
false
false
9,769
lean
-- import init.data.nat.basic -- import init.algebra.ring -- import init.algebra.norm_num import init import tactic import data.nat.parity import data.finset import data.fintype import algebra.big_operators import data.real.basic set_option class.instance_max_depth 15000000 #eval 2 open_locale classical --open_local matrix --Alice only sees r and Bob only sees c. The strategy isn't (r,c) → (...) but two maps, r→(r1 r2 r3) and c → (c1 c2 c3) --I'm using 0 and 1 instead of Green and Red as the two options to fill squares. This makes checking parity of strategies easier --fin 3 (type = {1,2,3}) --eventually we will be interested in relative probabilities ------------METHOD 1: enumerate all the constraints as concisely as possible and reduce to show we get a contraditcion---------------------------------- --try namespace outside of def but enclosing it def checkStrategyrc (r c : ℕ) (strategy : ((ℕ → ℕ × ℕ × ℕ) × (ℕ → ℕ × ℕ × ℕ))) : Prop := --functionalize this with lists. let r1 := (strategy.1 r).1, r2 := (strategy.1 r).2.1, r3 := (strategy.1 r).2.2, c1 := (strategy.2 c).1, c2 := (strategy.2 c).2.1, c3 := (strategy.2 c).2.2 in nat.even(r1 + r2 + r3) ∧ (¬ nat.even(c1 + c2 + c3)) ∧ ((r = 1 ∧ c = 1 ∧ r1 = c1) ∨ (r = 1 ∧ c = 2 ∧ r2 = c1) ∨ (r = 1 ∧ c = 3 ∧ r3 = c1) ∨(r = 2 ∧ c = 1 ∧ r1 = c2) ∨ (r = 2 ∧ c = 2 ∧ r2 = c2) ∨ (r = 2 ∧ c = 3 ∧ r3 = c2) ∨(r = 3 ∧ c = 1 ∧ r1 = c3) ∨ (r = 3 ∧ c = 2 ∧ r2 = c3) ∨ (r = 3 ∧ c = 3 ∧ r3 = c3)) --checks all three conditions are met for the strategy def checkStrategy (strategy : ((ℕ → ℕ × ℕ × ℕ) × (ℕ → ℕ × ℕ × ℕ))) : Prop := (checkStrategyrc 1 1 strategy) ∧ (checkStrategyrc 1 2 strategy) ∧ (checkStrategyrc 1 3 strategy) ∧ (checkStrategyrc 2 1 strategy) ∧ (checkStrategyrc 2 2 strategy) ∧ (checkStrategyrc 2 3 strategy) ∧ (checkStrategyrc 3 1 strategy) ∧ (checkStrategyrc 3 2 strategy) ∧ (checkStrategyrc 3 3 strategy) --someone on Zulip said to try putting this not directly after the import statements. This seems to have helped --given a strategy, we can't have it satisfy all the conditions theorem odd_add_odd {m n} : ¬ nat.even m → ¬ nat.even n → nat.even (m + n) := sorry theorem odd_add_even {m n} : ¬ nat.even m → nat.even n → ¬ nat.even (m + n) := sorry theorem even_add_even {m n} : nat.even m → nat.even n → nat.even (m + n) := sorry theorem noStrategy2 (strategy : ((ℕ → ℕ × ℕ × ℕ) × (ℕ → ℕ × ℕ × ℕ))) : ¬ (checkStrategy (strategy)) := begin intro s, rw checkStrategy at s, repeat {rw checkStrategyrc at s}, revert s, rw (show 1 = 2 ↔ false, by norm_num), rw (show 2 = 1 ↔ false, by norm_num), rw (show 3 = 1 ↔ false, by norm_num), rw (show 1 = 3 ↔ false, by norm_num), rw (show 3 = 2 ↔ false, by norm_num), rw (show 2 = 3 ↔ false, by norm_num), repeat {simp only [false_and, false_or, and_false, or_false]}, rw (show 1=1 ↔ true, by norm_num), rw (show 2=2 ↔ true, by norm_num), rw (show 3=3 ↔ true, by norm_num), simp only [true_and, and_true, true_or, or_true], intro s, rcases s with ⟨⟨s1, t1, u1⟩, ⟨s2, t2, u2⟩, ⟨s3, t3, u3⟩, ⟨s4, t4, u4⟩, ⟨s5, t5, u5⟩, ⟨s6, t6, u6⟩, ⟨s7, t7, u7⟩, ⟨s8, t8, u8⟩, ⟨s9, t9, u9⟩⟩, -- fails rw u1 at *, rw u2 at *, rw u3 at *, rw u4 at *, rw u5 at *, rw u6 at *, rw u7 at *, rw u8 at *, rw u9 at *, apply odd_add_even t1 (odd_add_odd t2 t3), convert even_add_even s1 (even_add_even s4 s7) using 1, ring, --seems like norm_num, finish, or safe could be useful here --every case here has a false equality and-ed with something else. How do I replace them with false and reduce? --how do I tell it that we only care about the cases where r,c ∈ {1,2,3} and then do cases on those? end --------------General case: mxn where m and n are odd def checkStrategyMN {m n : nat} (strategyA : fin m → fin n → nat) (strategyB: fin n → fin m → nat) : Prop := (∀ r : fin m, (∀ c : fin n, ((finset.univ.sum (strategyA r)).even) ∧ (¬ (finset.univ.sum (strategyB c)).even) ∧ ((strategyA r c) = (strategyB c r)))) -- (∀ r : fin m, (finset.univ.sum (strategyA r)).even) ∧ (∀ c : fin n, ¬ (finset.univ.sum (strategyB c)).even) ∧ -- (∀ r : m, ∀ c : n, ((strategyA r c) = (strategyB c r))) theorem noStrategyMN {m n : nat} (strategyA : fin m → fin n → nat) (strategyB: fin n → fin m → nat) : ((¬ m.even) ∧ (¬ n.even)) → ¬ (checkStrategyMN strategyA strategyB) := begin rw checkStrategyMN, intro h, push_neg, --?????????????????????? end ----Method 2: show sampling--- #check [[1,2],[1,2,3,4],[1,2,3,4,0],[]] def board {m n : nat} (strategyA : fin m → fin n → nat) (strategyB: fin n → fin m → nat) : fin m → fin n → nat := strategyA --woah man...these representations are THE SAME!!!! (function that returns a vector and a matrix) def consistent {m n : nat} (strategyA : fin m → fin n → nat) (strategyB: fin n → fin m → nat) : Prop := ∀ (r : fin m) (c : fin n), (strategyA r c) = (strategyB c r) def sampleA {m n : nat} (board : fin m → fin n → nat) : fin m → fin n → nat := board def sampleB {m n : nat} (board : fin m → fin n → nat) : fin n → fin m → nat := λ (n : fin n) (m : fin m), board m n #check sampleA #check sampleB lemma board_equiv_strategy {m n : nat} (strategyA : fin m → fin n → nat) (strategyB: fin n → fin m → nat) : (consistent strategyA strategyB) → (strategyA = ((sampleA (board strategyA strategyB))) ∧ (strategyB = (sampleB (board strategyA strategyB)))) := begin intro h, split, rw sampleA, rw board, rw board, rw sampleB, rw consistent at h, ext i, rw h, --Logically this should work and seems pretty simple. How do I tell lean to do this??????????? end def each_row_sum_even {m n : nat} (board : fin m → fin n → nat) : Prop := ∀ (r : fin m), (finset.univ.sum (sampleA board r)).even def each_col_sum_odd {m n : nat} (board : fin m → fin n → nat) : Prop := ∀ (c : fin n), ¬(finset.univ.sum (sampleB board c)).even def even_strategy {m n : nat} (strategyA : fin m → fin n → nat) : Prop := (∀ r : fin m, ((finset.univ.sum (strategyA r)).even)) def odd_strategy {m n : nat} (strategyB : fin n → fin m → nat) : Prop := (∀ (c : fin n), ¬ (finset.univ.sum (strategyB c)).even) lemma even_strategy_implies_even_rows {m n : nat} (strategyA : fin m → fin n → nat) (strategyB : fin n → fin m → nat) : ((consistent strategyA strategyB) ∧ even_strategy strategyA) → each_row_sum_even (board strategyA strategyB) := begin rw even_strategy, rw each_row_sum_even, rw sampleA, rw board, intro h, have h := h.right, exact h, end --In order to talk about a board we need to assume the two strategies are consistent. Or else we need to define the board differently to allowfor this lemma odd_strategy_implies_odd_cols {m n : nat} (strategyA : fin m → fin n → nat) (strategyB : fin n → fin m → nat) : ((consistent strategyA strategyB) ∧ odd_strategy strategyB) → each_col_sum_odd (board strategyA strategyB) := begin intro h, cases h with h1 h2, have h3 := board_equiv_strategy strategyA strategyB h1, cases h3 with h4 h5, rw each_col_sum_odd, rw ← h5, rw odd_strategy at h2, exact h2, end --switch to mathlib matrix implementation --Posted on Zulip about this------------------- --Does this actually sum rows???????? We don't need a column one because we have our sampling function sampleB which is like a transpose def matrix_sum {m n : ℕ} (M : fin m → fin n → ℕ ) : ℕ := finset.univ.sum $ λ i, finset.univ.sum $ M i def row_sum {m n : nat} (board : fin m → fin n → nat) : nat := matrix_sum (sampleA board) def col_sum {m n : nat} (board : fin m → fin n → nat) : nat := matrix_sum (sampleB board) --how does this use sorry????? theorem sum_univ_fin_eq_sum_range (n : ℕ) (f : fin n → ℝ) : finset.sum finset.univ f = (finset.range n).sum (λ i, if hi : i < n then f ⟨i, hi⟩ else 0) := begin set F : ℕ → ℝ := λ i, if hi : i < n then f ⟨i, hi⟩ else 0 with hF, have H : f = λ (i : fin n), F (i.val), { ext i, rw hF, show f i = dite (i.val < n) (λ (hi : i.val < n), f ⟨i.val, hi⟩) (λ (hi : ¬i.val < n), 0), rw dif_pos i.is_lt, cases i, refl, }, rw H, rw ←finset.sum_image, { congr', -- ⊢ finset.image (λ (x : fin n), x.val) finset.univ = finset.range n ext j, -- sigh rw [finset.mem_range, finset.mem_image], split, rintro ⟨⟨j,hj⟩, _, rfl⟩, exact hj, intro hj, use ⟨j, hj⟩, split, apply finset.mem_univ, refl }, intros _ _ _ _, exact fin.eq_of_veq, end lemma row_sum_eq_col_sum {m n : nat} (board : fin m → fin n → nat) : row_sum board = col_sum board := begin rw row_sum, rw col_sum, rw matrix_sum, rw matrix_sum, rw sampleB, rw sampleA, have h := sum_univ_fin_eq_sum_range, sorry, -- finset.sum_comm, end theorem noStrategyMN2 {m n : nat} (strategyA : fin m → fin n → nat) (strategyB: fin n → fin m → nat) : ¬ ((consistent strategyA strategyB) ∧ (even_strategy strategyA) ∧ (odd_strategy strategyB)) := begin intro h, cases h with c y, cases y with even odd, have cEven := even, have x := even_strategy_implies_even_rows strategyA strategyB (c ∧ even), --why is this not ok??????? have y := odd_strategy_implies_odd_cols strategyA strategyB (c ∧ even), end ------------------------tests----------------- theorem myTheorem : ¬ (∀ x : nat, x = 2) := begin intro h, specialize h 0, end ------Ideas---- --use mathlib matrix representation
18c21e7cc002d583a49316cec68c17f194a0fa8f
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/group_theory/subgroup.lean
cabe0ceaaa30cd66af01340ac6a342d1a05630e5
[ "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
44,783
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import algebra.group.conj /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl -- note that `to_additive` transfers the `simp` attribute over but not the `norm_cast` attribute attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n - g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n lemma sub_mem (H : add_subgroup A) {x y : A} (hx : x ∈ H) (hy : y ∈ H) : x - y ∈ H := H.add_mem hx (H.neg_mem hy) /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def to_range (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) /-- `lift_of_surjective f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_surjective f hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] noncomputable def lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (classical.some (hf b)), map_one' := hg (classical.some_spec (hf 1)), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [classical.some_spec (hf _)], end } @[simp, to_additive] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_surjective hf g hg) (f x) = g x := begin dsimp [lift_of_surjective], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [classical.some_spec (hf _)], end @[simp, to_additive] lemma lift_of_surjective_comp (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : (f.lift_of_surjective hf g hg).comp f = g := by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] } @[to_additive] lemma eq_lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_surjective hf g hg) := begin ext b, rcases hf b with ⟨a, rfl⟩, simp only [← comp_apply, hh, f.lift_of_surjective_comp], end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset end add_subgroup namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ?
0eb2ca2d847fc2e45dca12767ba00af9bf425a74
74caf7451c921a8d5ab9c6e2b828c9d0a35aae95
/library/init/algebra/order.lean
26c7b72056e1004fae051479f69c7155c7a50a90
[ "Apache-2.0" ]
permissive
sakas--/lean
f37b6fad4fd4206f2891b89f0f8135f57921fc3f
570d9052820be1d6442a5cc58ece37397f8a9e4c
refs/heads/master
1,586,127,145,194
1,480,960,018,000
1,480,960,635,000
40,137,176
0
0
null
1,438,621,351,000
1,438,621,351,000
null
UTF-8
Lean
false
false
8,396
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u variables {α : Type u} class weak_order (α : Type u) extends has_le α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) class linear_weak_order (α : Type u) extends weak_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) class strict_order (α : Type u) extends has_lt α := (lt_irrefl : ∀ a : α, ¬ a < a) (lt_trans : ∀ a b c : α, a < b → b < c → a < c) /- structures with a weak and a strict order -/ class order_pair (α : Type u) extends weak_order α, has_lt α := (le_of_lt : ∀ a b : α, a < b → a ≤ b) (lt_of_lt_of_le : ∀ a b c : α, a < b → b ≤ c → a < c) (lt_of_le_of_lt : ∀ a b c : α, a ≤ b → b < c → a < c) (lt_irrefl : ∀ a : α, ¬ a < a) class strong_order_pair (α : Type u) extends weak_order α, has_lt α := (le_iff_lt_or_eq : ∀ a b : α, a ≤ b ↔ a < b ∨ a = b) (lt_irrefl : ∀ a : α, ¬ a < a) class linear_order_pair (α : Type u) extends order_pair α, linear_weak_order α class linear_strong_order_pair (α : Type u) extends strong_order_pair α, linear_weak_order α class decidable_linear_order (α : Type u) extends linear_strong_order_pair α := (decidable_lt : decidable_rel lt) lemma le_refl [weak_order α] : ∀ a : α, a ≤ a := weak_order.le_refl lemma le_trans [weak_order α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := weak_order.le_trans lemma le_antisymm [weak_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := weak_order.le_antisymm lemma le_of_eq [weak_order α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a lemma ge_trans [weak_order α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_weak_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_weak_order.le_total lemma le_of_not_ge [linear_weak_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma lt_irrefl [strict_order α] : ∀ a : α, ¬ a < a := strict_order.lt_irrefl lemma gt_irrefl [strict_order α] : ∀ a : α, ¬ a > a := lt_irrefl lemma lt_trans [strict_order α] : ∀ {a b c : α}, a < b → b < c → a < c := strict_order.lt_trans lemma gt_trans [strict_order α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ lemma ne_of_lt [strict_order α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [strict_order α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [strict_order α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [strict_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [order_pair α] : ∀ {a b : α}, a < b → a ≤ b := order_pair.le_of_lt lemma lt_of_lt_of_le [order_pair α] : ∀ {a b c : α}, a < b → b ≤ c → a < c := order_pair.lt_of_lt_of_le lemma lt_of_le_of_lt [order_pair α] : ∀ {a b c : α}, a ≤ b → b < c → a < c := order_pair.lt_of_le_of_lt lemma gt_of_gt_of_ge [order_pair α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ lemma gt_of_ge_of_gt [order_pair α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ instance order_pair.to_strict_order [s : order_pair α] : strict_order α := { s with lt_irrefl := order_pair.lt_irrefl, lt_trans := λ a b c h₁ h₂, lt_of_lt_of_le h₁ (le_of_lt h₂) } lemma not_le_of_gt [order_pair α] {a b : α} (h : a > b) : ¬ a ≤ b := λ h₁, lt_irrefl b (lt_of_lt_of_le h h₁) lemma not_lt_of_ge [order_pair α] {a b : α} (h : a ≥ b) : ¬ a < b := λ h₁, lt_irrefl b (lt_of_le_of_lt h h₁) lemma le_iff_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b := strong_order_pair.le_iff_lt_or_eq lemma lt_or_eq_of_le [strong_order_pair α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b := λ a b h, iff.mp le_iff_lt_or_eq h lemma le_of_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b := λ a b h, iff.mpr le_iff_lt_or_eq h lemma lt_of_le_of_ne [strong_order_pair α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, or.resolve_right (lt_or_eq_of_le h₁) h₂ private lemma lt_irrefl' [strong_order_pair α] : ∀ a : α, ¬ a < a := strong_order_pair.lt_irrefl private lemma le_of_lt' [strong_order_pair α] ⦃a b : α⦄ (h : a < b) : a ≤ b := le_of_lt_or_eq (or.inl h) private lemma lt_of_lt_of_le' [strong_order_pair α] (a b c : α) (h₁ : a < b) (h₂ : b ≤ c) : a < c := have a ≤ c, from le_trans (le_of_lt' h₁) h₂, or.elim (lt_or_eq_of_le this) (λ h : a < c, h) (λ h : a = c, have b ≤ a, from h^.symm ▸ h₂, have a = b, from le_antisymm (le_of_lt' h₁) this, absurd h₁ (this ▸ lt_irrefl' a)) private lemma lt_of_le_of_lt' [strong_order_pair α] (a b c : α) (h₁ : a ≤ b) (h₂ : b < c) : a < c := have a ≤ c, from le_trans h₁ (le_of_lt' h₂), or.elim (lt_or_eq_of_le this) (λ h : a < c, h) (λ h : a = c, have c ≤ b, from h ▸ h₁, have c = b, from le_antisymm this (le_of_lt' h₂), absurd h₂ (this ▸ lt_irrefl' c)) instance strong_order_pair.to_order_pair [s : strong_order_pair α] : order_pair α := { s with lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le'} instance linear_strong_order_pair.to_linear_order_pair [s : linear_strong_order_pair α] : linear_order_pair α := { s with lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le'} lemma lt_trichotomy [linear_strong_order_pair α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h^.symm))) lemma le_of_not_gt [linear_strong_order_pair α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_strong_order_pair α] {a b : α} (h : ¬ a ≥ b) : a < b := match lt_trichotomy a b with | or.inl hlt := hlt | or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h | or.inr (or.inr hgt) := absurd (le_of_lt hgt) h end lemma lt_or_ge [linear_strong_order_pair α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_strong_order_pair α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_strong_order_pair α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt α a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := if h₁ : a < b then is_true (le_of_lt h₁) else if h₂ : b < a then is_false (not_le_of_gt h₂) else is_true (le_of_not_gt h₂) instance [decidable_linear_order α] (a b : α) : decidable (a = b) := if h₁ : a ≤ b then if h₂ : b ≤ a then is_true (le_antisymm h₁ h₂) else is_false (λ he : a = b, h₂ (he ▸ le_refl a)) else is_false (λ he : a = b, h₁ (he ▸ le_refl a)) lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁)))
177485bc5bbeab3a26260cc04382c2c799591a91
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/array_test.lean
84e3221c8d973888454ea3a69814535961e37fd4
[ "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
1,237
lean
def foo (a : Array Nat) : Array Nat := let a := a.push 0 let a := a.push 1 let a := a.push 2 let a := a.push 3 a def main : IO UInt32 := do let a : Array Nat := Array.empty IO.println (toString a) IO.println (toString a.size) let a := foo a IO.println (toString a) let a := a.map (fun a => a + 10) IO.println (toString a) IO.println (toString a.size) let a1 := a.pop let a2 := a.push 100 IO.println (toString a1) IO.println (toString a2) let a2 := a.pop IO.println a2 IO.println $ (([1, 2, 3, 4].toArray).map (fun a => a + 2)).map toString IO.println $ ([1, 2, 3, 4].toArray.extract 1 3) IO.println $ ([1, 2, 3, 4].toArray.extract 0 100) IO.println $ ([1, 2, 3, 4].toArray.extract 1 1) IO.println $ ([1, 2, 3, 4].toArray.extract 2 4) IO.println [1,2,3,4].toArray.reverse IO.println ([] : List Nat).toArray.reverse IO.println [1,2,3].toArray.reverse IO.println $ [1,2,3,4].toArray.filter (fun a => a % 2 == 0) IO.println $ [1,2,3,4,5].toArray.filter (fun a => a % 2 == 0) IO.println $ [1,2,3,4,5].toArray.filter (fun a => a % 2 == 1) IO.println $ [1,2,3,4].toArray.filter (fun a => a > 2) IO.println $ [1,2,3,4].toArray.filter (fun a => a > 10) IO.println $ [1,2,3,4].toArray.filter (fun a => a > 0) pure 0
e4392745212c8b315085e195eee4366ab6328958
36938939954e91f23dec66a02728db08a7acfcf9
/lean/deps/galois_stdlib/src/galois/data/bool.lean
23e31f1a488400803143a9765db0ad19e9bac566
[ "Apache-2.0" ]
permissive
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
376
lean
-- Boolean operations. /- Implication over Booleans. -/ def bimplies : bool → bool → bool | tt y := y | ff _ := tt /- Return conjunction of all elements in list. -/ def ball : list bool → bool | [] := tt | (tt::r) := ball r | (ff::r) := ff /- Return disjunction of all elements in list. -/ def bany : list bool → bool | [] := ff | (tt::r) := tt | (ff::r) := bany r
3d4a61d2ede1f5fc639b75c0a27dab842c39648e
ec62863c729b7eedee77b86d974f2c529fa79d25
/9/a.lean
091d66beb320213071289a161ef3e0557de818f8
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
495
lean
def bufSize : Nat := 25 def isPairSum (xs : List Int) (y : Int) : Bool := do for x₁ in xs do for x₂ in xs do if x₁ ≠ x₂ && x₁ + x₂ == y then return true return false def firstBad (xs : List Int) : Int := do let mut old := xs.take bufSize for x in xs.drop bufSize do if ! isPairSum old x then return x old := old.drop 1 ++ [x] panic! "no solution" def main : IO Unit := do let input ← IO.FS.lines "a.in" IO.print s!"{firstBad (input.toList.map String.toInt!)}\n"
391536e2c6f7265022093b48b123992f93d29bd9
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/System/IO.lean
1919b54d671e99313764269afbf72e9868396f9e
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
24,913
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Control.EState import Init.Control.Reader import Init.Data.String import Init.Data.ByteArray import Init.System.IOError import Init.System.FilePath import Init.System.ST import Init.Data.ToString.Macro import Init.Data.Ord open System /-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld. Makes sure we never reorder `IO` operations. TODO: mark opaque -/ def IO.RealWorld : Type := Unit /- TODO(Leo): mark it as an opaque definition. Reason: prevent functions defined in other modules from accessing `IO.RealWorld`. We don't want action such as ``` def getWorld : IO (IO.RealWorld) := get ``` -/ def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld instance : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld)) instance : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld)) instance : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld)) instance : OrElse (EIO ε α) := ⟨MonadExcept.orElse⟩ instance [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α)) /-- An `EIO` monad that cannot throw exceptions. -/ def BaseIO := EIO Empty instance : Monad BaseIO := inferInstanceAs (Monad (EIO Empty)) instance : MonadFinally BaseIO := inferInstanceAs (MonadFinally (EIO Empty)) @[inline] def BaseIO.toEIO (act : BaseIO α) : EIO ε α := fun s => match act s with | EStateM.Result.ok a s => EStateM.Result.ok a s instance : MonadLift BaseIO (EIO ε) := ⟨BaseIO.toEIO⟩ @[inline] def EIO.toBaseIO (act : EIO ε α) : BaseIO (Except ε α) := fun s => match act s with | EStateM.Result.ok a s => EStateM.Result.ok (Except.ok a) s | EStateM.Result.error ex s => EStateM.Result.ok (Except.error ex) s @[inline] def EIO.catchExceptions (act : EIO ε α) (h : ε → BaseIO α) : BaseIO α := fun s => match act s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex s => h ex s open IO (Error) in abbrev IO : Type → Type := EIO Error @[inline] def BaseIO.toIO (act : BaseIO α) : IO α := act @[inline] def EIO.toIO (f : ε → IO.Error) (act : EIO ε α) : IO α := act.adaptExcept f @[inline] def EIO.toIO' (act : EIO ε α) : IO (Except ε α) := act.toBaseIO @[inline] def IO.toEIO (f : IO.Error → ε) (act : IO α) : EIO ε α := act.adaptExcept f /- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()` represents the "initial world". We don't want to cache this closed term. So, we disable the "extract closed terms" optimization. -/ set_option compiler.extract_closed false in @[inline] unsafe def unsafeBaseIO (fn : BaseIO α) : α := match fn.run () with | EStateM.Result.ok a _ => a @[inline] unsafe def unsafeEIO (fn : EIO ε α) : Except ε α := unsafeBaseIO fn.toBaseIO @[inline] unsafe def unsafeIO (fn : IO α) : Except IO.Error α := unsafeEIO fn @[extern "lean_io_timeit"] opaque timeit (msg : @& String) (fn : IO α) : IO α @[extern "lean_io_allocprof"] opaque allocprof (msg : @& String) (fn : IO α) : IO α /-- Programs can execute IO actions during initialization that occurs before the `main` function is executed. The attribute `[init <action>]` specifies which IO action is executed to set the value of an opaque constant. The action `initializing` returns `true` iff it is invoked during initialization. -/ @[extern "lean_io_initializing"] opaque IO.initializing : BaseIO Bool namespace BaseIO /-- Run `act` in a separate `Task`. This is similar to Haskell's [`unsafeInterleaveIO`](http://hackage.haskell.org/package/base-4.14.0.0/docs/System-IO-Unsafe.html#v:unsafeInterleaveIO), except that the `Task` is started eagerly as usual. Thus pure accesses to the `Task` do not influence the impure `act` computation. Unlike with pure tasks created by `Task.spawn`, tasks created by this function will be run even if the last reference to the task is dropped. The `act` should manually check for cancellation via `IO.checkCanceled` if it wants to react to that. -/ @[extern "lean_io_as_task"] opaque asTask (act : BaseIO α) (prio := Task.Priority.default) : BaseIO (Task α) := Task.pure <$> act /-- See `BaseIO.asTask`. -/ @[extern "lean_io_map_task"] opaque mapTask (f : α → BaseIO β) (t : Task α) (prio := Task.Priority.default) : BaseIO (Task β) := Task.pure <$> f t.get /-- See `BaseIO.asTask`. -/ @[extern "lean_io_bind_task"] opaque bindTask (t : Task α) (f : α → BaseIO (Task β)) (prio := Task.Priority.default) : BaseIO (Task β) := f t.get def mapTasks (f : List α → BaseIO β) (tasks : List (Task α)) (prio := Task.Priority.default) : BaseIO (Task β) := go tasks [] where go | t::ts, as => BaseIO.bindTask t (fun a => go ts (a :: as)) prio | [], as => f as.reverse |>.asTask prio end BaseIO namespace EIO /-- `EIO` specialization of `BaseIO.asTask`. -/ @[inline] def asTask (act : EIO ε α) (prio := Task.Priority.default) : BaseIO (Task (Except ε α)) := act.toBaseIO.asTask prio /-- `EIO` specialization of `BaseIO.mapTask`. -/ @[inline] def mapTask (f : α → EIO ε β) (t : Task α) (prio := Task.Priority.default) : BaseIO (Task (Except ε β)) := BaseIO.mapTask (fun a => f a |>.toBaseIO) t prio /-- `EIO` specialization of `BaseIO.bindTask`. -/ @[inline] def bindTask (t : Task α) (f : α → EIO ε (Task (Except ε β))) (prio := Task.Priority.default) : BaseIO (Task (Except ε β)) := BaseIO.bindTask t (fun a => f a |>.catchExceptions fun e => return Task.pure <| Except.error e) prio /-- `EIO` specialization of `BaseIO.mapTasks`. -/ @[inline] def mapTasks (f : List α → EIO ε β) (tasks : List (Task α)) (prio := Task.Priority.default) : BaseIO (Task (Except ε β)) := BaseIO.mapTasks (fun as => f as |>.toBaseIO) tasks prio end EIO namespace IO def ofExcept [ToString ε] (e : Except ε α) : IO α := match e with | Except.ok a => pure a | Except.error e => throw (IO.userError (toString e)) def lazyPure (fn : Unit → α) : IO α := pure (fn ()) /-- Monotonically increasing time since an unspecified past point in milliseconds. No relation to wall clock time. -/ @[extern "lean_io_mono_ms_now"] opaque monoMsNow : BaseIO Nat /-- Monotonically increasing time since an unspecified past point in nanoseconds. No relation to wall clock time. -/ @[extern "lean_io_mono_nanos_now"] opaque monoNanosNow : BaseIO Nat /-- Read bytes from a system entropy source. Not guaranteed to be cryptographically secure. If `nBytes = 0`, return immediately with an empty buffer. -/ @[extern "lean_io_get_random_bytes"] opaque getRandomBytes (nBytes : USize) : IO ByteArray def sleep (ms : UInt32) : IO Unit := -- TODO: add a proper primitive for IO.sleep fun s => dbgSleep ms fun _ => EStateM.Result.ok () s /-- `IO` specialization of `EIO.asTask`. -/ @[inline] def asTask (act : IO α) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error α)) := EIO.asTask act prio /-- `IO` specialization of `EIO.mapTask`. -/ @[inline] def mapTask (f : α → IO β) (t : Task α) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error β)) := EIO.mapTask f t prio /-- `IO` specialization of `EIO.bindTask`. -/ @[inline] def bindTask (t : Task α) (f : α → IO (Task (Except IO.Error β))) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error β)) := EIO.bindTask t f prio /-- `IO` specialization of `EIO.mapTasks`. -/ @[inline] def mapTasks (f : List α → IO β) (tasks : List (Task α)) (prio := Task.Priority.default) : BaseIO (Task (Except IO.Error β)) := EIO.mapTasks f tasks prio /-- Check if the task's cancellation flag has been set by calling `IO.cancel` or dropping the last reference to the task. -/ @[extern "lean_io_check_canceled"] opaque checkCanceled : BaseIO Bool /-- Request cooperative cancellation of the task. The task must explicitly call `IO.checkCanceled` to react to the cancellation. -/ @[extern "lean_io_cancel"] opaque cancel : @& Task α → BaseIO Unit /-- Check if the task has finished execution, at which point calling `Task.get` will return immediately. -/ @[extern "lean_io_has_finished"] opaque hasFinished : @& Task α → BaseIO Bool /-- Wait for the task to finish, then return its result. -/ @[extern "lean_io_wait"] opaque wait (t : Task α) : BaseIO α := return t.get /-- Wait until any of the tasks in the given list has finished, then return its result. -/ @[extern "lean_io_wait_any"] opaque waitAny : @& List (Task α) → IO α /-- Helper method for implementing "deterministic" timeouts. It is the number of "small" memory allocations performed by the current execution thread. -/ @[extern "lean_io_get_num_heartbeats"] opaque getNumHeartbeats : BaseIO Nat inductive FS.Mode where | read | write | readWrite | append opaque FS.Handle : Type := Unit /-- A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can capture output of `#eval` commands into memory. -/ structure FS.Stream where isEof : IO Bool flush : IO Unit read : USize → IO ByteArray write : ByteArray → IO Unit getLine : IO String putStr : String → IO Unit deriving Inhabited open FS @[extern "lean_get_stdin"] opaque getStdin : BaseIO FS.Stream @[extern "lean_get_stdout"] opaque getStdout : BaseIO FS.Stream @[extern "lean_get_stderr"] opaque getStderr : BaseIO FS.Stream /-- Replaces the stdin stream of the current thread and returns its previous value. -/ @[extern "lean_get_set_stdin"] opaque setStdin : FS.Stream → BaseIO FS.Stream /-- Replaces the stdout stream of the current thread and returns its previous value. -/ @[extern "lean_get_set_stdout"] opaque setStdout : FS.Stream → BaseIO FS.Stream /-- Replaces the stderr stream of the current thread and returns its previous value. -/ @[extern "lean_get_set_stderr"] opaque setStderr : FS.Stream → BaseIO FS.Stream @[specialize] partial def iterate (a : α) (f : α → IO (Sum α β)) : IO β := do let v ← f a match v with | Sum.inl a => iterate a f | Sum.inr b => pure b namespace FS namespace Handle private def fopenFlags (m : FS.Mode) (b : Bool) : String := let mode := match m with | FS.Mode.read => "r" | FS.Mode.write => "w" | FS.Mode.readWrite => "r+" | FS.Mode.append => "a" ; let bin := if b then "b" else "t" mode ++ bin @[extern "lean_io_prim_handle_mk"] opaque mkPrim (fn : @& FilePath) (mode : @& String) : IO Handle def mk (fn : FilePath) (Mode : Mode) (bin : Bool := true) : IO Handle := mkPrim fn (fopenFlags Mode bin) /-- Returns whether the end of the file has been reached while reading a file. `h.isEof` returns true /after/ the first attempt at reading past the end of `h`. Once `h.isEof` is true, reading `h` will always return an empty array. -/ @[extern "lean_io_prim_handle_is_eof"] opaque isEof (h : @& Handle) : BaseIO Bool @[extern "lean_io_prim_handle_flush"] opaque flush (h : @& Handle) : IO Unit @[extern "lean_io_prim_handle_read"] opaque read (h : @& Handle) (bytes : USize) : IO ByteArray @[extern "lean_io_prim_handle_write"] opaque write (h : @& Handle) (buffer : @& ByteArray) : IO Unit @[extern "lean_io_prim_handle_get_line"] opaque getLine (h : @& Handle) : IO String @[extern "lean_io_prim_handle_put_str"] opaque putStr (h : @& Handle) (s : @& String) : IO Unit end Handle @[extern "lean_io_realpath"] opaque realPath (fname : FilePath) : IO FilePath @[extern "lean_io_remove_file"] opaque removeFile (fname : @& FilePath) : IO Unit /-- Remove given directory. Fails if not empty; see also `IO.FS.removeDirAll`. -/ @[extern "lean_io_remove_dir"] opaque removeDir : @& FilePath → IO Unit @[extern "lean_io_create_dir"] opaque createDir : @& FilePath → IO Unit end FS @[extern "lean_io_getenv"] opaque getEnv (var : @& String) : BaseIO (Option String) @[extern "lean_io_app_path"] opaque appPath : IO FilePath @[extern "lean_io_current_dir"] opaque currentDir : IO FilePath namespace FS @[inline] def withFile (fn : FilePath) (mode : Mode) (f : Handle → IO α) : IO α := Handle.mk fn mode >>= f def Handle.putStrLn (h : Handle) (s : String) : IO Unit := h.putStr (s.push '\n') partial def Handle.readBinToEnd (h : Handle) : IO ByteArray := do let rec loop (acc : ByteArray) : IO ByteArray := do let buf ← h.read 1024 if buf.isEmpty then return acc else loop (acc ++ buf) loop ByteArray.empty partial def Handle.readToEnd (h : Handle) : IO String := do let rec loop (s : String) := do let line ← h.getLine if line.isEmpty then return s else loop (s ++ line) loop "" def readBinFile (fname : FilePath) : IO ByteArray := do let h ← Handle.mk fname Mode.read true h.readBinToEnd def readFile (fname : FilePath) : IO String := do let h ← Handle.mk fname Mode.read false h.readToEnd partial def lines (fname : FilePath) : IO (Array String) := do let h ← Handle.mk fname Mode.read false let rec read (lines : Array String) := do let line ← h.getLine if line.length == 0 then pure lines else if line.back == '\n' then let line := line.dropRight 1 let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line read <| lines.push line else pure <| lines.push line read #[] def writeBinFile (fname : FilePath) (content : ByteArray) : IO Unit := do let h ← Handle.mk fname Mode.write true h.write content def writeFile (fname : FilePath) (content : String) : IO Unit := do let h ← Handle.mk fname Mode.write false h.putStr content def Stream.putStrLn (strm : FS.Stream) (s : String) : IO Unit := strm.putStr (s.push '\n') structure DirEntry where root : FilePath fileName : String deriving Repr def DirEntry.path (entry : DirEntry) : FilePath := entry.root / entry.fileName inductive FileType where | dir | file | symlink | other deriving Repr, BEq structure SystemTime where sec : Int nsec : UInt32 deriving Repr, BEq, Ord, Inhabited instance : LT SystemTime := ltOfOrd instance : LE SystemTime := leOfOrd structure Metadata where --permissions : ... accessed : SystemTime modified : SystemTime byteSize : UInt64 type : FileType deriving Repr end FS end IO namespace System.FilePath open IO @[extern "lean_io_read_dir"] opaque readDir : @& FilePath → IO (Array IO.FS.DirEntry) @[extern "lean_io_metadata"] opaque metadata : @& FilePath → IO IO.FS.Metadata def isDir (p : FilePath) : BaseIO Bool := do match (← p.metadata.toBaseIO) with | Except.ok m => return m.type == IO.FS.FileType.dir | Except.error _ => return false def pathExists (p : FilePath) : BaseIO Bool := return (← p.metadata.toBaseIO).toBool /-- Return all filesystem entries of a preorder traversal of all directories satisfying `enter`, starting at `p`. Symbolic links are visited as well by default. -/ partial def walkDir (p : FilePath) (enter : FilePath → IO Bool := fun _ => pure true) : IO (Array FilePath) := Prod.snd <$> StateT.run (go p) #[] where go p := do if !(← enter p) then return () for d in (← p.readDir) do modify (·.push d.path) let m ← d.path.metadata match m.type with | FS.FileType.symlink => let p' ← FS.realPath d.path if (← p'.isDir) then -- do not call `enter` on a non-directory symlink if (← enter p) then go p' | FS.FileType.dir => go d.path | _ => pure () end System.FilePath namespace IO def withStdin [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStdin h try x finally discard <| setStdin prev def withStdout [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStdout h try x finally discard <| setStdout prev def withStderr [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (h : FS.Stream) (x : m α) : m α := do let prev ← setStderr h try x finally discard <| setStderr prev def print [ToString α] (s : α) : IO Unit := do let out ← getStdout out.putStr <| toString s def println [ToString α] (s : α) : IO Unit := print ((toString s).push '\n') def eprint [ToString α] (s : α) : IO Unit := do let out ← getStderr out.putStr <| toString s def eprintln [ToString α] (s : α) : IO Unit := eprint <| toString s |>.push '\n' @[export lean_io_eprint] private def eprintAux (s : String) : IO Unit := eprint s @[export lean_io_eprintln] private def eprintlnAux (s : String) : IO Unit := eprintln s def appDir : IO FilePath := do let p ← appPath let some p ← pure p.parent | throw <| IO.userError s!"System.IO.appDir: unexpected filename '{p}'" FS.realPath p /-- Create given path and all missing parents as directories. -/ partial def FS.createDirAll (p : FilePath) : IO Unit := do if ← p.isDir then return () if let some parent := p.parent then createDirAll parent try createDir p catch | e => if ← p.isDir then pure () -- I guess someone else was faster else throw e /-- Fully remove given directory by deleting all contained files and directories in an unspecified order. Fails if any contained entry cannot be deleted or was newly created during execution. -/ partial def FS.removeDirAll (p : FilePath) : IO Unit := do for ent in (← p.readDir) do if (← ent.path.isDir : Bool) then removeDirAll ent.path else removeFile ent.path removeDir p namespace Process inductive Stdio where | piped | inherit | null def Stdio.toHandleType : Stdio → Type | Stdio.piped => FS.Handle | Stdio.inherit => Unit | Stdio.null => Unit structure StdioConfig where /-- Configuration for the process' stdin handle. -/ stdin := Stdio.inherit /-- Configuration for the process' stdout handle. -/ stdout := Stdio.inherit /-- Configuration for the process' stderr handle. -/ stderr := Stdio.inherit structure SpawnArgs extends StdioConfig where /-- Command name. -/ cmd : String /-- Arguments for the process -/ args : Array String := #[] /-- Working directory for the process. Inherit from current process if `none`. -/ cwd : Option FilePath := none /-- Add or remove environment variables for the process. -/ env : Array (String × Option String) := #[] -- TODO(Sebastian): constructor must be private structure Child (cfg : StdioConfig) where stdin : cfg.stdin.toHandleType stdout : cfg.stdout.toHandleType stderr : cfg.stderr.toHandleType @[extern "lean_io_process_spawn"] opaque spawn (args : SpawnArgs) : IO (Child args.toStdioConfig) @[extern "lean_io_process_child_wait"] opaque Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32 /-- Extract the `stdin` field from a `Child` object, allowing them to be freed independently. This operation is necessary for closing the child process' stdin while still holding on to a process handle, e.g. for `Child.wait`. A file handle is closed when all references to it are dropped, which without this operation includes the `Child` object. -/ @[extern "lean_io_process_child_take_stdin"] opaque Child.takeStdin {cfg : @& StdioConfig} : Child cfg → IO (cfg.stdin.toHandleType × Child { cfg with stdin := Stdio.null }) structure Output where exitCode : UInt32 stdout : String stderr : String /-- Run process to completion and capture output. -/ def output (args : SpawnArgs) : IO Output := do let child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped } let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated let stderr ← child.stderr.readToEnd let exitCode ← child.wait let stdout ← IO.ofExcept stdout.get pure { exitCode := exitCode, stdout := stdout, stderr := stderr } /-- Run process to completion and return stdout on success. -/ def run (args : SpawnArgs) : IO String := do let out ← output args if out.exitCode != 0 then throw <| IO.userError <| "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode pure out.stdout @[extern "lean_io_exit"] opaque exit : UInt8 → IO α end Process structure AccessRight where read : Bool := false write : Bool := false execution : Bool := false def AccessRight.flags (acc : AccessRight) : UInt32 := let r : UInt32 := if acc.read then 0x4 else 0 let w : UInt32 := if acc.write then 0x2 else 0 let x : UInt32 := if acc.execution then 0x1 else 0 r.lor <| w.lor x structure FileRight where user : AccessRight := {} group : AccessRight := {} other : AccessRight := {} def FileRight.flags (acc : FileRight) : UInt32 := let u : UInt32 := acc.user.flags.shiftLeft 6 let g : UInt32 := acc.group.flags.shiftLeft 3 let o : UInt32 := acc.other.flags u.lor <| g.lor o @[extern "lean_chmod"] opaque Prim.setAccessRights (filename : @& FilePath) (mode : UInt32) : IO Unit def setAccessRights (filename : FilePath) (mode : FileRight) : IO Unit := Prim.setAccessRights filename mode.flags /-- References -/ abbrev Ref (α : Type) := ST.Ref IO.RealWorld α instance : MonadLift (ST IO.RealWorld) BaseIO := ⟨id⟩ def mkRef (a : α) : BaseIO (IO.Ref α) := ST.mkRef a namespace FS namespace Stream @[export lean_stream_of_handle] def ofHandle (h : Handle) : Stream := { isEof := Handle.isEof h, flush := Handle.flush h, read := Handle.read h, write := Handle.write h, getLine := Handle.getLine h, putStr := Handle.putStr h, } structure Buffer where data : ByteArray := ByteArray.empty pos : Nat := 0 def ofBuffer (r : Ref Buffer) : Stream := { isEof := do let b ← r.get; pure <| b.pos >= b.data.size, flush := pure (), read := fun n => r.modifyGet fun b => let data := b.data.extract b.pos (b.pos + n.toNat) (data, { b with pos := b.pos + data.size }), write := fun data => r.modify fun b => -- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, getLine := r.modifyGet fun b => let pos := match b.data.findIdx? (start := b.pos) fun u => u == 0 || u = '\n'.toNat.toUInt8 with -- include '\n', but not '\0' | some pos => if b.data.get! pos == 0 then pos else pos + 1 | none => b.data.size (String.fromUTF8Unchecked <| b.data.extract b.pos pos, { b with pos := pos }), putStr := fun s => r.modify fun b => let data := s.toUTF8 { b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size }, } end Stream /-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/ def withIsolatedStreams [Monad m] [MonadFinally m] [MonadLiftT BaseIO m] (x : m α) (isolateStderr := true) : m (String × α) := do let bIn ← mkRef { : Stream.Buffer } let bOut ← mkRef { : Stream.Buffer } let r ← withStdin (Stream.ofBuffer bIn) <| withStdout (Stream.ofBuffer bOut) <| (if isolateStderr then withStderr (Stream.ofBuffer bOut) else id) <| x let bOut ← liftM (m := BaseIO) bOut.get let out := String.fromUTF8Unchecked bOut.data pure (out, r) end FS end IO universe u namespace Lean /-- Typeclass used for presenting the output of an `#eval` command. -/ class Eval (α : Type u) where -- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval` -- so that `()` output is hidden in chained instances such as for some `IO Unit`. -- We take `Unit → α` instead of `α` because ‵α` may contain effectful debugging primitives (e.g., `dbg_trace`) eval : (Unit → α) → (hideUnit : Bool := true) → IO Unit instance [ToString α] : Eval α where eval a _ := IO.println (toString (a ())) instance [Repr α] : Eval α where eval a _ := IO.println (repr (a ())) instance : Eval Unit where eval u hideUnit := if hideUnit then pure () else IO.println (repr (u ())) instance [Eval α] : Eval (IO α) where eval x _ := do let a ← x () Eval.eval fun _ => a @[noinline, nospecialize] def runEval [Eval α] (a : Unit → α) : IO (String × Except IO.Error Unit) := IO.FS.withIsolatedStreams (Eval.eval a false |>.toBaseIO) end Lean syntax "println! " (interpolatedStr(term) <|> term) : term macro_rules | `(println! $msg:interpolatedStr) => `((IO.println (s! $msg) : IO Unit)) | `(println! $msg:term) => `((IO.println $msg : IO Unit))
2d72a3dbc5aae17c41c79d4c7ddf1f5d52892234
b82c5bb4c3b618c23ba67764bc3e93f4999a1a39
/src/formal_ml/measurable_space.lean
53e965a9b17c71c70d08d0b465facff1870c1f3a
[ "Apache-2.0" ]
permissive
nouretienne/formal-ml
83c4261016955bf9bcb55bd32b4f2621b44163e0
40b6da3b6e875f47412d50c7cd97936cb5091a2b
refs/heads/master
1,671,216,448,724
1,600,472,285,000
1,600,472,285,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,215
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import measure_theory.measurable_space import measure_theory.measure_space import formal_ml.set import formal_ml.finset import formal_ml.classical lemma set_Prop_le_def {α:Type*} (M M2:set α → Prop): M ≤ M2 ↔ (∀ X:set α, M X → M2 X) := begin refl, end lemma finset_union_measurable {α:Type*} {T:finset α} {β:Type*} [measurable_space β] {U:α → set β}: (∀ t∈ T, is_measurable (U t)) → is_measurable (⋃ x ∈ T, U x) := begin intros, have A1:(set.sUnion (set.image U ({a|a∈ T}:set α))) = (⋃ x ∈ T, U x), { simp, }, rw ← A1, apply is_measurable.sUnion, { apply set.countable.image, apply set.finite.countable, apply finite_finset, }, { intros, simp at H, cases H with x H, cases H with A2 A3, subst t, apply a, exact A2, } end lemma finset_inter_measurable {α:Type*} {T:finset α} {β:Type*} [measurable_space β] {U:α → set β}: (∀ t∈ T, is_measurable (U t)) → is_measurable (⋂ x ∈ T, U x) := begin intros, have A1:(set.sInter (set.image U ({a|a∈ T}:set α))) = (⋂ x ∈ T, U x), { simp, }, rw ← A1, apply is_measurable.sInter, { apply set.countable.image, apply set.finite.countable, apply finite_finset, }, { intros, simp at H, cases H with x H, cases H with A2 A3, subst t, apply a, exact A2, } end lemma measurable_space_le_def {α:Type*} (M:measurable_space α) (M2:measurable_space α): M.is_measurable ≤ M2.is_measurable ↔ M ≤ M2 := begin refl, end lemma measurable_space_le_def2 {α:Type*} (M:measurable_space α) (M2:measurable_space α): (∀ X:set α, M.is_measurable X → M2.is_measurable X) ↔ M ≤ M2 := begin intros, apply iff.trans, { apply set_Prop_le_def, }, { apply measurable_space_le_def, } end -- Delete? lemma measurable_space_le_intro {α:Type*} (M:measurable_space α) (M2:measurable_space α): (∀ X:set α, M.is_measurable X → M2.is_measurable X) → M ≤ M2 := begin intros, have A1:M.is_measurable ≤ M2.is_measurable ↔ M ≤ M2, { apply measurable_space_le_def, }, apply A1.mp, have A2:M.is_measurable ≤ M2.is_measurable ↔ (∀ X:set α, M.is_measurable X → M2.is_measurable X), { apply set_Prop_le_def, }, apply A2.mpr, apply a, end lemma measurable_def {α β:Type*} [M1:measurable_space α] [M2:measurable_space β] (f:α → β): (∀ B:(set β), (is_measurable B) → is_measurable (f ⁻¹' B)) ↔ (measurable f) := begin unfold measurable, end lemma measurable_intro {α β:Type*} [measurable_space α] [measurable_space β] (f:α → β): (∀ B:(set β), is_measurable B → is_measurable (f ⁻¹' B)) → (measurable f) := begin apply (measurable_def _).mp, end lemma measurable_elim {α β:Type*} [measurable_space α] [measurable_space β] (f:α → β) (B:set β): (measurable f)→ (is_measurable B) → (is_measurable (f ⁻¹' B)) := begin intros, apply (measurable_def _).mpr, apply a, apply a_1, end lemma measurable_fun_product_measurableh {α β:Type*} [M1:measurable_space α] [M2:measurable_space β]: (@prod.measurable_space α β M1 M2) = M1.comap prod.fst ⊔ M2.comap prod.snd := begin refl end lemma comap_elim {α β:Type*} [M2:measurable_space β] (f:α → β) (B:set β): (is_measurable B) → (M2.comap f).is_measurable (set.preimage f B) := begin intros, unfold measurable_space.comap, simp, apply exists.intro B, split, apply a, refl end lemma measurable_comap {α β:Type*} [M1:measurable_space α] [M2:measurable_space β] (f:α → β): (M2.comap f) ≤ M1 → measurable f := begin intros, apply measurable_intro, intros, have A1:(M2.comap f).is_measurable (set.preimage f B), { apply comap_elim, apply a_1, }, rw ← measurable_space_le_def2 at a, apply a, apply A1, end lemma fst_measurable {α β:Type*} [M1:measurable_space α] [M2:measurable_space β]:measurable (λ x:(α × β), x.fst) := begin apply measurable_comap, have A1:M1.comap prod.fst ≤ (@prod.measurable_space α β M1 M2), { rw measurable_fun_product_measurableh, apply complete_lattice.le_sup_left (M1.comap prod.fst) (M2.comap prod.snd), }, apply A1, end lemma snd_measurable {α β:Type*} [M1:measurable_space α] [M2:measurable_space β]:measurable (λ x:(α × β), x.snd) := begin apply measurable_comap, have A1:M2.comap prod.snd ≤ (@prod.measurable_space α β M1 M2), { rw measurable_fun_product_measurableh, apply complete_lattice.le_sup_right (M1.comap prod.fst) (M2.comap prod.snd), }, apply A1, end lemma comap_def {α β:Type*} {B:set (set β)} (f:α → β): @measurable_space.comap α β f (measurable_space.generate_from B) = (measurable_space.generate_from (set.image (set.preimage f) B)) := begin apply measurable_space.comap_generate_from, end lemma comap_fst_def {α β:Type*} {Bα:set (set α)}: (measurable_space.generate_from Bα).comap (@prod.fst α β) = measurable_space.generate_from {U:set (α × β)|∃ A∈ Bα, U = set.prod A set.univ} := begin rw measurable_space.comap_generate_from, rw set.preimage_fst_def, end lemma comap_snd_def {α β:Type*} {Bβ:set (set β)}: (measurable_space.generate_from Bβ).comap (@prod.snd α β) = measurable_space.generate_from {U:set (α × β)|∃ B∈ Bβ, U = set.prod set.univ B} := begin rw measurable_space.comap_generate_from, rw set.preimage_snd_def, end lemma measurable_space_sup_def {α:Type*} {B C:set (set α)}: (measurable_space.generate_from B) ⊔ (measurable_space.generate_from C) = (measurable_space.generate_from (B ∪ C)) := begin apply measurable_space.generate_from_sup_generate_from, end lemma prod_measurable_space_def {α β:Type*} {Bα:set (set α)} {Bβ:set (set β)}: (@prod.measurable_space α β (measurable_space.generate_from Bα) (measurable_space.generate_from Bβ)) = @measurable_space.generate_from (α × β) ( {U:set (α × β)|∃ A∈ Bα, U = set.prod A set.univ} ∪ {U:set (α × β)|∃ B∈ Bβ, U = set.prod set.univ B}) := begin rw measurable_fun_product_measurableh, rw comap_fst_def, rw comap_snd_def, rw measurable_space_sup_def, end lemma set.sUnion_eq_univ_elim {α:Type*} {S:set (set α)} (a:α): (set.sUnion S = set.univ) → (∃ T∈S, a∈ T) := begin intro A1, have A2:a∈ set.univ := set.mem_univ a, rw ← A1 at A2, simp at A2, cases A2 with T A2, apply exists.intro T, apply exists.intro A2.left, apply A2.right, end lemma prod_measurable_space_le {α β:Type*} {Bα:set (set α)} {Bβ:set (set β)}: @measurable_space.generate_from (α × β) {U:set (α × β)|∃ A∈ Bα, ∃ B∈Bβ, U = set.prod A B} ≤ (@prod.measurable_space α β (measurable_space.generate_from Bα) (measurable_space.generate_from Bβ)) := begin rw prod_measurable_space_def, apply measurable_space.generate_from_le, intros X A5, simp at A5, cases A5 with A A5, cases A5 with A5 A6, cases A6 with B A6, cases A6 with A6 A7, have A8:(set.prod A (@set.univ β)) ∩ (set.prod (@set.univ α) B) = set.prod A B, { ext p,split;intros A3A;{ simp at A3A, simp, --cases p, apply A3A, }, }, rw ← A8 at A7, rw A7, apply is_measurable.inter, { apply measurable_space.is_measurable_generate_from, apply set.mem_union_left, simp, apply exists.intro A, split, apply A5, refl, }, { apply measurable_space.is_measurable_generate_from, apply set.mem_union_right, simp, apply exists.intro B, split, apply A6, refl, }, end lemma prod_measurable_space_def2 {α β:Type*} {Bα:set (set α)} {Bβ:set (set β)} {Cα:set (set α)} {Cβ:set (set β)}: (set.countable Cα) → (set.countable Cβ) → (Cα ⊆ Bα) → (Cβ ⊆ Bβ) → (set.sUnion Cα = set.univ) → (set.sUnion Cβ = set.univ) → (@prod.measurable_space α β (measurable_space.generate_from Bα) (measurable_space.generate_from Bβ)) = @measurable_space.generate_from (α × β) {U:set (α × β)|∃ A∈ Bα, ∃ B∈Bβ, U = set.prod A B} := begin intros A1 A2 A3 A4 AX1 AX2, --rw prod_measurable_space_def, apply le_antisymm, { rw prod_measurable_space_def, apply measurable_space.generate_from_le, intros X A5, simp at A5, cases A5, { cases A5 with A A5, cases A5 with A5 A6, have A7:X = set.sUnion (set.image (set.prod A) Cβ), { rw A6, ext a,split;intro A7A;simp;simp at A7A, { have A7B := set.sUnion_eq_univ_elim a.snd AX2, cases A7B with i A7B, cases A7B with A7B A7C, apply exists.intro i, apply and.intro A7B (and.intro A7A A7C), }, { cases A7A with i A7A, apply A7A.right.left, }, }, rw A7, --apply measurable_space.is_measurable_generate_from, apply is_measurable.sUnion, apply set.countable.image, apply A2, intro U, intro A8, simp at A8, cases A8 with B A8, cases A8 with A8 A9, subst U, apply measurable_space.is_measurable_generate_from, simp, apply exists.intro A, split, apply A5, apply exists.intro B, split, rw set.subset_def at A4, apply A4, apply A8, refl, }, { cases A5 with B A5, cases A5 with A5 A6, have A7:X = set.sUnion (set.image (λ x, set.prod x B) Cα), { rw A6, ext a,split;intro A7A;simp;simp at A7A, { have A7B := set.sUnion_eq_univ_elim a.fst AX1, cases A7B with i A7B, cases A7B with A7B A7C, apply exists.intro i, apply and.intro A7B (and.intro A7C A7A), }, { cases A7A with i A7A, apply A7A.right.right, }, }, rw A7, --apply measurable_space.is_measurable_generate_from, apply is_measurable.sUnion, apply set.countable.image, apply A1, intro U, intro A8, simp at A8, cases A8 with A A8, cases A8 with A8 A9, subst U, apply measurable_space.is_measurable_generate_from, simp, apply exists.intro A, split, rw set.subset_def at A3, apply A3, apply A8, apply exists.intro B, split, apply A5, refl, }, }, { apply prod_measurable_space_le, } end lemma preimage_compl {α β:Type*} (f:α → β) (S:set β): (f ⁻¹' Sᶜ) = ((f ⁻¹' S)ᶜ) := begin ext, split;intros, { intro, unfold set.preimage at a, simp at a, apply a, apply a_1, }, { unfold set.preimage, simp, intro, apply a, apply a_1, } end lemma preimage_Union {α β:Type*} (f:α → β) (g:ℕ → set β): (f ⁻¹' ⋃ (i : ℕ), g i)=(⋃ (i : ℕ), f ⁻¹' (g i)) := begin ext, split;intros, { cases a with B a, cases a with H a, cases H with y H, split, simp, split, apply exists.intro y, { simp at H, }, { simp at H, subst B, apply a, } }, { cases a with A a, cases a with A1 A2, cases A1 with i A3, simp at A3, subst A, split, simp, split, { apply exists.intro i, refl, }, { apply A2, }, } end lemma generate_from_measurable {α β:Type*} [M:measurable_space α] [M2:measurable_space β] (X:set (set β)) (f:α → β): (measurable_space.generate_from X = M2)→ (∀ B∈ X, is_measurable (set.preimage f B))→ (measurable f) := begin intros, apply measurable_intro, intros, have A1:@is_measurable β (measurable_space.generate_from X) B, { rw a, apply a_2, }, clear a_2, -- Important for induction later. have A2:measurable_space.generate_measurable X B, { apply A1, }, induction A2, { apply a_1, apply A2_H, }, { simp, }, { -- ⊢ is_measurable (f ⁻¹' -A2_s) rw preimage_compl, apply measurable_space.is_measurable_compl, apply A2_ih, { apply (is_measurable.compl_iff).mp, apply A1, }, }, { rw preimage_Union, apply measurable_space.is_measurable_Union, intros, apply A2_ih, { apply A2_a, } } end lemma generate_from_self {α:Type*} (M:measurable_space α): M = measurable_space.generate_from {s : set α|measurable_space.is_measurable M s} := begin ext, split;intros, { apply measurable_space.generate_measurable.basic, apply a, }, { induction a, { apply a_H, }, { apply measurable_space.is_measurable_empty, }, { apply measurable_space.is_measurable_compl, apply a_ih, }, { apply measurable_space.is_measurable_Union, apply a_ih, }, } end lemma measurable_fun_comap_def {α β:Type*} [M2:measurable_space β] (f:α → β): measurable_space.comap f M2 = measurable_space.generate_from {s : set α|∃ (s' : set β), measurable_space.is_measurable M2 s' ∧ f ⁻¹' s' = s} := begin unfold measurable_space.comap, apply generate_from_self, end lemma measurable_fun_product_measurable {α β γ:Type*} [M1:measurable_space α] [M2:measurable_space β] [M3:measurable_space γ] (X: α → β) (Y: α → γ): measurable X → measurable Y → measurable (λ a:α, prod.mk (X a) (Y a)) := begin intros B1 B2, have A1:@measurable _ _ _ (@prod.measurable_space β γ M2 M3) (λ a:α, prod.mk (X a) (Y a)), { have A1A:(@prod.measurable_space β γ M2 M3)=measurable_space.generate_from ( {s : set (β × γ) | ∃ (s' : set β), measurable_space.is_measurable M2 s' ∧ prod.fst ⁻¹' s' = s} ∪ {s : set (β × γ) | ∃ (s' : set γ), measurable_space.is_measurable M3 s' ∧ prod.snd ⁻¹' s' = s}), { rw measurable_fun_product_measurableh, rw measurable_fun_comap_def, rw measurable_fun_comap_def, rw measurable_space.generate_from_sup_generate_from, }, rw A1A, apply generate_from_measurable, { refl, }, { intro BC, intros, cases H, { cases H with B H, cases H, subst BC, have A1B:(λ (a : α), (X a, Y a)) ⁻¹' (prod.fst ⁻¹' B) = (X ⁻¹' B), { ext,split;intros, { simp at a, apply a, }, { simp, apply a, } }, rw A1B, apply B1, apply H_left, }, { cases H with C H, cases H, subst BC, have A1C:(λ (a : α), (X a, Y a)) ⁻¹' (prod.snd ⁻¹' C) = (Y ⁻¹' C), { ext,split;intros, { simp at a, apply a, }, { simp, apply a, } }, rw A1C, apply B2, apply H_left, } } }, apply A1, end lemma compose_measurable_fun_measurable {α β γ:Type*} [measurable_space α] [measurable_space β] [measurable_space γ] (X:β → γ) (Y: α→ β): measurable X → measurable Y → measurable (X ∘ Y) := begin intros B1 B2, apply measurable_intro, intros, have A1:(X ∘ Y ⁻¹' B)=(Y ⁻¹' (X ⁻¹' B)), { refl, }, rw A1, apply measurable_elim Y _ B2, apply measurable_elim X _ B1, apply a end -- Constant functions are measurable. -- Different than is_measurable.const lemma const_measurable {Ω:Type*} [measurable_space Ω] {β:Type*} [measurable_space β] (c:β): (measurable (λ ω:Ω, c)) := begin apply measurable_const, end lemma is_measurable_of_le_of_is_measurable {α : Type*} {M1 : measurable_space α} {M2 : measurable_space α} {X:set α}: M1 ≤ M2 → measurable_space.is_measurable M1 X → measurable_space.is_measurable M2 X := begin intros A2 A1, rw ← measurable_space_le_def2 at A2, apply A2, apply A1, end -- cf. is_measurable_prod lemma is_measurable_prod' {β : Type*} {γ : Type*} {Mβ : measurable_space β} {Mγ : measurable_space γ} {X:set β} {Y:set γ}:is_measurable X → is_measurable Y → is_measurable (set.prod X Y) := begin --apply is_measurable_of_le_of_is_measurable, intros A1 A2, rw generate_from_self Mβ, rw generate_from_self Mγ, apply is_measurable_of_le_of_is_measurable, apply prod_measurable_space_le, apply measurable_space.is_measurable_generate_from, simp, apply exists.intro X, split, apply A1, apply exists.intro Y, split, apply A2, refl, end lemma measurable.preimage {α β:Type*} [measurable_space α] [measurable_space β] {f:α → β} {S:set β}:measurable f → is_measurable S → is_measurable (set.preimage f S) := begin intros A1 A2, apply A1, apply A2, end lemma measurable.if {α β:Type*} {Mα:measurable_space α} {Mβ:measurable_space β} {E:set α} {D:decidable_pred E} {X Y:α → β}:is_measurable E → measurable X → measurable Y → measurable (λ a:α, if (E a) then (X a) else (Y a)) := begin intros A1 A2 A3, intros S B1, rw preimage_if, apply is_measurable.union, { apply is_measurable.inter, apply A1, apply A2, apply B1, }, { apply is_measurable.inter, apply is_measurable.compl, apply A1, apply A3, apply B1, }, end
56c051256388003d4991a19bc24ff35956c63c64
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/resolveGlobalName.lean
4218a786dc76372f60210370f716af8c97fcf90b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
590
lean
import Lean def Boo.x := 1 def Foo.x := 2 def Foo.x.y := 3 def Bla.x := 4 namespace Test export Bla (x) end Test open Lean open Lean.Elab.Term open Lean.Elab.Command syntax (name := resolveKind) "#resolve " ident : command @[commandElab resolveKind] def elabResolve : CommandElab := fun stx => liftTermElabM none do let cs ← resolveGlobalName $ stx.getIdAt 1; Lean.Elab.logInfo $ toString cs; pure () #resolve x.y #resolve x open Foo #resolve x #resolve x.y #resolve x.z.w open Boo #resolve x #resolve x.y #resolve x.z.w open Test #resolve x #resolve x.w.h.r #resolve x.y
adaff992af569f71e5ddc8169a7f107e5463ff31
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Data/HashMap.lean
99b1de34d5ae0550f28472c6c053ff3a6d835512
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
9,308
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Data.AssocList namespace Lean def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size.isPowerOfTwo } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.size_set]; apply data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) where size : Nat buckets : HashMapBucket α β private def numBucketsForCapacity (capacity : Nat) : Nat := -- a "load factor" of 0.75 is the usual standard for hash maps capacity * 4 / 3 def mkHashMapImp {α : Type u} {β : Type v} (capacity := 8) : HashMapImp α β := { size := 0 buckets := ⟨mkArray (numBucketsForCapacity capacity).nextPowerOfTwo AssocList.nil, by simp; apply Nat.isPowerOfTwo_nextPowerOfTwo⟩ } namespace HashMapImp variable {α : Type u} {β : Type v} /- Remark: we use a C implementation because this function is performance critical. -/ @[extern c inline "(size_t)(#2) & (lean_unbox(#1) - 1)"] private def mkIdx {sz : Nat} (hash : UInt64) (h : sz.isPowerOfTwo) : { u : USize // u.toNat < sz } := -- TODO: avoid `if` in the reference implementation let u := hash.toUSize &&& (sz.toUSize - 1) if h' : u.toNat < sz then ⟨u, h'⟩ else ⟨0, by simp [USize.toNat, OfNat.ofNat, USize.ofNat, Fin.ofNat']; rw [Nat.zero_mod]; apply Nat.pos_of_isPowerOfTwo h⟩ @[inline] def reinsertAux (hashFn : α → UInt64) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx (hashFn a) data.property data.update i (AssocList.cons a b data.val[i]) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f @[inline] def forBucketsM {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (f : α → β → m PUnit) : m PUnit := data.val.forM fun b => b.forM f @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMapImp α β) : m PUnit := forBucketsM h.buckets f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property buckets.val[i].findEntry? a def find? [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property buckets.val[i].find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property buckets.val[i].contains a def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target termination_by _ i source _ => source.size - i def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let bucketsNew : HashMapBucket α β := ⟨ mkArray (buckets.val.size * 2) AssocList.nil, by simp; apply Nat.mul2_isPowerOfTwo_of_isPowerOfTwo buckets.property ⟩ { size := size, buckets := moveEntries 0 buckets.val bucketsNew } @[inline] def insert [beq : BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β × Bool := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property let bkt := buckets.val[i] if bkt.contains a then (⟨size, buckets.update i (bkt.replace a b) h⟩, true) else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if numBucketsForCapacity size' ≤ buckets.val.size then ({ size := size', buckets := buckets' }, false) else (expand size' buckets', false) def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx (hash a) buckets.property let bkt := buckets.val[i] if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop where | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b |>.1) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Lean.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (capacity := 8) : HashMap α β := ⟨ mkHashMapImp capacity, WellFormed.mkWff capacity ⟩ namespace HashMap instance [BEq α] [Hashable α] : Inhabited (HashMap α β) where default := mkHashMap instance [BEq α] [Hashable α] : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def empty [BEq α] [Hashable α] : HashMap α β := mkHashMap variable {α : Type u} {β : Type v} {_ : BEq α} {_ : Hashable α} def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => match h:m.insert a b with | (m', _) => ⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩ /-- Similar to `insert`, but also returns a Boolean flad indicating whether an existing entry has been replaced with `a -> b`. -/ def insert' (m : HashMap α β) (a : α) (b : β) : HashMap α β × Bool := match m with | ⟨ m, hw ⟩ => match h:m.insert a b with | (m', replaced) => (⟨ m', by have aux := WellFormed.insertWff m a b hw; rw [h] at aux; assumption ⟩, replaced) @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" instance : GetElem (HashMap α β) α (Option β) fun _ _ => True where getElem m k _ := m.find? k @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def forM {m : Type w → Type w} [Monad m] (f : α → β → m PUnit) (h : HashMap α β) : m PUnit := match h with | ⟨ h, _ ⟩ => h.forM f @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size /-- Builds a `HashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. -/ def ofList (l : List (α × β)) : HashMap α β := l.foldl (init := HashMap.empty) (fun m p => m.insert p.fst p.snd) /-- Variant of `ofList` which accepts a function that combines values of duplicated keys. -/ def ofListWith (l : List (α × β)) (f : β → β → β) : HashMap α β := l.foldl (init := HashMap.empty) (fun m p => match m.find? p.fst with | none => m.insert p.fst p.snd | some v => m.insert p.fst $ f v p.snd)
18327d5d3c23566cbb20b47b4f0cb9e8456cf533
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Data/Lsp/LanguageFeatures.lean
efc12a85cc5cf9c6e4d46fc70ec4e0175a821d37
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
5,699
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic namespace Lean namespace Lsp open Json structure CompletionOptions where triggerCharacters? : Option (Array String) := none allCommitCharacters? : Option (Array String) := none resolveProvider : Bool := false deriving FromJson, ToJson structure CompletionItem where label : String detail? : Option String documentation? : Option MarkupContent /- kind? : CompletionItemKind tags? : CompletionItemTag[] deprecated? : boolean preselect? : boolean sortText? : string filterText? : string insertText? : string insertTextFormat? : InsertTextFormat insertTextMode? : InsertTextMode textEdit? : TextEdit | InsertReplaceEdit additionalTextEdits? : TextEdit[] commitCharacters? : string[] command? : Command data? : any -/ deriving FromJson, ToJson, Inhabited structure CompletionList where isIncomplete : Bool items : Array CompletionItem deriving FromJson, ToJson structure CompletionParams extends TextDocumentPositionParams where -- context? : CompletionContext deriving FromJson, ToJson structure Hover where /- NOTE we should also accept MarkedString/MarkedString[] here but they are deprecated, so maybe can get away without. -/ contents : MarkupContent range? : Option Range := none deriving ToJson, FromJson structure HoverParams extends TextDocumentPositionParams deriving FromJson, ToJson structure DeclarationParams extends TextDocumentPositionParams deriving FromJson, ToJson structure DefinitionParams extends TextDocumentPositionParams deriving FromJson, ToJson structure TypeDefinitionParams extends TextDocumentPositionParams deriving FromJson, ToJson structure DocumentHighlightParams extends TextDocumentPositionParams deriving FromJson, ToJson inductive DocumentHighlightKind where | text | read | write instance : ToJson DocumentHighlightKind where toJson | DocumentHighlightKind.text => 1 | DocumentHighlightKind.read => 2 | DocumentHighlightKind.write => 3 structure DocumentHighlight where range : Range kind? : Option DocumentHighlightKind := none deriving ToJson abbrev DocumentHighlightResult := Array DocumentHighlight structure DocumentSymbolParams where textDocument : TextDocumentIdentifier deriving FromJson, ToJson inductive SymbolKind where | file | module | «namespace» | package | «class» | method | property | field | constructor | enum | interface | function | «variable» | «constant» | string | number | boolean | array | object | key | null | enumMember | struct | event | operator | typeParameter instance : ToJson SymbolKind where toJson | SymbolKind.file => 1 | SymbolKind.module => 2 | SymbolKind.namespace => 3 | SymbolKind.package => 4 | SymbolKind.class => 5 | SymbolKind.method => 6 | SymbolKind.property => 7 | SymbolKind.field => 8 | SymbolKind.constructor => 9 | SymbolKind.enum => 10 | SymbolKind.interface => 11 | SymbolKind.function => 12 | SymbolKind.variable => 13 | SymbolKind.constant => 14 | SymbolKind.string => 15 | SymbolKind.number => 16 | SymbolKind.boolean => 17 | SymbolKind.array => 18 | SymbolKind.object => 19 | SymbolKind.key => 20 | SymbolKind.null => 21 | SymbolKind.enumMember => 22 | SymbolKind.struct => 23 | SymbolKind.event => 24 | SymbolKind.operator => 25 | SymbolKind.typeParameter => 26 structure DocumentSymbolAux (Self : Type) where name : String detail? : Option String := none kind : SymbolKind -- tags? : Array SymbolTag range : Range selectionRange : Range children? : Option (Array Self) := none deriving ToJson inductive DocumentSymbol where | mk (sym : DocumentSymbolAux DocumentSymbol) partial instance : ToJson DocumentSymbol where toJson := let rec go | DocumentSymbol.mk sym => have ToJson DocumentSymbol := ⟨go⟩ toJson sym go structure DocumentSymbolResult where syms : Array DocumentSymbol instance : ToJson DocumentSymbolResult where toJson dsr := toJson dsr.syms inductive SemanticTokenType where | keyword | «variable» | property /- | «namespace» | type | «class» | enum | interface | struct | typeParameter | parameter | enumMember | event | function | method | «macro» | modifier | comment | string | number | regexp | operator -/ def SemanticTokenType.names : Array String := #["keyword", "variable", "property"] -- must be the correct index in `names` def SemanticTokenType.toNat : SemanticTokenType → Nat | keyword => 0 | «variable» => 1 | property => 2 /- inductive SemanticTokenModifier where | declaration | definition | readonly | static | deprecated | abstract | async | modification | documentation | defaultLibrary -/ structure SemanticTokensLegend where tokenTypes : Array String tokenModifiers : Array String deriving FromJson, ToJson structure SemanticTokensOptions where legend : SemanticTokensLegend range : Bool full : Bool /- | { delta?: boolean; } -/ deriving FromJson, ToJson structure SemanticTokensParams where textDocument : TextDocumentIdentifier deriving FromJson, ToJson structure SemanticTokensRangeParams where textDocument : TextDocumentIdentifier range : Range deriving FromJson, ToJson structure SemanticTokens where -- resultId?: string; data : Array Nat deriving FromJson, ToJson end Lsp end Lean
f0b20f47fefe3def00a88e5fa910fe664b81c527
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/hash_map.lean
604e8f0e096459e8384eb4c3083ba265d04b9339
[ "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
27,893
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, Mario Carneiro -/ import data.pnat.basic import data.list.range import data.array.lemmas import algebra.group import data.sigma.basic universes u v w /-- `bucket_array α β` is the underlying data type for `hash_map α β`, an array of linked lists of key-value pairs. -/ def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) := array n (list Σ a, β a) /-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/ def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n := ⟨i % n, nat.mod_lt _ n.2⟩ namespace bucket_array section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) variables {n : ℕ+} (data : bucket_array α β n) instance : inhabited (bucket_array α β n) := ⟨mk_array _ []⟩ /-- Read the bucket corresponding to an element -/ def read (a : α) : list Σ a, β a := let bidx := hash_map.mk_idx n (hash_fn a) in data.read bidx /-- Write the bucket corresponding to an element -/ def write (a : α) (l : list Σ a, β a) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in data.write bidx l /-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/ def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in array.write data bidx (f (array.read data bidx)) /-- The list of all key-value pairs in the bucket list -/ def as_list : list Σ a, β a := data.to_list.join theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i := have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔ ∃ (i : fin (n.val)), a ∈ array.read data i, by rw exists_swap; exact exists_congr (λ i, by simp), by simp [as_list]; simpa [array.mem.def, and_comm] /-- Fold a function `f` over the key-value pairs in the bucket list -/ def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ := data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d) theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d := by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl] end end bucket_array namespace hash_map section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) /-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array (without checking for duplication) -/ def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n := data.modify hash_fn a (λl, ⟨a, b⟩ :: l) theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n [] : bucket_array α β n) = [] := list.eq_nil_iff_forall_not_mem.mpr $ λ x m, let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h parameter [decidable_eq α] /-- Search a bucket for a key `a` and return the value -/ def find_aux (a : α) : list (Σ a, β a) → option (β a) | [] := none | (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l) | [] nd := ⟨λn, by injection n, false.elim⟩ | (⟨a',b'⟩::t) nd := begin by_cases a' = a, { clear find_aux_iff, subst h, suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]}, refine (or_iff_left_of_imp (λ m, _)).symm, have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd, exact this.elim (list.mem_map_of_mem sigma.fst m) }, { have : sigma.mk a b ≠ ⟨a', b'⟩, { intro e, injection e with e, exact h e.symm }, simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] } end /-- Returns `tt` if the bucket `l` contains the key `a` -/ def contains_aux (a : α) (l : list Σ a, β a) : bool := (find_aux a l).is_some theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst := begin unfold contains_aux, cases h : find_aux a l with b; simp, { assume (b : β a) (m : sigma.mk a b ∈ l), rw (find_aux_iff nd).2 m at h, contradiction }, { show ∃ (b : β a), sigma.mk a b ∈ l, exact ⟨_, (find_aux_iff nd).1 h⟩ }, end /-- Modify a bucket to replace a value in the list. Leaves the list unchanged if the key is not found. -/ def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t /-- Modify a bucket to remove a key, if it exists. -/ def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t /-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map` invariants: There are exactly `sz` elements in it, every pair is in the bucket determined by its key and the hash function, and no key appears multiple times in the list. -/ structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop := (len : bkts.as_list.length = sz) (idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i → mk_idx n (hash_fn a.1) = i) (nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup) theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : ∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ := (array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl) theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : (mk_idx n (hash_fn a)).1 = i := let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup := begin suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint, { simp [bucket_array.as_list, list.nodup_join, this], change ∀ l s, array.mem s bkts → list.map sigma.fst s = l → l.nodup, introv m e, subst e, cases m with i e, subst e, apply v.nodup }, rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map], have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range], refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this), rw prod.forall, intros i l₁, rw prod.forall, intros j l₂ me₁ me₂ ij, simp [list.disjoint], intros a b ml₁ b' ml₂, apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂] end theorem mk_valid (n : ℕ+) : @valid n (mk_array n []) 0 := ⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩ theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} : find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list := (find_aux_iff (v.nodup _)).trans $ by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩ theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) : contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst := by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn] section parameters {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin n} {f : list (Σ a, β a) → list (Σ a, β a)} (u v1 v2 w : list Σ a, β a) local notation `L` := array.read bkts bidx private def bkts' : bucket_array α β n := array.write bkts bidx (f L) variables (hl : L = u ++ v1 ++ w) (hfl : f L = u ++ v2 ++ w) include hl hfl theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' := begin unfold bucket_array.as_list, have h : (bidx : ℕ) < bkts.to_list.length, { simp only [bidx.is_lt, array.to_list_length] }, refine ⟨(bkts.to_list.take bidx).join ++ u, w ++ (bkts.to_list.drop (bidx+1)).join, _, _⟩, { conv { to_lhs, rw [← list.take_append_drop bidx bkts.to_list, list.drop_eq_nth_le_cons h], simp [hl] }, simp }, { conv { to_lhs, rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h], simp [hfl] }, simp } end variables (hvnd : (v2.map sigma.fst).nodup) (hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx) (djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst)) (djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst)) include hvnd hal djuv djwv theorem valid.modify {sz : ℕ} (v : valid bkts sz) : v1.length ≤ sz + v2.length ∧ valid bkts' (sz + v2.length - v1.length) := begin rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩, rw [← v.len, e₁], suffices : valid bkts' (u' ++ v2 ++ w').length, { simpa [ge, add_comm, add_left_comm, nat.le_add_right, nat.add_sub_cancel_left] }, refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.idx _ _ _ v bidx a, simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢, exact ⟨⟨this.1.1, hal _⟩, this.2⟩ }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } }, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.nodup _ _ _ v bidx, simp [hl, list.nodup_append] at this, simp [list.nodup_append, this, hvnd, djuv, djwv.symm] }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } } end end theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', suffices : ∃ (u w : list Σ a, β a) (b'' : β a), (sigma.mk a b') :: t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa}, refine ⟨[], t, b', _⟩, simp [replace_aux] }, { suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), (sigma.mk a' b') :: t = u ++ ⟨a, b''⟩ :: w ∧ (sigma.mk a' b') :: (replace_aux a b t) = u ++ ⟨a, b⟩ :: w, { simpa [replace_aux, ne.symm e, e] }, intros x m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w, { simpa using valid.replace_aux t }, rcases IH x m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ } end theorem valid.replace {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩, simp [hl, list.nodup_append] at nd, refine (v.modify hash_fn u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa' e1 e2, _) (λa' e1 e2, _)).2; { revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] } end theorem valid.insert {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hnc : ¬ contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), refine (v.modify hash_fn [] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa', false.elim) (λa' e1 e2, _)).2, simp [-sigma.exists] at e2, subst a', exact Hnc ((contains_aux_iff nd).2 e1) end theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', simpa [erase_aux, and_comm] using show ∃ u w (x : β a), t = u ++ w ∧ (sigma.mk a b') :: t = u ++ ⟨a, x⟩ :: w, from ⟨[], t, b', by simp⟩ }, { simp [erase_aux, e, ne.symm e], suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a), (sigma.mk a' b') :: t = u ++ ⟨a, x⟩ :: w ∧ (sigma.mk a' b') :: (erase_aux a t) = u ++ w, { simpa [replace_aux, ne.symm e, e] }, intros b m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a), t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w, { simpa using valid.erase_aux t }, rcases IH b m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ } end theorem valid.erase {n} {bkts : bucket_array α β n} {sz} (a : α) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩, refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2; simp end end end hash_map /-- A hash map data structure, representing a finite key-value map with key type `α` and value type `β` (which may depend on `α`). -/ structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) := (hash_fn : α → nat) (size : ℕ) (nbuckets : ℕ+) (buckets : bucket_array α β nbuckets) (is_valid : hash_map.valid hash_fn buckets size) /-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/ def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β := let n := if nbuckets = 0 then 8 else nbuckets in let nz : n > 0 := by abstract { cases nbuckets; simp [if_pos, nat.succ_ne_zero] } in { hash_fn := hash_fn, size := 0, nbuckets := ⟨n, nz⟩, buckets := mk_array n [], is_valid := hash_map.mk_valid _ _ } namespace hash_map variables {α : Type u} {β : α → Type v} [decidable_eq α] /-- Return the value corresponding to a key, or `none` if not found -/ def find (m : hash_map α β) (a : α) : option (β a) := find_aux a (m.buckets.read m.hash_fn a) /-- Return `tt` if the key exists in the map -/ def contains (m : hash_map α β) (a : α) : bool := (m.find a).is_some instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩ /-- Fold a function over the key-value pairs in the map -/ def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ := m.buckets.foldl d f /-- The list of key-value pairs in the map -/ def entries (m : hash_map α β) : list Σ a, β a := m.buckets.as_list /-- The list of keys in the map -/ def keys (m : hash_map α β) : list α := m.entries.map sigma.fst theorem find_iff (m : hash_map α β) (a : α) (b : β a) : m.find a = some b ↔ sigma.mk a b ∈ m.entries := m.is_valid.find_aux_iff _ theorem contains_iff (m : hash_map α β) (a : α) : m.contains a ↔ a ∈ m.keys := m.is_valid.contains_aux_iff _ _ theorem entries_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).entries = [] := mk_as_list _ theorem keys_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).keys = [] := by dsimp [keys]; rw entries_empty; refl theorem find_empty (hash_fn : α → nat) (n a) : (@mk_hash_map α _ β hash_fn n).find a = none := by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl, { have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }] theorem not_contains_empty (hash_fn : α → nat) (n a) : ¬ (@mk_hash_map α _ β hash_fn n).contains a := by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl theorem insert_lemma (hash_fn : α → nat) {n n'} {bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) : valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz := begin suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz, valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup → valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length), { have p := this bkts.as_list _ _ (mk_valid _ _), rw [mk_as_list, list.append_nil, zero_add, v.len] at p, rw bucket_array.foldl_eq, exact p (v.as_list_nodup _) }, intro l, induction l with c l IH; intros t sz v nd, {exact v}, rw show sz + (c :: l).length = sz + 1 + l.length, by simp [add_comm, add_assoc], rcases (show (l.map sigma.fst).nodup ∧ ((bucket_array.as_list t).map sigma.fst).nodup ∧ c.fst ∉ l.map sigma.fst ∧ c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧ (l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst), by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd) with ⟨nd1, nd2, nm1, nm2, dj⟩, have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc), apply IH _ _ v', suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l → ∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false, { simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] }, intros a b m1 b' m2, rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩, have : sigma.mk a b' ∉ array.read t i, { intro m3, have : a ∈ list.map sigma.fst t.as_list := list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩), exact dj (list.mem_map_of_mem sigma.fst m1) this }, by_cases h : mk_idx n' (hash_fn c.1) = i, { subst h, have e : sigma.mk a b' = ⟨c.1, c.2⟩, { simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im }, injection e with e, subst a, exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) }, { apply this, simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im } end /-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/ def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β | ⟨hash_fn, size, n, buckets, v⟩ a b := let bkt := buckets.read hash_fn a in if hc : contains_aux a bkt then { hash_fn := hash_fn, size := size, nbuckets := n, buckets := buckets.modify hash_fn a (replace_aux a b), is_valid := v.replace _ a b hc } else let size' := size + 1, buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l), valid' := v.insert _ a b hc in if size' ≤ n then { hash_fn := hash_fn, size := size', nbuckets := n, buckets := buckets', is_valid := valid' } else let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩, buckets'' : bucket_array α β n' := buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in { hash_fn := hash_fn, size := size', nbuckets := n', buckets := buckets'', is_valid := insert_lemma _ valid' } theorem mem_insert : Π (m : hash_map α β) (a b a' b'), (sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔ if a = a' then b == b' else sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin let bkt := bkts.read hash_fn a, have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)), have lem : Π (bkts' : bucket_array α β n) (v1 u w) (hl : bucket_array.as_list bkts = u ++ v1 ++ w) (hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w) (veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]), sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, { intros bkts' v1 u w hl hfl veq, rw [hl, hfl], by_cases h : a = a', { subst a', suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b', { simpa [eq_comm, or.left_comm] }, refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _), rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩, { have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc, simp [hl, not_or_distrib] at na, simp [na] }, { have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] } }, { suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]}, rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } }, by_cases Hc : (contains_aux a bkt : Prop), { rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩, rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩, simpa [insert, @dif_pos (contains_aux a bkt) _ Hc] using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) }, { let size' := size + 1, let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l), have mi : sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list := let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩, simp [insert, @dif_neg (contains_aux a bkt) _ Hc], by_cases h : size' ≤ n, -- TODO(Mario): Why does the by_cases assumption look different than the stated one? { simpa [show size' ≤ n, from h] using mi }, { let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩, let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn), suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse, { simpa [show ¬ size' ≤ n, from h, mi] }, rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _, ← list.foldr_reverse], induction bkts'.as_list.reverse with a l IH, { simp [mk_as_list] }, { cases a with a'' b'', let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'), reinsert_aux hash_fn x y.1 y.2) (mk_array n' []), rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩, simp [IH.symm, or.left_comm, show B.as_list = _, from hl, show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } } end theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b := (find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') : (m.insert a b).find a' = m.find a' := option.eq_of_eq_some $ λb', let t := mem_insert m a b a' b' in (find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) : (m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' := if h : a = a' then by rw dif_pos h; exact match a', h with ._, rfl := find_insert_eq m a b end else by rw dif_neg h; exact find_insert_ne m a a' b h /-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/ def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β := l.foldl (λ m ⟨a, b⟩, insert m a b) m /-- Construct a hash map from a list of key-value pairs. -/ def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β := insert_all l (mk_hash_map hash_fn (2 * l.length)) /-- Remove a key from the map. (Modifies `m` in-place when applicable) -/ def erase (m : hash_map α β) (a : α) : hash_map α β := match m with ⟨hash_fn, size, n, buckets, v⟩ := if hc : contains_aux a (buckets.read hash_fn a) then { hash_fn := hash_fn, size := size - 1, nbuckets := n, buckets := buckets.modify hash_fn a (erase_aux a), is_valid := v.erase _ a hc } else m end theorem mem_erase : Π (m : hash_map α β) (a a' b'), (sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔ a ≠ a' ∧ sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin let bkt := bkts.read hash_fn a, by_cases Hc : (contains_aux a bkt : Prop), { let bkts' := bkts.modify hash_fn a (erase_aux a), suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list, { simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] }, have nd := v.nodup (mk_idx n (hash_fn a)), rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩, rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩, suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a', { have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨ ¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w), { simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] }, simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left, and_comm, and.left_comm, or.left_comm] }, intros m e, subst a', revert m, apply not_or_distrib.2, have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] }, { suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a', { simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] }, intros m e, subst a', exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) } end theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none := begin cases h : (m.erase a).find a with b, {refl}, exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left end theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') : (m.erase a).find a' = m.find a' := option.eq_of_eq_some $ λb', (find_iff _ _ _).trans $ (mem_erase m a a' b').trans $ (and_iff_right h).trans (find_iff _ _ _).symm theorem find_erase (m : hash_map α β) (a' a : α) : (m.erase a).find a' = if a = a' then none else m.find a' := if h : a = a' then by subst a'; simp [find_erase_eq m a] else by rw if_neg h; exact find_erase_ne m a a' h section string variables [has_to_string α] [∀ a, has_to_string (β a)] open prod private def key_data_to_string (a : α) (b : β a) (first : bool) : string := (if first then "" else ", ") ++ sformat!"{a} ← {b}" private def to_string (m : hash_map α β) : string := "⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩" instance : has_to_string (hash_map α β) := ⟨to_string⟩ end string section format open format prod variables [has_to_format α] [∀ a, has_to_format (β a)] private meta def format_key_data (a : α) (b : β a) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b private meta def to_format (m : hash_map α β) : format := group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++ to_fmt "⟩" meta instance : has_to_format (hash_map α β) := ⟨to_format⟩ end format end hash_map
a4d85d47b2cbf3c507390416822522f14ba7355d
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/complement.lean
42dfae52b389841fa689387acc83073bd6eb71b0
[ "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
12,271
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.group_action import group_theory.order_of_element import group_theory.quotient_group /-! # Complements In this file we define the complement of a subgroup. ## Main definitions - `is_complement S T` where `S` and `T` are subsets of `G` states that every `g : G` can be written uniquely as a product `s * t` for `s ∈ S`, `t ∈ T`. - `left_transversals T` where `T` is a subset of `G` is the set of all left-complements of `T`, i.e. the set of all `S : set G` that contain exactly one element of each left coset of `T`. - `right_transversals S` where `S` is a subset of `G` is the set of all right-complements of `S`, i.e. the set of all `T : set G` that contain exactly one element of each right coset of `S`. ## Main results - `is_complement_of_coprime` : Subgroups of coprime order are complements. -/ open_locale big_operators namespace subgroup variables {G : Type*} [group G] (H K : subgroup G) (S T : set G) /-- `S` and `T` are complements if `(*) : S × T → G` is a bijection. This notion generalizes left transversals, right transversals, and complementary subgroups. -/ @[to_additive "`S` and `T` are complements if `(*) : S × T → G` is a bijection"] def is_complement : Prop := function.bijective (λ x : S × T, x.1.1 * x.2.1) /-- `H` and `K` are complements if `(*) : H × K → G` is a bijection -/ @[to_additive "`H` and `K` are complements if `(*) : H × K → G` is a bijection"] abbreviation is_complement' := is_complement (H : set G) (K : set G) /-- The set of left-complements of `T : set G` -/ @[to_additive "The set of left-complements of `T : set G`"] def left_transversals : set (set G) := {S : set G | is_complement S T} /-- The set of right-complements of `S : set G` -/ @[to_additive "The set of right-complements of `S : set G`"] def right_transversals : set (set G) := {T : set G | is_complement S T} variables {H K S T} @[to_additive] lemma is_complement'_def : is_complement' H K ↔ is_complement (H : set G) (K : set G) := iff.rfl @[to_additive] lemma is_complement_iff_exists_unique : is_complement S T ↔ ∀ g : G, ∃! x : S × T, x.1.1 * x.2.1 = g := function.bijective_iff_exists_unique _ @[to_additive] lemma is_complement.exists_unique (h : is_complement S T) (g : G) : ∃! x : S × T, x.1.1 * x.2.1 = g := is_complement_iff_exists_unique.mp h g @[to_additive] lemma is_complement'.symm (h : is_complement' H K) : is_complement' K H := begin let ϕ : H × K ≃ K × H := equiv.mk (λ x, ⟨x.2⁻¹, x.1⁻¹⟩) (λ x, ⟨x.2⁻¹, x.1⁻¹⟩) (λ x, prod.ext (inv_inv _) (inv_inv _)) (λ x, prod.ext (inv_inv _) (inv_inv _)), let ψ : G ≃ G := equiv.mk (λ g : G, g⁻¹) (λ g : G, g⁻¹) inv_inv inv_inv, suffices : ψ ∘ (λ x : H × K, x.1.1 * x.2.1) = (λ x : K × H, x.1.1 * x.2.1) ∘ ϕ, { rwa [is_complement'_def, is_complement, ←equiv.bijective_comp, ←this, equiv.comp_bijective] }, exact funext (λ x, mul_inv_rev _ _), end @[to_additive] lemma is_complement'_comm : is_complement' H K ↔ is_complement' K H := ⟨is_complement'.symm, is_complement'.symm⟩ @[to_additive] lemma is_complement_top_singleton {g : G} : is_complement (⊤ : set G) {g} := ⟨λ ⟨x, _, rfl⟩ ⟨y, _, rfl⟩ h, prod.ext (subtype.ext (mul_right_cancel h)) rfl, λ x, ⟨⟨⟨x * g⁻¹, ⟨⟩⟩, g, rfl⟩, inv_mul_cancel_right x g⟩⟩ @[to_additive] lemma is_complement_singleton_top {g : G} : is_complement ({g} : set G) ⊤ := ⟨λ ⟨⟨_, rfl⟩, x⟩ ⟨⟨_, rfl⟩, y⟩ h, prod.ext rfl (subtype.ext (mul_left_cancel h)), λ x, ⟨⟨⟨g, rfl⟩, g⁻¹ * x, ⟨⟩⟩, mul_inv_cancel_left g x⟩⟩ @[to_additive] lemma is_complement_singleton_left {g : G} : is_complement {g} S ↔ S = ⊤ := begin refine ⟨λ h, top_le_iff.mp (λ x hx, _), λ h, (congr_arg _ h).mpr is_complement_singleton_top⟩, obtain ⟨⟨⟨z, rfl : z = g⟩, y, _⟩, hy⟩ := h.2 (g * x), rwa ← mul_left_cancel hy, end @[to_additive] lemma is_complement_singleton_right {g : G} : is_complement S {g} ↔ S = ⊤ := begin refine ⟨λ h, top_le_iff.mp (λ x hx, _), λ h, (congr_arg _ h).mpr is_complement_top_singleton⟩, obtain ⟨y, hy⟩ := h.2 (x * g), conv_rhs at hy { rw ← (show y.2.1 = g, from y.2.2) }, rw ← mul_right_cancel hy, exact y.1.2, end @[to_additive] lemma is_complement_top_left : is_complement ⊤ S ↔ ∃ g : G, S = {g} := begin refine ⟨λ h, set.exists_eq_singleton_iff_nonempty_unique_mem.mpr ⟨_, λ a b ha hb, _⟩, _⟩, { obtain ⟨a, ha⟩ := h.2 1, exact ⟨a.2.1, a.2.2⟩ }, { have : (⟨⟨_, mem_top a⁻¹⟩, ⟨a, ha⟩⟩ : (⊤ : set G) × S) = ⟨⟨_, mem_top b⁻¹⟩, ⟨b, hb⟩⟩ := h.1 ((inv_mul_self a).trans (inv_mul_self b).symm), exact subtype.ext_iff.mp ((prod.ext_iff.mp this).2) }, { rintro ⟨g, rfl⟩, exact is_complement_top_singleton }, end @[to_additive] lemma is_complement_top_right : is_complement S ⊤ ↔ ∃ g : G, S = {g} := begin refine ⟨λ h, set.exists_eq_singleton_iff_nonempty_unique_mem.mpr ⟨_, λ a b ha hb, _⟩, _⟩, { obtain ⟨a, ha⟩ := h.2 1, exact ⟨a.1.1, a.1.2⟩ }, { have : (⟨⟨a, ha⟩, ⟨_, mem_top a⁻¹⟩⟩ : S × (⊤ : set G)) = ⟨⟨b, hb⟩, ⟨_, mem_top b⁻¹⟩⟩ := h.1 ((mul_inv_self a).trans (mul_inv_self b).symm), exact subtype.ext_iff.mp ((prod.ext_iff.mp this).1) }, { rintro ⟨g, rfl⟩, exact is_complement_singleton_top }, end @[to_additive] lemma is_complement'_top_bot : is_complement' (⊤ : subgroup G) ⊥ := is_complement_top_singleton @[to_additive] lemma is_complement'_bot_top : is_complement' (⊥ : subgroup G) ⊤ := is_complement_singleton_top @[simp, to_additive] lemma is_complement'_bot_left : is_complement' ⊥ H ↔ H = ⊤ := is_complement_singleton_left.trans coe_eq_univ @[simp, to_additive] lemma is_complement'_bot_right : is_complement' H ⊥ ↔ H = ⊤ := is_complement_singleton_right.trans coe_eq_univ @[simp, to_additive] lemma is_complement'_top_left : is_complement' ⊤ H ↔ H = ⊥ := is_complement_top_left.trans coe_eq_singleton @[simp, to_additive] lemma is_complement'_top_right : is_complement' H ⊤ ↔ H = ⊥ := is_complement_top_right.trans coe_eq_singleton @[to_additive] lemma mem_left_transversals_iff_exists_unique_inv_mul_mem : S ∈ left_transversals T ↔ ∀ g : G, ∃! s : S, (s : G)⁻¹ * g ∈ T := begin rw [left_transversals, set.mem_set_of_eq, is_complement_iff_exists_unique], refine ⟨λ h g, _, λ h g, _⟩, { obtain ⟨x, h1, h2⟩ := h g, exact ⟨x.1, (congr_arg (∈ T) (eq_inv_mul_of_mul_eq h1)).mp x.2.2, λ y hy, (prod.ext_iff.mp (h2 ⟨y, y⁻¹ * g, hy⟩ (mul_inv_cancel_left y g))).1⟩ }, { obtain ⟨x, h1, h2⟩ := h g, refine ⟨⟨x, x⁻¹ * g, h1⟩, mul_inv_cancel_left x g, λ y hy, _⟩, have := h2 y.1 ((congr_arg (∈ T) (eq_inv_mul_of_mul_eq hy)).mp y.2.2), exact prod.ext this (subtype.ext (eq_inv_mul_of_mul_eq ((congr_arg _ this).mp hy))) }, end @[to_additive] lemma mem_right_transversals_iff_exists_unique_mul_inv_mem : S ∈ right_transversals T ↔ ∀ g : G, ∃! s : S, g * (s : G)⁻¹ ∈ T := begin rw [right_transversals, set.mem_set_of_eq, is_complement_iff_exists_unique], refine ⟨λ h g, _, λ h g, _⟩, { obtain ⟨x, h1, h2⟩ := h g, exact ⟨x.2, (congr_arg (∈ T) (eq_mul_inv_of_mul_eq h1)).mp x.1.2, λ y hy, (prod.ext_iff.mp (h2 ⟨⟨g * y⁻¹, hy⟩, y⟩ (inv_mul_cancel_right g y))).2⟩ }, { obtain ⟨x, h1, h2⟩ := h g, refine ⟨⟨⟨g * x⁻¹, h1⟩, x⟩, inv_mul_cancel_right g x, λ y hy, _⟩, have := h2 y.2 ((congr_arg (∈ T) (eq_mul_inv_of_mul_eq hy)).mp y.1.2), exact prod.ext (subtype.ext (eq_mul_inv_of_mul_eq ((congr_arg _ this).mp hy))) this }, end @[to_additive] lemma mem_left_transversals_iff_exists_unique_quotient_mk'_eq : S ∈ left_transversals (H : set G) ↔ ∀ q : quotient (quotient_group.left_rel H), ∃! s : S, quotient.mk' s.1 = q := begin have key : ∀ g h, quotient.mk' g = quotient.mk' h ↔ g⁻¹ * h ∈ H := @quotient.eq' G (quotient_group.left_rel H), simp_rw [mem_left_transversals_iff_exists_unique_inv_mul_mem, set_like.mem_coe, ←key], exact ⟨λ h q, quotient.induction_on' q h, λ h g, h (quotient.mk' g)⟩, end @[to_additive] lemma mem_right_transversals_iff_exists_unique_quotient_mk'_eq : S ∈ right_transversals (H : set G) ↔ ∀ q : quotient (quotient_group.right_rel H), ∃! s : S, quotient.mk' s.1 = q := begin have key : ∀ g h, quotient.mk' g = quotient.mk' h ↔ h * g⁻¹ ∈ H := @quotient.eq' G (quotient_group.right_rel H), simp_rw [mem_right_transversals_iff_exists_unique_mul_inv_mem, set_like.mem_coe, ←key], exact ⟨λ h q, quotient.induction_on' q h, λ h g, h (quotient.mk' g)⟩, end @[to_additive] lemma mem_left_transversals_iff_bijective : S ∈ left_transversals (H : set G) ↔ function.bijective (S.restrict (quotient.mk' : G → quotient (quotient_group.left_rel H))) := mem_left_transversals_iff_exists_unique_quotient_mk'_eq.trans (function.bijective_iff_exists_unique (S.restrict quotient.mk')).symm @[to_additive] lemma mem_right_transversals_iff_bijective : S ∈ right_transversals (H : set G) ↔ function.bijective (set.restrict (quotient.mk' : G → quotient (quotient_group.right_rel H)) S) := mem_right_transversals_iff_exists_unique_quotient_mk'_eq.trans (function.bijective_iff_exists_unique (S.restrict quotient.mk')).symm @[to_additive] instance : inhabited (left_transversals (H : set G)) := ⟨⟨set.range quotient.out', mem_left_transversals_iff_bijective.mpr ⟨by { rintros ⟨_, q₁, rfl⟩ ⟨_, q₂, rfl⟩ hg, rw (q₁.out_eq'.symm.trans hg).trans q₂.out_eq' }, λ q, ⟨⟨q.out', q, rfl⟩, quotient.out_eq' q⟩⟩⟩⟩ @[to_additive] instance : inhabited (right_transversals (H : set G)) := ⟨⟨set.range quotient.out', mem_right_transversals_iff_bijective.mpr ⟨by { rintros ⟨_, q₁, rfl⟩ ⟨_, q₂, rfl⟩ hg, rw (q₁.out_eq'.symm.trans hg).trans q₂.out_eq' }, λ q, ⟨⟨q.out', q, rfl⟩, quotient.out_eq' q⟩⟩⟩⟩ lemma is_complement.card_mul [fintype G] [fintype S] [fintype T] (h : is_complement S T) : fintype.card S * fintype.card T = fintype.card G := (fintype.card_prod _ _).symm.trans (fintype.card_of_bijective h) lemma is_complement'.card_mul [fintype G] [fintype H] [fintype K] (h : is_complement' H K) : fintype.card H * fintype.card K = fintype.card G := h.card_mul lemma is_complement'.disjoint (h : is_complement' H K) : disjoint H K := λ g hg, let x : H × K := ⟨⟨g, hg.1⟩, 1⟩, y : H × K := ⟨1, ⟨g, hg.2⟩⟩ in subtype.ext_iff.mp (prod.ext_iff.mp (h.1 (show x.1.1 * _ = y.1.1 * _, from (mul_one g).trans (one_mul g).symm))).1 lemma is_complement'_of_card_mul_and_disjoint [fintype G] [fintype H] [fintype K] (h1 : fintype.card H * fintype.card K = fintype.card G) (h2 : disjoint H K) : is_complement' H K := begin refine (fintype.bijective_iff_injective_and_card _).mpr ⟨λ x y h, _, (fintype.card_prod H K).trans h1⟩, rw [←eq_inv_mul_iff_mul_eq, ←mul_assoc, ←mul_inv_eq_iff_eq_mul] at h, change ↑(x.2 * y.2⁻¹) = ↑(x.1⁻¹ * y.1) at h, rw [prod.ext_iff, ←@inv_mul_eq_one H _ x.1 y.1, ←@mul_inv_eq_one K _ x.2 y.2, subtype.ext_iff, subtype.ext_iff, coe_one, coe_one, h, and_self, ←mem_bot, ←h2.eq_bot, mem_inf], exact ⟨subtype.mem ((x.1)⁻¹ * (y.1)), (congr_arg (∈ K) h).mp (subtype.mem (x.2 * (y.2)⁻¹))⟩, end lemma is_complement'_iff_card_mul_and_disjoint [fintype G] [fintype H] [fintype K] : is_complement' H K ↔ fintype.card H * fintype.card K = fintype.card G ∧ disjoint H K := ⟨λ h, ⟨h.card_mul, h.disjoint⟩, λ h, is_complement'_of_card_mul_and_disjoint h.1 h.2⟩ lemma is_complement'_of_coprime [fintype G] [fintype H] [fintype K] (h1 : fintype.card H * fintype.card K = fintype.card G) (h2 : nat.coprime (fintype.card H) (fintype.card K)) : is_complement' H K := is_complement'_of_card_mul_and_disjoint h1 (disjoint_iff.mpr (inf_eq_bot_of_coprime h2)) end subgroup
9e909f0cda36ef0430f13db8a0fd50ffbccbb1ce
e791a827712b9cda7e14eb9861a152725a60f884
/algebra.lean
dac572a767b5cdf4500887bf81056a691a2fe17c
[]
no_license
Shamrock-Frost/FormalComplexAnalysis
29bf1d45f59b22d6553b24fe5b630464f9c2d9fa
3cac79d9b603b1edf7df1bc7e948c74eb86a2cc0
refs/heads/master
1,588,634,495,874
1,554,397,551,000
1,554,397,551,000
179,541,347
0
0
null
null
null
null
UTF-8
Lean
false
false
2,896
lean
lemma {u} FOIL {R : Type u} [ring R] : ∀ a b c d : R, (a + b) * (c + d) = a*c + a*d + b*c + b*d := by { intros, rw [left_distrib, right_distrib, right_distrib], ac_refl } lemma {u} FOIL_neg_square {R : Type u} [comm_ring R] : ∀ a b : R, (a - b) * (a - b) = a*a + (-(a*b)+ -(a*b)) + b*b := by { intros, rw sub_eq_add_neg, rw FOIL, rw neg_mul_neg, repeat { rw add_assoc }, congr, rw neg_mul_eq_mul_neg, rw [mul_comm a b, neg_mul_eq_neg_mul] } lemma {u} FOIL_sub {R : Type u} [ring R] : ∀ a b c d : R, (a - b) * (c - d) = a*c - a*d - b*c + b*d := by { intros, repeat { rw sub_eq_add_neg }, rw FOIL, rw neg_mul_eq_mul_neg, rw neg_mul_eq_neg_mul, apply congr_arg, rw [← neg_mul_eq_mul_neg, ← neg_mul_eq_neg_mul, neg_neg] } lemma difference_of_squares {R} [comm_ring R] : ∀ x y : R, x * x - y*y = (x - y)*(x + y) := begin intros, rw sub_eq_add_neg, rw sub_eq_add_neg, rw FOIL, rw add_assoc (x*x), rw mul_comm (-y) x, rw ← neg_mul_eq_mul_neg, rw ← sub_eq_add_neg (x*y), rw sub_self, rw add_zero, congr, rw neg_mul_eq_mul_neg, rw mul_comm end lemma div_of_div_eq_self {F} [field F] : ∀ x y : F, x ≠ 0 → y ≠ 0 → x/(x/y) = y := begin intros, rw div_eq_mul_one_div x y, rw field.div_mul_eq_div_mul_one_div _ a, rw div_self a, rw one_mul, rw [one_div_eq_inv, one_div_eq_inv], rw division_ring.inv_inv a_1, apply one_div_ne_zero a_1, end lemma square_neg_one {R} [ring R] : (-1)*(-1) = (1 : R) := begin apply eq_of_sub_eq_zero, rw sub_eq_add_neg, transitivity (-1)*(-1) + (-1)*(1:R), rw mul_one, rw ← left_distrib, rw neg_add_self, rw mul_zero end lemma weird_analysis_trick {R} [ring R] : ∀ a b c d : R, a * c = (a - b) * (c - d) + a * d + b * c - b * d := begin intros, rw [sub_eq_add_neg a, sub_eq_add_neg c], rw FOIL, rw [← neg_mul_eq_neg_mul b (-d), mul_neg_eq_neg_mul_symm b d, neg_neg], rw add_right_comm _ (b*d), rw add_right_comm _ (b*d), rw add_sub_assoc, rw [sub_self, add_zero], rw add_right_comm _ (-b*c), rw [← neg_mul_eq_neg_mul, add_assoc, neg_add_self, add_zero], rw [add_assoc, mul_neg_eq_neg_mul_symm, neg_add_self, add_zero] end lemma eq_zero_of_sqr_eq_zero {F} [division_ring F] [decidable_eq F] : ∀ {x : F}, x * x = 0 → x = 0 := begin intros x h, by_contra h', refine (_ : x * x ≠ 0) h, apply division_ring.mul_ne_zero h' h' end lemma classical.l_or_r_eq_zero_of_mul_eq_zero {F} [division_ring F] : ∀ {x y : F}, x * y = 0 → x = 0 ∨ y = 0 := begin intros x y h, apply classical.by_contradiction, rw @decidable.not_or_iff_and_not _ _ (classical.prop_decidable _) (classical.prop_decidable _), intro h', apply division_ring.mul_ne_zero h'.left h'.right, assumption end lemma eq_sub_implies_sub_zero {G} [add_comm_group G] : ∀ x y : G, x = x - y → y = 0 := begin intros, transitivity x - (x - y), { rw sub_sub_self x y }, rw ← a, apply sub_self end
56c2ed34f91dc70b96b14427122020fb1101fc8e
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/multiset/nodup.lean
09b5860fe59e1665df34f194adf4d22e16bc3335
[ "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
9,640
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.bind import data.multiset.powerset import data.multiset.range /-! # The `nodup` predicate for multisets without duplicate elements. -/ namespace multiset open function list variables {α β γ : Type*} {r : α → α → Prop} {s t : multiset α} {a : α} /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext p.nodup_iff) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons lemma nodup.cons (m : a ∉ s) (n : nodup s) : nodup (a ::ₘ s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup ({a} : multiset α) := nodup_singleton lemma nodup.of_cons (h : nodup (a ::ₘ s)) : nodup s := (nodup_cons.1 h).2 theorem nodup.not_mem (h : nodup (a ::ₘ s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup.sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a ::ₘ a ::ₘ 0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a ::ₘ a ::ₘ 0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm lemma nodup_iff_ne_cons_cons {s : multiset α} : s.nodup ↔ ∀ a t, s ≠ a ::ₘ a ::ₘ t := nodup_iff_le.trans ⟨λ h a t s_eq, h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))), λ h a le, let ⟨t, s_eq⟩ := le_iff_exists_add.mp le in h a t (by rwa [cons_add, cons_add, zero_add] at s_eq )⟩ theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma nodup_iff_pairwise {α} {s : multiset α} : nodup s ↔ pairwise (≠) s := quotient.induction_on s $ λ l, (pairwise_coe_iff_pairwise (by exact λ a b, ne.symm)).symm protected lemma nodup.pairwise : (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma pairwise.forall (H : symmetric r) (hs : pairwise r s) : ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → a ≠ b → r a b := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ hl₂.forall H theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 lemma nodup.add_iff (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] lemma nodup.of_map (f : α → β) : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup.of_map f lemma nodup.map_on {f : α → β} : (∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup.map_on lemma nodup.map {f : α → β} {s : multiset α} (hf : injective f) : nodup s → nodup (map f s) := nodup.map_on (λ x _ y _ h, hf h) theorem inj_on_of_nodup_map {f : α → β} {s : multiset α} : nodup (map f s) → ∀ (x ∈ s) (y ∈ s), f x = f y → x = y := quot.induction_on s $ λ l, inj_on_of_nodup_map theorem nodup_map_iff_inj_on {f : α → β} {s : multiset α} (d : nodup s) : nodup (map f s) ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨inj_on_of_nodup_map, λ h, d.map_on h⟩ lemma nodup.filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup.filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach lemma nodup.pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup.pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable lemma nodup.erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ d.erase_eq_filter a lemma nodup.erase [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) lemma nodup.mem_erase_iff [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw [d.erase_eq_filter b, mem_filter, and_comm] lemma nodup.not_mem_erase [decidable_eq α] {a : α} {s} (h : nodup s) : a ∉ s.erase a := λ ha, (h.mem_erase_iff.1 ha).1 rfl protected lemma nodup.product {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [d₁.product d₂] protected lemma nodup.sigma {σ : α → Type*} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup.sigma end protected lemma nodup.filter_map (f : α → option β) (H : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup.filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ lemma nodup.inter_left [decidable_eq α] (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ lemma nodup.inter_right [decidable_eq α] (s) : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, (nodup_of_le (map_single_le_powerset _) h).of_map _, quotient.induction_on s $ λ l h, by simp; refine (nodup_sublists'.2 h).map_on _ ; exact λ x sx y sy e, (h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ alias nodup_powerset ↔ nodup.of_powerset nodup.powerset protected lemma nodup.powerset_len {n : ℕ} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] lemma nodup.ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, d.subperm⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le tsub_le_self h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, tsub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le le_tsub_add h₁) h₂⟩ lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β} (hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.map f = t.map g := have t = s.attach.map (λ x, i x.1 x.2), from (ht.ext $ (nodup_attach.2 hs).map $ show injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy, subtype.eq $ i_inj x.1 y.1 x.2 y.2 hxy).2 (λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach]; exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩), calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map] ... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach] ... = t.map g : by rw [this, multiset.map_map]; exact map_congr rfl (λ x _, h _ _) end multiset
bfdf77f97a0d6f5d01c258762f90e51748d6c6ac
92b50235facfbc08dfe7f334827d47281471333b
/hott/hit/circle.hlean
d7a17712c2fcf20928eab241bf4b1d92f01561fc
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
9,711
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the circle -/ import .sphere import types.bool types.int.hott types.equiv import algebra.fundamental_group algebra.hott open eq susp bool sphere_index is_equiv equiv equiv.ops is_trunc pi definition circle : Type₀ := sphere 1 namespace circle notation `S¹` := circle definition base1 : circle := !north definition base2 : circle := !south definition seg1 : base1 = base2 := merid !north definition seg2 : base1 = base2 := merid !south definition base : circle := base1 definition loop : base = base := seg2 ⬝ seg1⁻¹ definition rec2 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) (x : circle) : P x := begin induction x with b, { exact Pb1}, { exact Pb2}, { esimp at *, induction b with y, { exact Ps1}, { exact Ps2}, { cases y}}, end definition rec2_on [reducible] {P : circle → Type} (x : circle) (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : P x := circle.rec2 Pb1 Pb2 Ps1 Ps2 x theorem rec2_seg1 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : apdo (rec2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := !rec_merid theorem rec2_seg2 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : apdo (rec2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := !rec_merid definition elim2 {P : Type} (Pb1 Pb2 : P) (Ps1 Ps2 : Pb1 = Pb2) (x : circle) : P := rec2 Pb1 Pb2 (pathover_of_eq Ps1) (pathover_of_eq Ps2) x definition elim2_on [reducible] {P : Type} (x : circle) (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : P := elim2 Pb1 Pb2 Ps1 Ps2 x theorem elim2_seg1 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg1), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim2,rec2_seg1], end theorem elim2_seg2 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg2), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim2,rec2_seg2], end definition elim2_type (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) (x : circle) : Type := elim2 Pb1 Pb2 (ua Ps1) (ua Ps2) x definition elim2_type_on [reducible] (x : circle) (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : Type := elim2_type Pb1 Pb2 Ps1 Ps2 x theorem elim2_type_seg1 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg1];apply cast_ua_fn theorem elim2_type_seg2 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg2];apply cast_ua_fn protected definition rec {P : circle → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) (x : circle) : P x := begin fapply (rec2_on x), { exact Pbase}, { exact (transport P seg1 Pbase)}, { apply pathover_tr}, { apply pathover_tr_of_pathover, exact Ploop} end protected definition rec_on [reducible] {P : circle → Type} (x : circle) (Pbase : P base) (Ploop : Pbase =[loop] Pbase) : P x := circle.rec Pbase Ploop x theorem rec_loop_helper {A : Type} (P : A → Type) {x y z : A} {p : x = y} {p' : z = y} {u : P x} {v : P z} (q : u =[p ⬝ p'⁻¹] v) : pathover_tr_of_pathover q ⬝o !pathover_tr⁻¹ᵒ = q := by cases p'; cases q; exact idp definition con_refl {A : Type} {x y : A} (p : x = y) : p ⬝ refl _ = p := eq.rec_on p idp theorem rec_loop {P : circle → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) : apdo (circle.rec Pbase Ploop) loop = Ploop := begin rewrite [↑loop,apdo_con,↑circle.rec,↑circle.rec2_on,↑base,rec2_seg2,apdo_inv,rec2_seg1], apply rec_loop_helper end protected definition elim {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) (x : circle) : P := circle.rec Pbase (pathover_of_eq Ploop) x protected definition elim_on [reducible] {P : Type} (x : circle) (Pbase : P) (Ploop : Pbase = Pbase) : P := circle.elim Pbase Ploop x theorem elim_loop {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) loop = Ploop := begin apply eq_of_fn_eq_fn_inv !(pathover_constant loop), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑circle.elim,rec_loop], end protected definition elim_type (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : circle) : Type := circle.elim Pbase (ua Ploop) x protected definition elim_type_on [reducible] (x : circle) (Pbase : Type) (Ploop : Pbase ≃ Pbase) : Type := circle.elim_type Pbase Ploop x theorem elim_type_loop (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (circle.elim_type Pbase Ploop) loop = Ploop := by rewrite [tr_eq_cast_ap_fn,↑circle.elim_type,circle.elim_loop];apply cast_ua_fn theorem elim_type_loop_inv (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (circle.elim_type Pbase Ploop) loop⁻¹ = to_inv Ploop := by rewrite [tr_inv_fn,↑to_inv]; apply inv_eq_inv; apply elim_type_loop end circle attribute circle.base1 circle.base2 circle.base [constructor] attribute circle.rec2 circle.elim2 [unfold 6] [recursor 6] attribute circle.elim2_type [unfold 5] attribute circle.rec2_on circle.elim2_on [unfold 2] attribute circle.elim2_type [unfold 1] attribute circle.elim circle.rec [unfold 4] [recursor 4] attribute circle.elim_type [unfold 3] attribute circle.rec_on circle.elim_on [unfold 2] attribute circle.elim_type_on [unfold 1] namespace circle definition pointed_circle [instance] [constructor] : pointed circle := pointed.mk base definition loop_neq_idp : loop ≠ idp := assume H : loop = idp, have H2 : Π{A : Type₁} {a : A} {p : a = a}, p = idp, from λA a p, calc p = ap (circle.elim a p) loop : elim_loop ... = ap (circle.elim a p) (refl base) : by rewrite H, absurd H2 eq_bnot_ne_idp definition nonidp (x : circle) : x = x := begin induction x, { exact loop}, { apply concato_eq, apply pathover_eq_lr, rewrite [con.left_inv,idp_con]} end definition nonidp_neq_idp : nonidp ≠ (λx, idp) := assume H : nonidp = λx, idp, have H2 : loop = idp, from apd10 H base, absurd H2 loop_neq_idp open int protected definition code (x : circle) : Type₀ := circle.elim_type_on x ℤ equiv_succ definition transport_code_loop (a : ℤ) : transport circle.code loop a = succ a := ap10 !elim_type_loop a definition transport_code_loop_inv (a : ℤ) : transport circle.code loop⁻¹ a = pred a := ap10 !elim_type_loop_inv a protected definition encode {x : circle} (p : base = x) : circle.code x := transport circle.code p (of_num 0) -- why is the explicit coercion needed here? protected definition decode {x : circle} : circle.code x → base = x := begin induction x, { exact power loop}, { apply arrow_pathover_left, intro b, apply concato_eq, apply pathover_eq_r, rewrite [power_con,transport_code_loop]} end --remove this theorem after #484 theorem encode_decode {x : circle} : Π(a : circle.code x), circle.encode (circle.decode a) = a := begin unfold circle.decode, induction x, { intro a, esimp [base,base1], --simplify after #587 apply rec_nat_on a, { exact idp}, { intros n p, apply transport (λ(y : base = base), transport circle.code y _ = _), apply power_con, rewrite [▸*,con_tr, transport_code_loop, ↑[circle.encode,circle.code] at p], krewrite p}, { intros n p, apply transport (λ(y : base = base), transport circle.code y _ = _), { exact !power_con_inv ⬝ ap (power loop) !neg_succ⁻¹}, rewrite [▸*,@con_tr _ circle.code,transport_code_loop_inv, ↑[circle.encode] at p, p, -neg_succ]}}, { apply pathover_of_tr_eq, apply eq_of_homotopy, intro a, apply @is_hset.elim, esimp [circle.code,base,base1], exact _} --simplify after #587 end definition circle_eq_equiv (x : circle) : (base = x) ≃ circle.code x := begin fapply equiv.MK, { exact circle.encode}, { exact circle.decode}, { exact circle.encode_decode}, { intro p, cases p, exact idp}, end definition base_eq_base_equiv : base = base ≃ ℤ := circle_eq_equiv base definition decode_add (a b : ℤ) : base_eq_base_equiv⁻¹ a ⬝ base_eq_base_equiv⁻¹ b = base_eq_base_equiv⁻¹ (a + b) := !power_con_power definition encode_con (p q : base = base) : circle.encode (p ⬝ q) = circle.encode p + circle.encode q := preserve_binary_of_inv_preserve base_eq_base_equiv concat add decode_add p q --the carrier of π₁(S¹) is the set-truncation of base = base. open core algebra trunc equiv.ops definition fg_carrier_equiv_int : π₁(S¹) ≃ ℤ := trunc_equiv_trunc 0 base_eq_base_equiv ⬝e !equiv_trunc⁻¹ᵉ definition fundamental_group_of_circle : π₁(S¹) = group_integers := begin apply (Group_eq fg_carrier_equiv_int), intros g h, induction g with g', induction h with h', -- esimp at *, -- esimp [fg_carrier_equiv_int,equiv.trans,equiv.symm,equiv_trunc,trunc_equiv_trunc, -- base_eq_base_equiv,circle_eq_equiv,is_equiv_tr,semigroup.to_has_mul,monoid.to_semigroup, -- group.to_monoid,fundamental_group.mul], apply encode_con, end end circle
56d4dc38205487f8e3c5b447e702302afa2eef5a
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/InvolutiveRingoid.lean
b8b5b4788fbe269a63dbc7e66fd5ed431308e68b
[]
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
14,081
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 InvolutiveRingoid structure InvolutiveRingoid (A : Type) : Type := (prim : (A → A)) (one : A) (fixes_prim_one : (prim one) = one) (involutive_prim : (∀ {x : A} , (prim (prim x)) = x)) (times : (A → (A → A))) (plus : (A → (A → A))) (leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z)))) (rightDistributive_times_plus : (∀ {x y z : A} , (times (plus y z) x) = (plus (times y x) (times z x)))) (antidis_prim_plus : (∀ {x y : A} , (prim (plus x y)) = (plus (prim y) (prim x)))) (antidis_prim_times : (∀ {x y : A} , (prim (times x y)) = (times (prim y) (prim x)))) open InvolutiveRingoid structure Sig (AS : Type) : Type := (primS : (AS → AS)) (oneS : AS) (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (primP : ((Prod A A) → (Prod A A))) (oneP : (Prod A A)) (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (fixes_prim_1P : (primP oneP) = oneP) (involutive_primP : (∀ {xP : (Prod A A)} , (primP (primP xP)) = xP)) (leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP)))) (rightDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP (plusP yP zP) xP) = (plusP (timesP yP xP) (timesP zP xP)))) (antidis_prim_plusP : (∀ {xP yP : (Prod A A)} , (primP (plusP xP yP)) = (plusP (primP yP) (primP xP)))) (antidis_prim_timesP : (∀ {xP yP : (Prod A A)} , (primP (timesP xP yP)) = (timesP (primP yP) (primP xP)))) structure Hom {A1 : Type} {A2 : Type} (In1 : (InvolutiveRingoid A1)) (In2 : (InvolutiveRingoid A2)) : Type := (hom : (A1 → A2)) (pres_prim : (∀ {x1 : A1} , (hom ((prim In1) x1)) = ((prim In2) (hom x1)))) (pres_one : (hom (one In1)) = (one In2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times In1) x1 x2)) = ((times In2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus In1) x1 x2)) = ((plus In2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (In1 : (InvolutiveRingoid A1)) (In2 : (InvolutiveRingoid A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_prim : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((prim In1) x1) ((prim In2) y1))))) (interp_one : (interp (one In1) (one In2))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times In1) x1 x2) ((times In2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus In1) x1 x2) ((plus In2) y1 y2)))))) inductive InvolutiveRingoidTerm : Type | primL : (InvolutiveRingoidTerm → InvolutiveRingoidTerm) | oneL : InvolutiveRingoidTerm | timesL : (InvolutiveRingoidTerm → (InvolutiveRingoidTerm → InvolutiveRingoidTerm)) | plusL : (InvolutiveRingoidTerm → (InvolutiveRingoidTerm → InvolutiveRingoidTerm)) open InvolutiveRingoidTerm inductive ClInvolutiveRingoidTerm (A : Type) : Type | sing : (A → ClInvolutiveRingoidTerm) | primCl : (ClInvolutiveRingoidTerm → ClInvolutiveRingoidTerm) | oneCl : ClInvolutiveRingoidTerm | timesCl : (ClInvolutiveRingoidTerm → (ClInvolutiveRingoidTerm → ClInvolutiveRingoidTerm)) | plusCl : (ClInvolutiveRingoidTerm → (ClInvolutiveRingoidTerm → ClInvolutiveRingoidTerm)) open ClInvolutiveRingoidTerm inductive OpInvolutiveRingoidTerm (n : ℕ) : Type | v : ((fin n) → OpInvolutiveRingoidTerm) | primOL : (OpInvolutiveRingoidTerm → OpInvolutiveRingoidTerm) | oneOL : OpInvolutiveRingoidTerm | timesOL : (OpInvolutiveRingoidTerm → (OpInvolutiveRingoidTerm → OpInvolutiveRingoidTerm)) | plusOL : (OpInvolutiveRingoidTerm → (OpInvolutiveRingoidTerm → OpInvolutiveRingoidTerm)) open OpInvolutiveRingoidTerm inductive OpInvolutiveRingoidTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpInvolutiveRingoidTerm2) | sing2 : (A → OpInvolutiveRingoidTerm2) | primOL2 : (OpInvolutiveRingoidTerm2 → OpInvolutiveRingoidTerm2) | oneOL2 : OpInvolutiveRingoidTerm2 | timesOL2 : (OpInvolutiveRingoidTerm2 → (OpInvolutiveRingoidTerm2 → OpInvolutiveRingoidTerm2)) | plusOL2 : (OpInvolutiveRingoidTerm2 → (OpInvolutiveRingoidTerm2 → OpInvolutiveRingoidTerm2)) open OpInvolutiveRingoidTerm2 def simplifyCl {A : Type} : ((ClInvolutiveRingoidTerm A) → (ClInvolutiveRingoidTerm A)) | (primCl oneCl) := oneCl | (primCl (primCl x)) := x | (plusCl (primCl y) (primCl x)) := (primCl (plusCl x y)) | (timesCl (primCl y) (primCl x)) := (primCl (timesCl x y)) | (primCl x1) := (primCl (simplifyCl x1)) | oneCl := oneCl | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpInvolutiveRingoidTerm n) → (OpInvolutiveRingoidTerm n)) | (primOL oneOL) := oneOL | (primOL (primOL x)) := x | (plusOL (primOL y) (primOL x)) := (primOL (plusOL x y)) | (timesOL (primOL y) (primOL x)) := (primOL (timesOL x y)) | (primOL x1) := (primOL (simplifyOpB x1)) | oneOL := oneOL | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpInvolutiveRingoidTerm2 n A) → (OpInvolutiveRingoidTerm2 n A)) | (primOL2 oneOL2) := oneOL2 | (primOL2 (primOL2 x)) := x | (plusOL2 (primOL2 y) (primOL2 x)) := (primOL2 (plusOL2 x y)) | (timesOL2 (primOL2 y) (primOL2 x)) := (primOL2 (timesOL2 x y)) | (primOL2 x1) := (primOL2 (simplifyOp x1)) | oneOL2 := oneOL2 | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((InvolutiveRingoid A) → (InvolutiveRingoidTerm → A)) | In (primL x1) := ((prim In) (evalB In x1)) | In oneL := (one In) | In (timesL x1 x2) := ((times In) (evalB In x1) (evalB In x2)) | In (plusL x1 x2) := ((plus In) (evalB In x1) (evalB In x2)) def evalCl {A : Type} : ((InvolutiveRingoid A) → ((ClInvolutiveRingoidTerm A) → A)) | In (sing x1) := x1 | In (primCl x1) := ((prim In) (evalCl In x1)) | In oneCl := (one In) | In (timesCl x1 x2) := ((times In) (evalCl In x1) (evalCl In x2)) | In (plusCl x1 x2) := ((plus In) (evalCl In x1) (evalCl In x2)) def evalOpB {A : Type} {n : ℕ} : ((InvolutiveRingoid A) → ((vector A n) → ((OpInvolutiveRingoidTerm n) → A))) | In vars (v x1) := (nth vars x1) | In vars (primOL x1) := ((prim In) (evalOpB In vars x1)) | In vars oneOL := (one In) | In vars (timesOL x1 x2) := ((times In) (evalOpB In vars x1) (evalOpB In vars x2)) | In vars (plusOL x1 x2) := ((plus In) (evalOpB In vars x1) (evalOpB In vars x2)) def evalOp {A : Type} {n : ℕ} : ((InvolutiveRingoid A) → ((vector A n) → ((OpInvolutiveRingoidTerm2 n A) → A))) | In vars (v2 x1) := (nth vars x1) | In vars (sing2 x1) := x1 | In vars (primOL2 x1) := ((prim In) (evalOp In vars x1)) | In vars oneOL2 := (one In) | In vars (timesOL2 x1 x2) := ((times In) (evalOp In vars x1) (evalOp In vars x2)) | In vars (plusOL2 x1 x2) := ((plus In) (evalOp In vars x1) (evalOp In vars x2)) def inductionB {P : (InvolutiveRingoidTerm → Type)} : ((∀ (x1 : InvolutiveRingoidTerm) , ((P x1) → (P (primL x1)))) → ((P oneL) → ((∀ (x1 x2 : InvolutiveRingoidTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : InvolutiveRingoidTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : InvolutiveRingoidTerm) , (P x)))))) | ppriml p1l ptimesl pplusl (primL x1) := (ppriml _ (inductionB ppriml p1l ptimesl pplusl x1)) | ppriml p1l ptimesl pplusl oneL := p1l | ppriml p1l ptimesl pplusl (timesL x1 x2) := (ptimesl _ _ (inductionB ppriml p1l ptimesl pplusl x1) (inductionB ppriml p1l ptimesl pplusl x2)) | ppriml p1l ptimesl pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ppriml p1l ptimesl pplusl x1) (inductionB ppriml p1l ptimesl pplusl x2)) def inductionCl {A : Type} {P : ((ClInvolutiveRingoidTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 : (ClInvolutiveRingoidTerm A)) , ((P x1) → (P (primCl x1)))) → ((P oneCl) → ((∀ (x1 x2 : (ClInvolutiveRingoidTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClInvolutiveRingoidTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClInvolutiveRingoidTerm A)) , (P x))))))) | psing pprimcl p1cl ptimescl ppluscl (sing x1) := (psing x1) | psing pprimcl p1cl ptimescl ppluscl (primCl x1) := (pprimcl _ (inductionCl psing pprimcl p1cl ptimescl ppluscl x1)) | psing pprimcl p1cl ptimescl ppluscl oneCl := p1cl | psing pprimcl p1cl ptimescl ppluscl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing pprimcl p1cl ptimescl ppluscl x1) (inductionCl psing pprimcl p1cl ptimescl ppluscl x2)) | psing pprimcl p1cl ptimescl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing pprimcl p1cl ptimescl ppluscl x1) (inductionCl psing pprimcl p1cl ptimescl ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpInvolutiveRingoidTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 : (OpInvolutiveRingoidTerm n)) , ((P x1) → (P (primOL x1)))) → ((P oneOL) → ((∀ (x1 x2 : (OpInvolutiveRingoidTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpInvolutiveRingoidTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpInvolutiveRingoidTerm n)) , (P x))))))) | pv pprimol p1ol ptimesol pplusol (v x1) := (pv x1) | pv pprimol p1ol ptimesol pplusol (primOL x1) := (pprimol _ (inductionOpB pv pprimol p1ol ptimesol pplusol x1)) | pv pprimol p1ol ptimesol pplusol oneOL := p1ol | pv pprimol p1ol ptimesol pplusol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv pprimol p1ol ptimesol pplusol x1) (inductionOpB pv pprimol p1ol ptimesol pplusol x2)) | pv pprimol p1ol ptimesol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pprimol p1ol ptimesol pplusol x1) (inductionOpB pv pprimol p1ol ptimesol pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpInvolutiveRingoidTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 : (OpInvolutiveRingoidTerm2 n A)) , ((P x1) → (P (primOL2 x1)))) → ((P oneOL2) → ((∀ (x1 x2 : (OpInvolutiveRingoidTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpInvolutiveRingoidTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpInvolutiveRingoidTerm2 n A)) , (P x)))))))) | pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 (primOL2 x1) := (pprimol2 _ (inductionOp pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 x1)) | pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 oneOL2 := p1ol2 | pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 x2)) | pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 pprimol2 p1ol2 ptimesol2 pplusol2 x2)) def stageB : (InvolutiveRingoidTerm → (Staged InvolutiveRingoidTerm)) | (primL x1) := (stage1 primL (codeLift1 primL) (stageB x1)) | oneL := (Now oneL) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClInvolutiveRingoidTerm A) → (Staged (ClInvolutiveRingoidTerm A))) | (sing x1) := (Now (sing x1)) | (primCl x1) := (stage1 primCl (codeLift1 primCl) (stageCl x1)) | oneCl := (Now oneCl) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpInvolutiveRingoidTerm n) → (Staged (OpInvolutiveRingoidTerm n))) | (v x1) := (const (code (v x1))) | (primOL x1) := (stage1 primOL (codeLift1 primOL) (stageOpB x1)) | oneOL := (Now oneOL) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpInvolutiveRingoidTerm2 n A) → (Staged (OpInvolutiveRingoidTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (primOL2 x1) := (stage1 primOL2 (codeLift1 primOL2) (stageOp x1)) | oneOL2 := (Now oneOL2) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (primT : ((Repr A) → (Repr A))) (oneT : (Repr A)) (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end InvolutiveRingoid
858b121fe30d022f512ec20de31515f4cfbb1f85
3618c6e11aa822fd542440674dfb9a7b9921dba0
/src/coprod/free_group.lean
9b77e4af9fe6eb910a2a42dba75de6f4185d87d1
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
7,183
lean
import coprod.basic import data.int.basic import algebra.group_power import logic.embedding import data.equiv.mul_add import group_theory.subgroup notation `C∞` := multiplicative ℤ @[reducible] def free_group (ι : Type*) := coprod (λ i : ι, C∞) namespace free_group variables {ι : Type*} [decidable_eq ι] {M : Type*} [monoid M] {G : Type*} [group G] variables {α : Type*} {β : Type*} {γ : Type*} [decidable_eq α] [decidable_eq β] [decidable_eq γ] open function coprod coprod.pre multiplicative instance : group (free_group ι) := @coprod.group ι (λ i : ι, C∞) _ _ _ instance : decidable_eq (free_group ι) := coprod.decidable_eq def of (i : ι) : free_group ι := ⟨[⟨i, of_add 1⟩], reduced_singleton dec_trivial⟩ def of' (i : ι) : C∞ →* free_group ι := coprod.of i def length : free_group α → ℕ := λ w, (w.to_list.map (λ a : Σ i : α, C∞, a.2.to_add.nat_abs)).sum @[simp] lemma cons_eq_of'_mul (l : list (Σ i : ι, C∞)) (g : Σ i : ι, C∞) (h) : @eq (free_group ι) ⟨g :: l, h⟩ (of' g.1 g.2 * ⟨l, reduced_of_reduced_cons h⟩) := coprod.cons_eq_of_mul _ _ @[simp] lemma append_eq_mul {l₁ l₂ : list (Σ i : ι, C∞)} (hl : reduced (l₁ ++ l₂)) : @eq (free_group ι) ⟨l₁ ++ l₂, hl⟩ (⟨l₁, reduced_of_reduced_append_left hl⟩ * ⟨l₂, reduced_of_reduced_append_right hl⟩) := coprod.append_eq_mul _ lemma of'_eq_of_pow (i : ι) (n : C∞) : of' i n = (of i) ^ n.to_add := calc of' i n = gpowers_hom _ (of i) n : congr_fun (congr_arg _ (monoid_hom.ext_int rfl)) _ ... = _ : rfl @[simp] lemma nil_eq_one (h): @eq (free_group ι) ⟨[], h⟩ 1 := rfl @[simp] lemma eta (w : free_group ι) : (⟨w.1, w.2⟩ : free_group ι) = w := by cases w; refl lemma of_eq_of' (i : ι) : of i = of' i (of_add 1) := rfl def lift' (f : Π i : ι, C∞ →* M) : free_group ι →* M := coprod.lift f def lift (f : ι → G) : free_group ι →* G := lift' (λ i, gpowers_hom _ (f i)) @[simp] lemma lift'_of' (f : Π i : ι, C∞ →* M) (i : ι) (n : C∞) : lift' f (of' i n) = f i n := by simp [lift', of'] @[simp] lemma lift_of (f : Π i : ι, G) (i : ι) : lift f (of i) = f i := by simp [lift, of_eq_of', gpowers_hom] @[simp] lemma lift'_comp_of' (f : Π i : ι, C∞ →* M) (i : ι) : (lift' f).comp (of' i) = f i := by ext; simp @[elab_as_eliminator] def rec_on' {C : free_group ι → Prop} (g : free_group ι) (h1 : C 1) (hof : ∀ i n, C (of' i n)) (f : Π (i : ι) (n : C∞) (h : free_group ι), C (of' i n) → C h → C (of' i n * h)) : C g := coprod.rec_on g h1 hof f @[elab_as_eliminator] lemma rec_on {C : free_group ι → Prop} (g : free_group ι) (h1 : C (1 : free_group ι)) (hof : ∀ i, C (of i)) (hinv : ∀ i, C ((of i)⁻¹)) (hmul : Π (a b : free_group ι), C a → C b → C (a * b)) : C g := free_group.rec_on' g h1 (begin assume i n, refine int.induction_on n _ _ _, { change (0 : ℤ) with (1 : C∞), simpa }, { assume n h, change (n + 1 : ℤ) with (of_add (n + 1 : ℤ)), rw [of_add_add, monoid_hom.map_mul], exact hmul _ _ h (hof _) }, { assume n h, change (-n - 1 : ℤ) with (of_add (-n - 1 : ℤ)), erw [sub_eq_add_neg, of_add_add, of_add_neg, of_add_neg, monoid_hom.map_mul, monoid_hom.map_inv (of' i) (of_add 1), ← of_eq_of'], exact hmul _ _ h (hinv _) }, end) (λ i a h , hmul _ _) lemma hom_ext {f g : free_group ι →* M} (h : ∀ i, f (of i) = g (of i)) : f = g := coprod.hom_ext (λ i, monoid_hom.ext_int (h i)) @[simp] lemma lift_of₂ : lift (of : ι → free_group ι) = monoid_hom.id _ := free_group.hom_ext (by simp) lemma lift'_eq_lift (f : Π i : ι, C∞ →* G) : lift' f = lift (λ i, f i (of_add 1)) := hom_ext (λ i, by rw [lift_of, of_eq_of', lift'_of']) section map variables {κ : Type*} [decidable_eq κ] (f : ι → κ) def map : free_group ι →* free_group κ := lift' (λ i, of' (f i)) @[simp] lemma map_of (i : ι): map f (of i) = of (f i) := by simp [map, of_eq_of'] @[simp] lemma map_of' (i : ι) (n : C∞) : map f (of' i n) = of' (f i) n := by simp [map, of_eq_of'] @[simp] lemma map_comp_of' (i : ι) : (map f).comp (of' i) = of' (f i) := by simp [map, of_eq_of'] lemma lift_comp_map (g : κ → G) : (lift g).comp (map f) = lift (λ x, g (f x)) := hom_ext (by simp) lemma lift_map (g : κ → G) (w : free_group ι) : lift g (map f w) = lift (λ x, g (f x)) w := by rw [← monoid_hom.comp_apply, lift_comp_map] @[simp] lemma map_id : map (λ x, x : ι → ι) = monoid_hom.id _ := free_group.hom_ext (by simp [map, of_eq_of']) end map protected def embedding (e : α ↪ β) : free_group α →* free_group β := { to_fun := λ x, ⟨pre.embedding e.1 (λ _, monoid_hom.id _) x.1, pre.reduced_embedding _ e.2 _ (by simp) x.2⟩, map_one' := rfl, map_mul' := λ _ _, subtype.eq (by dsimp; exact pre.embedding_mul e.1 e.2 (λ _, monoid_hom.id _) (by simp)) } @[simp] lemma embedding_of' (e : α ↪ β) (a : α) (n : C∞) : free_group.embedding e (of' a n) = of' (e a) n := subtype.eq begin simp [free_group.embedding, of', coprod.of, coprod.pre.of, pre.embedding], split_ifs; simp end @[simp] lemma embedding_of (e : α ↪ β) (a : α) : free_group.embedding e (of a) = of (e a) := by simp [of_eq_of'] @[simp] lemma embedding_id : free_group.embedding (embedding.refl α) = monoid_hom.id _ := free_group.hom_ext (λ _, by simp) @[simp] lemma embedding_trans (e₁ : α ↪ β) (e₂ : β ↪ γ) : free_group.embedding (e₁.trans e₂) = (free_group.embedding e₂).comp (free_group.embedding e₁) := free_group.hom_ext (λ _, by simp) protected def equiv (e : α ≃ β) : free_group α ≃* free_group β := { to_fun := free_group.embedding e.to_embedding, inv_fun := free_group.embedding e.symm.to_embedding, left_inv := λ x, begin rw [← monoid_hom.comp_apply], conv_rhs { rw ← monoid_hom.id_apply x }, refine congr_fun (congr_arg _ (free_group.hom_ext (by simp))) _ end, right_inv := λ x, begin rw [← monoid_hom.comp_apply], conv_rhs { rw ← monoid_hom.id_apply x }, refine congr_fun (congr_arg _ (free_group.hom_ext (by simp))) _ end, map_mul' := by simp } @[simp] lemma equiv_refl : free_group.equiv (equiv.refl α) = mul_equiv.refl _ := by ext; simp [free_group.equiv] @[simp] lemma equiv_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : free_group.equiv (e₁.trans e₂) = (free_group.equiv e₁).trans (free_group.equiv e₂) := by ext; simp [free_group.equiv] @[simp] lemma equiv_of' (e : α ≃ β) (a : α) (n : C∞) : free_group.equiv e (of' a n) = of' (e a) n := by ext; simp [free_group.equiv] @[simp] lemma equiv_of (e : α ≃ β) (a : α) : free_group.equiv e (of a) = of (e a) := by simp [free_group.equiv] def exp_sum (i : ι) : free_group ι →* C∞ := free_group.lift' (λ j, if i = j then monoid_hom.id _ else 1) @[simp] def exp_sum_of' (t i : ι) (n : C∞) : exp_sum t (of' i n) = if t = i then n else 1 := by simp [exp_sum]; split_ifs; simp @[simp] def exp_sum_of (t i : ι) : exp_sum t (of i) = if t = i then of_add (1 : ℤ) else 1 := by simp [exp_sum]; split_ifs; simp [of_eq_of', *] end free_group
283df630bec22cf94e2a424afb09b6a2c47493e8
0bd6c950c82dcba3e46dc8d8acb5ecc60b917520
/EulerPartition.lean
76125836e89b30ce30d43230dcc1499020fedf9d
[]
no_license
truonghoangle/formalabstracts
976dbbdede5c71346a3c534a8f319456248d4610
b889ec60143315053a51b1829a5dc4d82ba503b3
refs/heads/master
1,584,899,948,798
1,537,184,894,000
1,537,184,894,000
140,428,980
0
0
null
null
null
null
UTF-8
Lean
false
false
434
lean
import data.set.finite data.multiset open set finset variable α : Type def square (n:ℕ ):multiset ℕ :=multiset.join(multiset.repeat (multiset.range (n+1)) (n+1)) theorem Euler_Partition (n :ℕ): (multiset.filter (λ s:multiset ℕ , multiset.sum (s.map (λ i,i)) =n ∧ (∀ i, i∈ s→ i % 2=1)) (multiset.powerset (square n))).card = (filter (λ s:finset ℕ, s.sum (λ i,i)=n) (powerset(range (n+1)))).card:= sorry
2a2c65c15678675f08c4d34a3990653da48a7245
618003631150032a5676f229d13a079ac875ff77
/src/meta/expr.lean
de514c49c4cd9c617f4d9e7035c13d491ec6a3e7
[ "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
33,075
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
ead7a4ff22edb67e4ebd520683a0869229a14a6f
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/test/aime-1984-p1.lean
7c1732511a2dbc2760148ae3c0817d2e4a55c160
[ "Apache-2.0", "MIT" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
455
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.nat.basic import data.finset.basic import algebra.big_operators.basic open_locale big_operators example (u : ℕ → ℕ) (h₀ : ∀ n, u (n + 1) = u n + 1) (h₁ : ∑ k in finset.erase (finset.range 99) 0, u k = 137) : ∑ k in finset.erase (finset.range 50) 0, u (2*k) = 93:= begin sorry end
6dc7e98f5530a6a7f3cfd3e6f6795a1b63df94bb
f07ebb00c1b0eed4d4e2df146b6ab5d8aa10802d
/ch4.lean
aba03d8c41a2e278f6eff776920431a19c02ca27
[]
no_license
jgarte/theorem-proving-in-lean
7762e7339ef94269f04e2d8c89ccdcc77053204f
4b7b62f3ca82d4463f6e607e0ef974c9577a5b7e
refs/heads/master
1,650,893,202,520
1,587,934,185,000
1,587,934,185,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,712
lean
-- Chapter 4 -- 1. variables (α : Type) (p q : α → Prop) -- naming: eq = equivalence. theorem eq1 : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume h : (∀ x, p x ∧ q x), and.intro (assume z : α, (h z).left) (assume z : α, (h z).right)) (assume h : (∀ x, p x) ∧ (∀ x, q x), show (∀ x, p x ∧ q x), from assume z : α, and.intro (h.left z) (h.right z)) theorem eq2 : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := assume h₁ : (∀ x, p x → q x), assume h₂ : (∀ x, p x), assume z : α, (h₁ z) (h₂ z) theorem eq3 : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := assume h₁ : (∀ x, p x) ∨ (∀ x, q x), assume z : α, or.elim h₁ (assume hpx : (∀ x, p x), or.inl (hpx z)) (assume hqx : (∀ x, q x), or.inr (hqx z)) -- 2. -- variables (α : Type) (p q : α → Prop) variable r : Prop open classical --naming: two{1,2,3} theorem two1 : α → ((∀ x : α, r) ↔ r) := (assume z : α, iff.intro (assume h₁ : (∀ x : α, r), h₁ z) (assume hr : r, assume z : α, hr)) theorem two2 : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro (assume h₁ : (∀ x, p x ∨ r), or.elim (em r) (assume hr : r, or.inr hr) (assume hnr : ¬r, -- this next bit took an hour. my god. or.inl (assume z : α, (h₁ z).elim (assume hpz : p z, hpz) (assume hr : r, absurd hr hnr)))) (assume h₂ : (∀ x, p x) ∨ r, h₂.elim (assume hpx : ∀ x, p x, assume z : α, or.inl (hpx z)) (assume hr : r, assume z : α, or.inr hr)) theorem two3 : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro (assume h₁ : (∀ x, r → p x), show (r → ∀ x, p x), from assume hr : r, assume z : α, have hpz : p z, from (h₁ z) hr, hpz) (assume h₂ : (r → ∀ x, p x), show (∀ x, r → p x), from assume z : α, assume hr : r, have hpz : p z, from (h₂ hr) z, hpz) -- 3. Barber Paradox variables (men : Type) (barber : men) variable (shaves : men → men → Prop) -- theorem barber1 (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := -- -- 4 / 5. -- namespace hidden -- def divides (m n : ℕ) : Prop := ∃ k, m * k = n -- instance : has_dvd nat := ⟨divides⟩ -- def even (n : ℕ) : Prop := 2 ∣ n -- You can enter the '∣' character by typing \mid -- section -- variables m n : ℕ -- #check m ∣ n -- #check m^n -- #check even (m^n +3) -- end -- end hidden -- def prime (n : ℕ) : Prop := sorry -- def infinitely_many_primes : Prop := sorry -- def Fermat_prime (n : ℕ) : Prop := sorry -- def infinitely_many_Fermat_primes : Prop := sorry -- def goldbach_conjecture : Prop := sorry -- def Goldbach's_weak_conjecture : Prop := sorry -- def Fermat's_last_theorem : Prop := sorry -- -- 6. -- variables (real : Type) [ordered_ring real] -- variables (log exp : real → real) -- variable log_exp_eq : ∀ x, log (exp x) = x -- variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x -- variable exp_pos : ∀ x, exp x > 0 -- variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- -- this ensures the assumptions are available in tactic proofs -- include log_exp_eq exp_log_eq exp_pos exp_add -- example (x y z : real) : -- exp (x + y + z) = exp x * exp y * exp z := -- by rw [exp_add, exp_add] -- example (y : real) (h : y > 0) : exp (log y) = y := -- exp_log_eq h -- theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : -- log (x * y) = log x + log y := -- sorry -- -- 7. -- #check sub_self -- example (x : ℤ) : x * 0 = 0 := -- sorry
21e332769d153c1ba60528d544e4ebf897f15d95
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/group_power/lemmas.lean
ec04d26d5f4d95c56c7a70c436f2b37f286ab568
[ "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
32,897
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.group_power.basic import algebra.invertible import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import data.equiv.mul_add import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a := @list.prod_repeat (multiplicative A) _ @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n instance invertible_pow (m : M) [invertible m] (n : ℕ) : invertible (m ^ n) := { inv_of := ⅟ m ^ n, inv_of_mul_self := by rw [← (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow], mul_inv_of_self := by rw [← (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] } lemma inv_of_pow (m : M) [invertible m] (n : ℕ) [invertible (m ^ n)] : ⅟(m ^ n) = ⅟m ^ n := @invertible_unique M _ (m ^ n) (m ^ n) rfl ‹_› (invertible_pow m n) lemma is_unit.pow {m : M} (n : ℕ) : is_unit m → is_unit (m ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ /-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/ def invertible_of_pow_succ_eq_one (x : M) (n : ℕ) (hx : x ^ n.succ = 1) : invertible x := ⟨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hx⟩ /-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/ def invertible_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : invertible x := begin apply invertible_of_pow_succ_eq_one x (n - 1), convert hx, exact nat.sub_add_cancel (nat.succ_le_of_lt hn), end lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin haveI := invertible_of_pow_eq_one x n hx hn, exact is_unit_of_invertible x end end monoid theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n := by cases n; simp lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := by simpa only [sub_eq_add_neg] using @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add, gpow_bit0, gpow_one] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := @gpow_bit1 (multiplicative A) _ @[simp] theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] @[simp] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic` with their friends) because they require facts from `data.int.basic`-/ open int lemma gsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k •ℤ a := begin lift k to ℕ using int.le_of_lt hk, apply nsmul_pos ha, exact coe_nat_pos.mp hk, end theorem gsmul_le_gsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℤ a ≤ m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... ≤ n •ℤ a + (m - n) •ℤ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } theorem gsmul_lt_gsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n •ℤ a < m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... < n •ℤ a + (m - n) •ℤ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } lemma abs_nsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℕ) (a : α) : abs (n •ℕ a) = n •ℕ abs a := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_gsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℤ) (a : α) : abs (n •ℤ a) = (abs n) •ℤ abs a := begin by_cases n0 : 0 ≤ n, { lift n to ℕ using n0, simp only [abs_nsmul, coe_nat_abs, gsmul_coe_nat] }, { lift (- n) to ℕ using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h, rw [← abs_neg (n •ℤ a), ← neg_gsmul, ← abs_neg n, ← h], convert abs_nsmul m _, simp only [coe_nat_abs, gsmul_coe_nat] }, end lemma abs_add_eq_add_abs_le {α : Type*} [linear_ordered_add_comm_group α] {a b : α} (hle : a ≤ b) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases a0 : 0 ≤ a; by_cases b0 : 0 ≤ b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : α) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim }, any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] }, obtain F := (not_le.mp a0), have : (abs (a + b) = -a + b ↔ b ≤ 0) ↔ (abs (a + b) = abs a + abs b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0), { simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] }, refine this.mp ⟨λ h, _, λ h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]⟩, by_cases ba : a + b ≤ 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : α) _).elim, rw [abs_of_pos (not_le.mp ba), add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at F } end lemma abs_add_eq_add_abs_iff {α : Type*} [linear_ordered_add_comm_group α] (a b : α) : abs (a + b) = abs a + abs b ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases ab : a ≤ b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm, @and.comm (b ≤ 0 ) _] } end end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem gsmul_le_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a ≤ m •ℤ a ↔ n ≤ m := begin refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h) end theorem gsmul_lt_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a < m •ℤ a ↔ n < m := begin refine ⟨λ h, _, gsmul_lt_gsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h) end theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a ≤ m •ℕ a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a < m •ℕ a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [pow_succ', pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] section ordered_semiring variable [ordered_semiring R] /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (Hsqr' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsqr H)) Hsqr, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsqr' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_lt_pow_iff_of_lt_one {a : R} {n m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : ℕ} @[simp] lemma abs_pow (a : R) (n : ℕ) : abs (a ^ n) = abs a ^ n := abs_hom.to_monoid_hom.map_pow a n @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ h, mul_neg_of_neg_of_pos h (pow_bit0_pos h.ne _)⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff theorem pow_even_nonneg (a : R) (hn : even n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k theorem pow_even_pos (ha : a ≠ 0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k theorem pow_odd_nonneg (ha : 0 ≤ a) (hn : odd n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonneg_iff.mpr ha theorem pow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_pos_iff.mpr ha theorem pow_odd_nonpos (ha : a ≤ 0) (hn : odd n) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha theorem pow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma pow_even_abs (a : R) {p : ℕ} (hp : even p) : abs a ^ p = a ^ p := begin rw [←abs_pow, abs_eq_self], exact pow_even_nonneg _ hp end @[simp] lemma pow_bit0_abs (a : R) (p : ℕ) : abs a ^ bit0 p = a ^ bit0 p := pow_even_abs _ (even_bit0 _) lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (pow_two u).symm ▸ units_mul_self u lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] @[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] lemma abs_le_self_pow_two (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_pow_two a, pow_two], norm_cast, apply nat.le_mul_self } lemma le_self_pow_two (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_pow_two _) end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : gpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (gpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n •ℕ x := rfl @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : gmultiples_hom A x n = n •ℤ x := rfl @[simp] lemma gmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (gmultiples_hom A).symm f = f 1 := rfl lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← gpowers_hom_symm_apply, ← gpowers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mint [group M] ⦃f g : multiplicative ℤ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mint, g.apply_mint, h] lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n •ℕ (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n •ℤ (f 1) := by rw [← gmultiples_hom_symm_apply, ← gmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/ def gpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_gpow], ..gpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/ def gmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [gsmul_add], ..gmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma gpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : gpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma gpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (gpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n •ℕ x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma gmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : gmultiples_add_hom A x n = n •ℤ x := rfl @[simp] lemma gmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (gmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
e61b82450c660ce65335f3651c7e17f0883f8eb6
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/archive/imo/imo1998_q2.lean
7199b8ac8c23cc5dacfc1c37a98763ac0ca48906
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,574
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.fintype.basic import data.int.parity import algebra.big_operators.order import tactic.ring import tactic.noncomm_ring /-! # IMO 1998 Q2 In a competition, there are `a` contestants and `b` judges, where `b ≥ 3` is an odd integer. Each judge rates each contestant as either "pass" or "fail". Suppose `k` is a number such that, for any two judges, their ratings coincide for at most `k` contestants. Prove that `k / a ≥ (b - 1) / (2b)`. ## Solution The problem asks us to think about triples consisting of a contestant and two judges whose ratings agree for that contestant. We thus consider the subset `A ⊆ C × JJ` of all such incidences of agreement, where `C` and `J` are the sets of contestants and judges, and `JJ = J × J − {(j, j)}`. We have natural maps: `left : A → C` and `right: A → JJ`. We count the elements of `A` in two ways: as the sum of the cardinalities of the fibres of `left` and as the sum of the cardinalities of the fibres of `right`. We obtain an upper bound on the cardinality of `A` from the count for `right`, and a lower bound from the count for `left`. These two bounds combine to the required result. First consider the map `right : A → JJ`. Since the size of any fibre over a point in JJ is bounded by `k` and since `|JJ| = b^2 - b`, we obtain the upper bound: `|A| ≤ k(b^2−b)`. Now consider the map `left : A → C`. The fibre over a given contestant `c ∈ C` is the set of ordered pairs of (distinct) judges who agree about `c`. We seek to bound the cardinality of this fibre from below. Minimum agreement for a contestant occurs when the judges' ratings are split as evenly as possible. Since `b` is odd, this occurs when they are divided into groups of size `(b−1)/2` and `(b+1)/2`. This corresponds to a fibre of cardinality `(b-1)^2/2` and so we obtain the lower bound: `a(b-1)^2/2 ≤ |A|`. Rearranging gives the result. -/ open_locale classical noncomputable theory /-- An ordered pair of judges. -/ abbreviation judge_pair (J : Type*) := J × J /-- A triple consisting of contestant together with an ordered pair of judges. -/ abbreviation agreed_triple (C J : Type*) := C × (judge_pair J) variables {C J : Type*} (r : C → J → Prop) /-- The first judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₁ : judge_pair J → J := prod.fst /-- The second judge from an ordered pair of judges. -/ abbreviation judge_pair.judge₂ : judge_pair J → J := prod.snd /-- The proposition that the judges in an ordered pair are distinct. -/ abbreviation judge_pair.distinct (p : judge_pair J) := p.judge₁ ≠ p.judge₂ /-- The proposition that the judges in an ordered pair agree about a contestant's rating. -/ abbreviation judge_pair.agree (p : judge_pair J) (c : C) := r c p.judge₁ ↔ r c p.judge₂ /-- The contestant from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.contestant : agreed_triple C J → C := prod.fst /-- The ordered pair of judges from the triple consisting of a contestant and an ordered pair of judges. -/ abbreviation agreed_triple.judge_pair : agreed_triple C J → judge_pair J := prod.snd @[simp] lemma judge_pair.agree_iff_same_rating (p : judge_pair J) (c : C) : p.agree r c ↔ (r c p.judge₁ ↔ r c p.judge₂) := iff.rfl /-- The set of contestants on which two judges agree. -/ def agreed_contestants [fintype C] (p : judge_pair J) : finset C := finset.univ.filter (λ c, p.agree r c) section variables [fintype J] [fintype C] /-- All incidences of agreement. -/ def A : finset (agreed_triple C J) := finset.univ.filter (λ (a : agreed_triple C J), a.judge_pair.agree r a.contestant ∧ a.judge_pair.distinct) lemma A_maps_to_off_diag_judge_pair (a : agreed_triple C J) : a ∈ A r → a.judge_pair ∈ finset.off_diag (@finset.univ J _) := by simp [A, finset.mem_off_diag] lemma A_fibre_over_contestant (c : C) : finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct) = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).image prod.snd := begin ext p, simp only [A, finset.mem_univ, finset.mem_filter, finset.mem_image, true_and, exists_prop], split, { rintros ⟨h₁, h₂⟩, refine ⟨(c, p), _⟩, finish, }, { intros h, finish, }, end lemma A_fibre_over_contestant_card (c : C) : (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card = ((A r).filter (λ (a : agreed_triple C J), a.contestant = c)).card := by { rw A_fibre_over_contestant r, apply finset.card_image_of_inj_on, tidy, } lemma A_fibre_over_judge_pair {p : judge_pair J} (h : p.distinct) : agreed_contestants r p = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).image agreed_triple.contestant := begin dunfold A agreed_contestants, ext c, split; intros h, { rw finset.mem_image, refine ⟨⟨c, p⟩, _⟩, finish, }, { finish, }, end lemma A_fibre_over_judge_pair_card {p : judge_pair J} (h : p.distinct) : (agreed_contestants r p).card = ((A r).filter(λ (a : agreed_triple C J), a.judge_pair = p)).card := by { rw A_fibre_over_judge_pair r h, apply finset.card_image_of_inj_on, tidy, } lemma A_card_upper_bound {k : ℕ} (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (A r).card ≤ k * ((fintype.card J) * (fintype.card J) - (fintype.card J)) := begin change _ ≤ k * ((finset.card _ ) * (finset.card _ ) - (finset.card _ )), rw ← finset.off_diag_card, apply finset.card_le_mul_card_image_of_maps_to (A_maps_to_off_diag_judge_pair r), intros p hp, have hp' : p.distinct, { simp [finset.mem_off_diag] at hp, exact hp, }, rw ← A_fibre_over_judge_pair_card r hp', apply hk, exact hp', end end lemma add_sq_add_sq_sub {α : Type*} [ring α] (x y : α) : (x + y) * (x + y) + (x - y) * (x - y) = 2*x*x + 2*y*y := by noncomm_ring lemma norm_bound_of_odd_sum {x y z : ℤ} (h : x + y = 2*z + 1) : 2*z*z + 2*z + 1 ≤ x*x + y*y := begin suffices : 4*z*z + 4*z + 1 + 1 ≤ 2*x*x + 2*y*y, { rw ← mul_le_mul_left (@zero_lt_two _ _ int.nontrivial), convert this; ring, }, have h' : (x + y) * (x + y) = 4*z*z + 4*z + 1, { rw h, ring, }, rw [← add_sq_add_sq_sub, h', add_le_add_iff_left], suffices : 0 < (x - y) * (x - y), { apply int.add_one_le_of_lt this, }, apply mul_self_pos, rw sub_ne_zero, apply int.ne_of_odd_sum ⟨z, h⟩, end section variables [fintype J] lemma judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z + 2*z + 1 ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card := begin let x := (finset.univ.filter (λ j, r c j)).card, let y := (finset.univ.filter (λ j, ¬ r c j)).card, have h : (finset.univ.filter (λ (p : judge_pair J), p.agree r c)).card = x*x + y*y, { simp [← finset.filter_product_card], }, rw h, apply int.le_of_coe_nat_le_coe_nat, simp only [int.coe_nat_add, int.coe_nat_mul], apply norm_bound_of_odd_sum, suffices : x + y = 2*z + 1, { simp [← int.coe_nat_add, this], }, rw [finset.filter_card_add_filter_neg_card_eq_card, ← hJ], refl, end lemma distinct_judge_pairs_card_lower_bound {z : ℕ} (hJ : fintype.card J = 2*z + 1) (c : C) : 2*z*z ≤ (finset.univ.filter (λ (p : judge_pair J), p.agree r c ∧ p.distinct)).card := begin let s := finset.univ.filter (λ (p : judge_pair J), p.agree r c), let t := finset.univ.filter (λ (p : judge_pair J), p.distinct), have hs : 2*z*z + 2*z + 1 ≤ s.card, { exact judge_pairs_card_lower_bound r hJ c, }, have hst : s \ t = finset.univ.diag, { ext p, split; intros, { finish, }, { suffices : p.judge₁ = p.judge₂, { simp [this], }, finish, }, }, have hst' : (s \ t).card = 2*z + 1, { rw [hst, finset.diag_card, ← hJ], refl, }, rw [finset.filter_and, ← finset.sdiff_sdiff_self_left s t, finset.card_sdiff], { rw hst', rw add_assoc at hs, apply nat.le_sub_right_of_add_le hs, }, { apply finset.sdiff_subset, }, end lemma A_card_lower_bound [fintype C] {z : ℕ} (hJ : fintype.card J = 2*z + 1) : 2*z*z * (fintype.card C) ≤ (A r).card := begin have h : ∀ a, a ∈ A r → prod.fst a ∈ @finset.univ C _, { intros, apply finset.mem_univ, }, apply finset.mul_card_image_le_card_of_maps_to h, intros c hc, rw ← A_fibre_over_contestant_card, apply distinct_judge_pairs_card_lower_bound r hJ, end end local notation x `/` y := (x : ℚ) / y lemma clear_denominators {a b k : ℕ} (ha : 0 < a) (hb : 0 < b) : (b - 1) / (2 * b) ≤ k / a ↔ (b - 1) * a ≤ k * (2 * b) := by rw div_le_div_iff; norm_cast; simp [ha, hb] theorem imo1998_q2 [fintype J] [fintype C] (a b k : ℕ) (hC : fintype.card C = a) (hJ : fintype.card J = b) (ha : 0 < a) (hb : odd b) (hk : ∀ (p : judge_pair J), p.distinct → (agreed_contestants r p).card ≤ k) : (b - 1) / (2 * b) ≤ k / a := begin rw clear_denominators ha (nat.odd_gt_zero hb), obtain ⟨z, hz⟩ := hb, rw hz at hJ, rw hz, have h := le_trans (A_card_lower_bound r hJ) (A_card_upper_bound r hk), rw [hC, hJ] at h, -- We are now essentially done; we just need to bash `h` into exactly the right shape. have hl : k * ((2 * z + 1) * (2 * z + 1) - (2 * z + 1)) = (k * (2 * (2 * z + 1))) * z, { simp only [add_mul, two_mul, mul_comm, mul_assoc], finish, }, have hr : 2 * z * z * a = 2 * z * a * z, { ring, }, rw [hl, hr] at h, cases z, { simp, }, { exact le_of_mul_le_mul_right h z.succ_pos, }, end
2aa5a4e49b920f647fb6af3160565a61db098b47
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/measure_theory/measure/content.lean
3228c5593b5516196a4af4ccc4067f3e74bdedb9
[ "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
16,937
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 -/ import measure_theory.measure.measure_space import measure_theory.measure.regular import topology.opens import topology.compacts /-! # Contents In this file we work with *contents*. A content `λ` is a function from a certain class of subsets (such as the the compact subsets) to `ℝ≥0` that is * additive: If `K₁` and `K₂` are disjoint sets in the domain of `λ`, then `λ(K₁ ∪ K₂) = λ(K₁) + λ(K₂)`; * subadditive: If `K₁` and `K₂` are in the domain of `λ`, then `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)`; * monotone: If `K₁ ⊆ K₂` are in the domain of `λ`, then `λ(K₁) ≤ λ(K₂)`. We show that: * Given a content `λ` on compact sets, let us define a function `λ*` on open sets, by letting `λ* U` be the supremum of `λ K` for `K` included in `U`. This is a countably subadditive map that vanishes at `∅`. In Halmos (1950) this is called the *inner content* `λ*` of `λ`, and formalized as `inner_content`. * Given an inner content, we define an outer measure `μ*`, by letting `μ* E` be the infimum of `λ* U` over the open sets `U` containing `E`. This is indeed an outer measure. It is formalized as `outer_measure`. * Restricting this outer measure to Borel sets gives a regular measure `μ`. We define bundled contents as `content`. In this file we only work on contents on compact sets, and inner contents on open sets, and both contents and inner contents map into the extended nonnegative reals. However, in other applications other choices can be made, and it is not a priori clear what the best interface should be. ## Main definitions For `μ : content G`, we define * `μ.inner_content` : the inner content associated to `μ`. * `μ.outer_measure` : the outer measure associated to `μ`. * `μ.measure` : the Borel measure associated to `μ`. We prove that, on a locally compact space, the measure `μ.measure` is regular. ## References * Paul Halmos (1950), Measure Theory, §53 * <https://en.wikipedia.org/wiki/Content_(measure_theory)> -/ universe variables u v w noncomputable theory open set topological_space open_locale nnreal ennreal namespace measure_theory variables {G : Type w} [topological_space G] /-- A content is an additive function on compact sets taking values in `ℝ≥0`. It is a device from which one can define a measure. -/ structure content (G : Type w) [topological_space G] := (to_fun : compacts G → ℝ≥0) (mono' : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → to_fun K₁ ≤ to_fun K₂) (sup_disjoint' : ∀ (K₁ K₂ : compacts G), disjoint K₁.1 K₂.1 → to_fun (K₁ ⊔ K₂) = to_fun K₁ + to_fun K₂) (sup_le' : ∀ (K₁ K₂ : compacts G), to_fun (K₁ ⊔ K₂) ≤ to_fun K₁ + to_fun K₂) instance : inhabited (content G) := ⟨{ to_fun := λ K, 0, mono' := by simp, sup_disjoint' := by simp, sup_le' := by simp }⟩ /-- Although the `to_fun` field of a content takes values in `ℝ≥0`, we register a coercion to functions taking values in `ℝ≥0∞` as most constructions below rely on taking suprs and infs, which is more convenient in a complete lattice, and aim at constructing a measure. -/ instance : has_coe_to_fun (content G) := ⟨_, λ μ s, (μ.to_fun s : ℝ≥0∞)⟩ namespace content variable (μ : content G) lemma apply_eq_coe_to_fun (K : compacts G) : μ K = μ.to_fun K := rfl lemma mono (K₁ K₂ : compacts G) (h : K₁.1 ⊆ K₂.1) : μ K₁ ≤ μ K₂ := by simp [apply_eq_coe_to_fun, μ.mono' _ _ h] lemma sup_disjoint (K₁ K₂ : compacts G) (h : disjoint K₁.1 K₂.1) : μ (K₁ ⊔ K₂) = μ K₁ + μ K₂ := by simp [apply_eq_coe_to_fun, μ.sup_disjoint' _ _ h] lemma sup_le (K₁ K₂ : compacts G) : μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂ := by { simp only [apply_eq_coe_to_fun], norm_cast, exact μ.sup_le' _ _ } lemma lt_top (K : compacts G) : μ K < ∞ := ennreal.coe_lt_top lemma empty : μ ⊥ = 0 := begin have := μ.sup_disjoint' ⊥ ⊥, simpa [apply_eq_coe_to_fun] using this, end /-- Constructing the inner content of a content. From a content defined on the compact sets, we obtain a function defined on all open sets, by taking the supremum of the content of all compact subsets. -/ def inner_content (U : opens G) : ℝ≥0∞ := ⨆ (K : compacts G) (h : K.1 ⊆ U), μ K lemma le_inner_content (K : compacts G) (U : opens G) (h2 : K.1 ⊆ U) : μ K ≤ μ.inner_content U := le_supr_of_le K $ le_supr _ h2 lemma inner_content_le (U : opens G) (K : compacts G) (h2 : (U : set G) ⊆ K.1) : μ.inner_content U ≤ μ K := bsupr_le $ λ K' hK', μ.mono _ _ (subset.trans hK' h2) lemma inner_content_of_is_compact {K : set G} (h1K : is_compact K) (h2K : is_open K) : μ.inner_content ⟨K, h2K⟩ = μ ⟨K, h1K⟩ := le_antisymm (bsupr_le $ λ K' hK', μ.mono _ ⟨K, h1K⟩ hK') (μ.le_inner_content _ _ subset.rfl) lemma inner_content_empty : μ.inner_content ∅ = 0 := begin refine le_antisymm _ (zero_le _), rw ←μ.empty, refine bsupr_le (λ K hK, _), have : K = ⊥, { ext1, rw [subset_empty_iff.mp hK, compacts.bot_val] }, rw this, refl' end /-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/ lemma inner_content_mono ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ := supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2 lemma inner_content_exists_compact {U : opens G} (hU : μ.inner_content U < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ K : compacts G, K.1 ⊆ U ∧ μ.inner_content U ≤ μ K + ε := begin have h'ε := ennreal.zero_lt_coe_iff.2 hε, cases le_or_lt (μ.inner_content U) ε, { exact ⟨⊥, empty_subset _, le_trans h (le_add_of_nonneg_left (zero_le _))⟩ }, have := ennreal.sub_lt_self (ne_of_lt hU) (ne_of_gt $ lt_trans h'ε h) h'ε, conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this, rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩, rw [← ennreal.sub_le_iff_le_add], exact le_of_lt h2U end /-- The inner content of a supremum of opens is at most the sum of the individual inner contents. -/ lemma inner_content_Sup_nat [t2_space G] (U : ℕ → opens G) : μ.inner_content (⨆ (i : ℕ), U i) ≤ ∑' (i : ℕ), μ.inner_content (U i) := begin have h3 : ∀ (t : finset ℕ) (K : ℕ → compacts G), μ (t.sup K) ≤ t.sum (λ i, μ (K i)), { intros t K, refine finset.induction_on t _ _, { simp only [μ.empty, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty], }, { intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn], exact le_trans (μ.sup_le _ _) (add_le_add_left ih _) }}, refine bsupr_le (λ K hK, _), rcases is_compact.elim_finite_subcover K.2 _ (λ i, (U i).prop) _ with ⟨t, ht⟩, swap, { convert hK, rw [opens.supr_def, subtype.coe_mk] }, rcases K.2.finite_compact_cover t (coe ∘ U) (λ i _, (U _).prop) (by simp only [ht]) with ⟨K', h1K', h2K', h3K'⟩, let L : ℕ → compacts G := λ n, ⟨K' n, h1K' n⟩, convert le_trans (h3 t L) _, { ext1, simp only [h3K', compacts.finset_sup_val, finset.sup_eq_supr, set.supr_eq_Union] }, refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t), intros i hi, refine le_trans _ (le_supr _ (L i)), refine le_trans _ (le_supr _ (h2K' i)), refl' end /-- The inner content of a union of sets is at most the sum of the individual inner contents. This is the "unbundled" version of `inner_content_Sup_nat`. It required for the API of `induced_outer_measure`. -/ lemma inner_content_Union_nat [t2_space G] ⦃U : ℕ → set G⦄ (hU : ∀ (i : ℕ), is_open (U i)) : μ.inner_content ⟨⋃ (i : ℕ), U i, is_open_Union hU⟩ ≤ ∑' (i : ℕ), μ.inner_content ⟨U i, hU i⟩ := by { have := μ.inner_content_Sup_nat (λ i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this } lemma inner_content_comap (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (U : opens G) : μ.inner_content (U.comap f.continuous) = μ.inner_content U := begin refine supr_congr _ ((compacts.equiv f).surjective) _, intro K, refine supr_congr_Prop image_subset_iff _, intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv], apply h, end @[to_additive] lemma is_mul_left_invariant_inner_content [group G] [topological_group G] (h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G) (U : opens G) : μ.inner_content (U.comap $ continuous_mul_left g) = μ.inner_content U := by convert μ.inner_content_comap (homeomorph.mul_left g) (λ K, h g) U @[to_additive] lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G] (h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (K : compacts G) (hK : 0 < μ K) (U : opens G) (hU : (U : set G).nonempty) : 0 < μ.inner_content U := begin have : (interior (U : set G)).nonempty, rwa [U.prop.interior_eq], rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩, suffices : μ K ≤ s.card * μ.inner_content U, { exact (ennreal.mul_pos.mp $ lt_of_lt_of_le hK this).2 }, have : K.1 ⊆ ↑⨆ (g ∈ s), U.comap $ continuous_mul_left g, { simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] }, refine (μ.le_inner_content _ _ this).trans _, refine (rel_supr_sum (μ.inner_content) (μ.inner_content_empty) (≤) (μ.inner_content_Sup_nat) _ _).trans _, simp only [μ.is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl] end lemma inner_content_mono' ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ := supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2 /-- Extending a content on compact sets to an outer measure on all sets. -/ protected def outer_measure : outer_measure G := induced_outer_measure (λ U hU, μ.inner_content ⟨U, hU⟩) is_open_empty μ.inner_content_empty variables [t2_space G] lemma outer_measure_opens (U : opens G) : μ.outer_measure U = μ.inner_content U := induced_outer_measure_eq' (λ _, is_open_Union) μ.inner_content_Union_nat μ.inner_content_mono U.2 lemma outer_measure_of_is_open (U : set G) (hU : is_open U) : μ.outer_measure U = μ.inner_content ⟨U, hU⟩ := μ.outer_measure_opens ⟨U, hU⟩ lemma outer_measure_le (U : opens G) (K : compacts G) (hUK : (U : set G) ⊆ K.1) : μ.outer_measure U ≤ μ K := (μ.outer_measure_opens U).le.trans $ μ.inner_content_le U K hUK lemma le_outer_measure_compacts (K : compacts G) : μ K ≤ μ.outer_measure K.1 := begin rw [content.outer_measure, induced_outer_measure_eq_infi], { exact le_infi (λ U, le_infi $ λ hU, le_infi $ μ.le_inner_content K ⟨U, hU⟩) }, { exact μ.inner_content_Union_nat }, { exact μ.inner_content_mono } end lemma outer_measure_eq_infi (A : set G) : μ.outer_measure A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), μ.inner_content ⟨U, hU⟩ := induced_outer_measure_eq_infi _ μ.inner_content_Union_nat μ.inner_content_mono A lemma outer_measure_interior_compacts (K : compacts G) : μ.outer_measure (interior K.1) ≤ μ K := le_trans (le_of_eq $ μ.outer_measure_opens (opens.interior K.1)) (μ.inner_content_le _ _ interior_subset) lemma outer_measure_exists_compact {U : opens G} (hU : μ.outer_measure U < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ K : compacts G, K.1 ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure K.1 + ε := begin rw [μ.outer_measure_opens] at hU ⊢, rcases μ.inner_content_exists_compact hU hε with ⟨K, h1K, h2K⟩, exact ⟨K, h1K, le_trans h2K $ add_le_add_right (μ.le_outer_measure_compacts K) _⟩, end lemma outer_measure_exists_open {A : set G} (hA : μ.outer_measure A < ∞) {ε : ℝ≥0} (hε : 0 < ε) : ∃ U : opens G, A ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure A + ε := begin rcases induced_outer_measure_exists_set _ _ μ.inner_content_mono hA.ne hε with ⟨U, hU, h2U, h3U⟩, exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact μ.inner_content_Union_nat end lemma outer_measure_preimage (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (A : set G) : μ.outer_measure (f ⁻¹' A) = μ.outer_measure A := begin refine induced_outer_measure_preimage _ μ.inner_content_Union_nat μ.inner_content_mono _ (λ s, f.is_open_preimage) _, intros s hs, convert μ.inner_content_comap f h ⟨s, hs⟩ end lemma outer_measure_lt_top_of_is_compact [locally_compact_space G] {K : set G} (hK : is_compact K) : μ.outer_measure K < ∞ := begin rcases exists_compact_superset hK with ⟨F, h1F, h2F⟩, calc μ.outer_measure K ≤ μ.outer_measure (interior F) : outer_measure.mono' _ h2F ... ≤ μ ⟨F, h1F⟩ : by apply μ.outer_measure_le ⟨interior F, is_open_interior⟩ ⟨F, h1F⟩ interior_subset ... < ⊤ : μ.lt_top _ end @[to_additive] lemma is_mul_left_invariant_outer_measure [group G] [topological_group G] (h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G) (A : set G) : μ.outer_measure ((λ h, g * h) ⁻¹' A) = μ.outer_measure A := by convert μ.outer_measure_preimage (homeomorph.mul_left g) (λ K, h g) A lemma outer_measure_caratheodory (A : set G) : μ.outer_measure.caratheodory.measurable_set' A ↔ ∀ (U : opens G), μ.outer_measure (U ∩ A) + μ.outer_measure (U \ A) ≤ μ.outer_measure U := begin dsimp [opens], rw subtype.forall, apply induced_outer_measure_caratheodory, apply inner_content_Union_nat, apply inner_content_mono' end @[to_additive] lemma outer_measure_pos_of_is_mul_left_invariant [group G] [topological_group G] (h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (K : compacts G) (hK : 0 < μ K) {U : set G} (h1U : is_open U) (h2U : U.nonempty) : 0 < μ.outer_measure U := by { convert μ.inner_content_pos_of_is_mul_left_invariant h3 K hK ⟨U, h1U⟩ h2U, exact μ.outer_measure_opens ⟨U, h1U⟩ } variables [S : measurable_space G] [borel_space G] include S /-- For the outer measure coming from a content, all Borel sets are measurable. -/ lemma borel_le_caratheodory : S ≤ μ.outer_measure.caratheodory := begin rw [@borel_space.measurable_eq G _ _], refine measurable_space.generate_from_le _, intros U hU, rw μ.outer_measure_caratheodory, intro U', rw μ.outer_measure_of_is_open ((U' : set G) ∩ U) (is_open.inter U'.prop hU), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {L : compacts G // L.1 ⊆ U' ∩ U} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.supr_add], refine supr_le _, rintro ⟨L, hL⟩, simp only [subset_inter_iff] at hL, have : ↑U' \ U ⊆ U' \ L.1 := diff_subset_diff_right hL.2, refine le_trans (add_le_add_left (μ.outer_measure.mono' this) _) _, rw μ.outer_measure_of_is_open (↑U' \ L.1) (is_open.sdiff U'.2 L.2.is_closed), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {M : compacts G // M.1 ⊆ ↑U' \ L.1} := ⟨⟨⊥, empty_subset _⟩⟩, rw [ennreal.add_supr], refine supr_le _, rintro ⟨M, hM⟩, simp only [subset_diff] at hM, have : (L ⊔ M).1 ⊆ U', { simp only [union_subset_iff, compacts.sup_val, hM, hL, and_self] }, rw μ.outer_measure_of_is_open ↑U' U'.2, refine le_trans (ge_of_eq _) (μ.le_inner_content _ _ this), exact μ.sup_disjoint _ _ hM.2.symm, end /-- The measure induced by the outer measure coming from a content, on the Borel sigma-algebra. -/ def measure : measure G := μ.outer_measure.to_measure μ.borel_le_caratheodory lemma measure_apply {s : set G} (hs : measurable_set s) : μ.measure s = μ.outer_measure s := to_measure_apply _ _ hs /-- In a locally compact space, any measure constructed from a content is regular. -/ instance regular [locally_compact_space G] : μ.measure.regular := begin split, { intros K hK, rw [measure_apply _ hK.measurable_set], exact μ.outer_measure_lt_top_of_is_compact hK }, { intros A hA, rw [measure_apply _ hA, outer_measure_eq_infi], refine binfi_le_binfi _, intros U hU, refine infi_le_infi _, intro h2U, rw [measure_apply _ hU.measurable_set, μ.outer_measure_of_is_open U hU], refl' }, { intros U hU, rw [measure_apply _ hU.measurable_set, μ.outer_measure_of_is_open U hU], dsimp only [inner_content], refine bsupr_le (λ K hK, _), refine le_supr_of_le K.1 _, refine le_supr_of_le K.2 _, refine le_supr_of_le hK _, rw [measure_apply _ K.2.measurable_set], apply le_outer_measure_compacts }, end end content end measure_theory
0981eaf003e7734ba4facde73403a9708182b815
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Meta/Match/MatcherInfo.lean
6d9545447c2242e599093e0fa82e95c8732ae7ad
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,719
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.Basic namespace Lean.Meta namespace Match /-- A "matcher" auxiliary declaration has the following structure: - `numParams` parameters - motive - `numDiscrs` discriminators (aka major premises) - `altNumParams.size` alternatives (aka minor premises) where alternative `i` has `altNumParams[i]` parameters - `uElimPos?` is `some pos` when the matcher can eliminate in different universe levels, and `pos` is the position of the universe level parameter that specifies the elimination universe. It is `none` if the matcher only eliminates into `Prop`. -/ structure MatcherInfo where numParams : Nat numDiscrs : Nat altNumParams : Array Nat uElimPos? : Option Nat def MatcherInfo.numAlts (info : MatcherInfo) : Nat := info.altNumParams.size def MatcherInfo.arity (info : MatcherInfo) : Nat := info.numParams + 1 + info.numDiscrs + info.numAlts def MatcherInfo.getMotivePos (info : MatcherInfo) : Nat := info.numParams namespace Extension structure Entry where name : Name info : MatcherInfo structure State where map : SMap Name MatcherInfo := {} instance : Inhabited State := ⟨{}⟩ def State.addEntry (s : State) (e : Entry) : State := { s with map := s.map.insert e.name e.info } def State.switch (s : State) : State := { s with map := s.map.switch } builtin_initialize extension : SimplePersistentEnvExtension Entry State ← registerSimplePersistentEnvExtension { name := `matcher addEntryFn := State.addEntry addImportedFn := fun es => (mkStateFromImportedEntries State.addEntry {} es).switch } def addMatcherInfo (env : Environment) (matcherName : Name) (info : MatcherInfo) : Environment := extension.addEntry env { name := matcherName, info := info } def getMatcherInfo? (env : Environment) (declName : Name) : Option MatcherInfo := (extension.getState env).map.find? declName end Extension def addMatcherInfo (matcherName : Name) (info : MatcherInfo) : MetaM Unit := modifyEnv fun env => Extension.addMatcherInfo env matcherName info end Match export Match (MatcherInfo) def getMatcherInfoCore? (env : Environment) (declName : Name) : Option MatcherInfo := Match.Extension.getMatcherInfo? env declName def getMatcherInfo? [Monad m] [MonadEnv m] (declName : Name) : m (Option MatcherInfo) := return getMatcherInfoCore? (← getEnv) declName def isMatcherCore (env : Environment) (declName : Name) : Bool := getMatcherInfoCore? env declName |>.isSome def isMatcher [Monad m] [MonadEnv m] (declName : Name) : m Bool := return isMatcherCore (← getEnv) declName def isMatcherAppCore (env : Environment) (e : Expr) : Bool := let fn := e.getAppFn if fn.isConst then if let some matcherInfo := getMatcherInfoCore? env fn.constName! then e.getAppNumArgs ≥ matcherInfo.arity else false else false def isMatcherApp [Monad m] [MonadEnv m] (e : Expr) : m Bool := return isMatcherAppCore (← getEnv) e structure MatcherApp where matcherName : Name matcherLevels : Array Level uElimPos? : Option Nat params : Array Expr motive : Expr discrs : Array Expr altNumParams : Array Nat alts : Array Expr remaining : Array Expr def matchMatcherApp? [Monad m] [MonadEnv m] (e : Expr) : m (Option MatcherApp) := do match e.getAppFn with | Expr.const declName declLevels _ => match (← getMatcherInfo? declName) with | none => return none | some info => let args := e.getAppArgs if args.size < info.arity then return none else return some { matcherName := declName matcherLevels := declLevels.toArray uElimPos? := info.uElimPos? params := args.extract 0 info.numParams motive := args[info.getMotivePos] discrs := args[info.numParams + 1 : info.numParams + 1 + info.numDiscrs] altNumParams := info.altNumParams alts := args[info.numParams + 1 + info.numDiscrs : info.numParams + 1 + info.numDiscrs + info.numAlts] remaining := args[info.numParams + 1 + info.numDiscrs + info.numAlts : args.size] } | _ => return none def MatcherApp.toExpr (matcherApp : MatcherApp) : Expr := let result := mkAppN (mkConst matcherApp.matcherName matcherApp.matcherLevels.toList) matcherApp.params let result := mkApp result matcherApp.motive let result := mkAppN result matcherApp.discrs let result := mkAppN result matcherApp.alts mkAppN result matcherApp.remaining end Lean.Meta
1c70ea671956d1457891febb65605102a391859d
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/topology/instances/ennreal.lean
d2c9baecb0c05023bcad35f380d5e9938972378e
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,231
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.nnreal import topology.algebra.ordered.liminf_limsup import topology.metric_space.lipschitz /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} section topological_space open topological_space /-- Topology on `ℝ≥0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞ instance : order_topology ℝ≥0∞ := ⟨rfl⟩ instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference instance : second_countable_topology ℝ≥0∞ := ⟨⟨⋃q ≥ (0:ℚ), {{a : ℝ≥0∞ | a < real.to_nnreal q}, {a : ℝ≥0∞ | ↑(real.to_nnreal q) < a}}, (countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _, le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < real.to_nnreal q}, {b | ↑(real.to_nnreal q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(real.to_nnreal q) < a}, {b | b < ↑(real.to_nnreal q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} : tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l := show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map] lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} : continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x := tendsto_nhds_coe_iff lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝ≥0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma eventually_eq_of_to_real_eventually_eq {l : filter α} {f g : α → ℝ≥0∞} (hfi : ∀ᶠ x in l, f x ≠ ∞) (hgi : ∀ᶠ x in l, g x ≠ ∞) (hfg : (λ x, (f x).to_real) =ᶠ[l] (λ x, (g x).to_real)) : f =ᶠ[l] g := begin filter_upwards [hfi, hgi, hfg], intros x hfx hgx hfgx, rwa ← ennreal.to_real_eq_to_real hfx hgx, end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ continuous_coe, .. ne_top_equiv_nnreal } /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[Ioi r] (r : ℝ≥0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ennreal.coe_lt_top @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[Ioi 0] (0 : ℝ≥0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds (xt : x ≠ ⊤) (ε0 : ε ≠ 0) : Icc (x - ε) (x + ε) ∈ 𝓝 x := begin rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top (xt : x ≠ ⊤) : 𝓝 x = ⨅ ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0.lt.ne', -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), rcases hs with ⟨xs, ⟨a, (rfl : s = Ioi a)|(rfl : s = Iio a)⟩⟩, { rcases exists_between xs with ⟨b, ab, bx⟩, have xb_pos : 0 < x - b := tsub_pos_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel xt bx.le, refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rcases exists_between xs with ⟨b, xb, ba⟩, have bx_pos : 0 < b - x := tsub_pos_iff_lt.2 xb, have xbx : x + (b - x) = b := add_tsub_cancel_of_le xb.le, refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝ≥0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} : filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_tsub, zero_le _, true_and], }, { exact hβ, }, end protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, replace hε : 0 < ε, from coe_pos.1 hε, filter_upwards [prod_is_open.mem_nhds (lt_mem_nhds $ @coe_lt_top (n / ε)) (lt_mem_nhds hεb)], rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, rw [← div_mul_cancel n hε.ne', coe_mul], exact mul_lt_mul h₁ h₂ end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞} (s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞): tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := begin induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] }, simp only [finset.prod_insert has], apply tendsto.mul (h _ (finset.mem_insert_self _ _)), { right, exact (prod_lt_top (λ i hi, h' _ (finset.mem_insert_of_mem hi))).ne }, { exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi)) (λ i hi, h' _ (finset.mem_insert_of_mem hi)) }, { exact or.inr (h' _ (finset.mem_insert_self _ _)) } end protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) @[continuity] lemma continuous_pow (n : ℕ) : continuous (λ a : ℝ≥0∞, a ^ n) := begin induction n with n IH, { simp [continuous_const] }, simp_rw [nat.succ_eq_add_one, pow_add, pow_one, continuous_iff_continuous_at], assume x, refine ennreal.tendsto.mul (IH.tendsto _) _ tendsto_id _; by_cases H : x = 0, { simp only [H, zero_ne_top, ne.def, or_true, not_false_iff]}, { exact or.inl (λ h, H (pow_eq_zero h)) }, { simp only [H, pow_eq_top_iff, zero_ne_top, false_or, eq_self_iff_true, not_true, ne.def, not_false_iff, false_and], }, { simp only [H, true_or, ne.def, not_false_iff] } end protected lemma tendsto.pow {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} {n : ℕ} (hm : tendsto m f (𝓝 a)) : tendsto (λ x, (m x) ^ n) f (𝓝 (a ^ n)) := ((continuous_pow n).tendsto a).comp hm lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[Iio 1] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, mul_top, if_neg], exact mt h0 (not_nonempty_iff.2 ‹_›) }, { exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H) ennreal.mul_left_mono).symm } } end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := infi_mul_left' h (λ _, ‹nonempty ι›) lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := infi_mul_right' h (λ _, ‹nonempty ι›) protected lemma continuous_inv : continuous (has_inv.inv : ℝ≥0∞ → ℝ≥0∞) := continuous_iff_continuous_at.2 $ λ a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := begin simp only [← Sup_image], symmetry, rw [image_comp (+ a)], refine is_lub.Sup_eq ((is_lub_Sup $ f '' s).is_lub_of_tendsto _ (hs.image _) _), exacts [λ x _ y _ hxy, add_le_add hxy le_rfl, tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds] end lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by rw Sup_range ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ℝ≥0∞, (⨆i, f i) = 0 := λ f, supr_eq_zero.mpr (λ i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ℝ≥0∞), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s ≠ 0 := pos_iff_ne_zero.1 (lt_of_lt_of_le (pos_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub.Sup_eq ((is_lub_Sup s).is_lub_of_tendsto (assume x _ y _ h, mul_le_mul_left' h _) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a := supr_mul protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine forall_ennreal.2 ⟨λ a, _, _⟩, { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, ← with_top.coe_sub], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, tsub_le_tsub (le_refl (r : ℝ≥0∞))) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_rfl end topological_space section tsum variables {f g : α → ℝ≥0∞} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} : ∑' i, f i = filter.at_top.liminf (λ n, ∑ i in finset.range n, f i) := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (λ n, le_antisymm _ _), { refine le_binfi (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a @[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ := let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ lemma tsum_const_eq_top_of_ne_zero {α : Type*} [infinite α] {c : ℝ≥0∞} (hc : c ≠ 0) : (∑' (a : α), c) = ∞ := begin have A : tendsto (λ (n : ℕ), (n : ℝ≥0∞) * c) at_top (𝓝 (∞ * c)), { apply ennreal.tendsto.mul_const tendsto_nat_nhds_top, simp only [true_or, top_ne_zero, ne.def, not_false_iff] }, have B : ∀ (n : ℕ), (n : ℝ≥0∞) * c ≤ (∑' (a : α), c), { assume n, rcases infinite.exists_subset_card_eq α n with ⟨s, hs⟩, simpa [hs] using @ennreal.sum_le_tsum α (λ i, c) s }, simpa [hc] using le_of_tendsto' A B, end protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) : tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_ne_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf, have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal), from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf), end lemma tendsto_at_top_zero_of_tsum_ne_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_ne_top hf } /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, convert ennreal.tendsto_coe.2 (nnreal.tendsto_tsum_compl_at_top_zero f), ext1 s, rw ennreal.coe_tsum, exact nnreal.summable_comp_injective (tsum_coe_ne_top_iff_summable.1 hf) subtype.coe_injective end protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i ≠ ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, add_sub_self h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw tsub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end end tsum lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞} (hx : x ≠ ∞) : fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) := begin refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩, have h_eq : f = (λ n, ennreal.of_real (f n).to_real), by { ext1 n, rw ennreal.of_real_to_real (hf n), }, rw [h_eq, ← ennreal.of_real_to_real hx], exact ennreal.tendsto_of_real h, end lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) := begin rw nnreal.summable_coe, exact tsum_coe_ne_top_iff_summable, end lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) := begin rw [← @not_not (∑' a, ↑(f a) = ⊤)], exact not_congr tsum_coe_ne_top_iff_summable_coe end lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : summable (λ x, (f x).to_real) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum, rwa ennreal.tsum_coe_ne_top_iff_summable_coe at hsum, end end ennreal namespace nnreal open_locale nnreal lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} : (∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal := begin by_cases h : summable f, { rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] }, { have A := tsum_eq_zero_of_not_summable h, simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h, simp only [h, ennreal.top_to_nnreal, A] } end /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ℝ≥0∞) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) : summable (s.indicator f) := begin refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) : ∑' x, (s.indicator f) x ≠ 0 := λ h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a), have : (sf : ℝ) < sg := has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg), exact nnreal.coe_lt_coe.1 this end @[mono] lemma has_sum_strict_mono {f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum @[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg } end nnreal namespace ennreal lemma tsum_to_real_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_real = ∑' a, (f a).to_real := begin lift f to α → ℝ≥0 using hf, have : (∑' (a : α), (f a : ℝ≥0∞)).to_real = ((∑' (a : α), (f a : ℝ≥0∞)).to_nnreal : ℝ≥0∞).to_real, { rw [ennreal.coe_to_real], refl }, rw [this, ← nnreal.tsum_eq_to_nnreal_tsum, ennreal.coe_to_real], exact nnreal.coe_tsum end lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin lift f to α → ℝ≥0 using hn, rw nnreal.summable_coe at hf, simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := begin lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b), lift g to β → ℝ≥0 using hg, rw nnreal.summable_coe at hf ⊢, exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf end /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_of_real_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : finset ι, ∑ x in u, f x ≤ c) : summable f := ⟨ ⨆ u : finset ι, ∑ x in u, f x, tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩ lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1 (summable_of_sum_range_le hf h).has_sum) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is 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`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin rcases eq_or_ne C 0 with (rfl|C0), { simp only [zero_mul, add_zero] at h, exact continuous_of_const (λ x y, le_antisymm (h _ _) (h _ _)) }, { refine continuous_iff_continuous_at.2 (λ x, _), by_cases hx : f x = ∞, { have : f =ᶠ[𝓝 x] (λ _, ∞), { filter_upwards [emetric.ball_mem_nhds x ennreal.coe_lt_top], refine λ y (hy : edist y x < ⊤), _, rw edist_comm at hy, simpa [hx, hC, hy.ne] using h x y }, exact this.continuous_at }, { refine (ennreal.tendsto_nhds hx).2 (λ ε (ε0 : 0 < ε), _), filter_upwards [emetric.closed_ball_mem_nhds x (ennreal.div_pos_iff.2 ⟨ε0.ne', hC⟩)], have hεC : C * (ε / C) = ε := ennreal.mul_div_cancel' C0 hC, refine λ y (hy : edist y x ≤ ε / C), ⟨tsub_le_iff_right.2 _, _⟩, { rw edist_comm at hy, calc f x ≤ f y + C * edist x y : h x y ... ≤ f y + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f y) ... = f y + ε : by rw hεC }, { calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f x) ... = f x + ε : by rw hεC } } } end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end @[continuity] theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure2 (@continuous_edist α _) hx hy (λ _ _, edist_le_diam_of_mem), rwa closure_Iic at this end @[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) : metric.diam (closure s) = diam s := by simp only [metric.diam, emetric.diam_closure] lemma is_closed_set_of_lipschitz_on_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (s : set α) : is_closed {f : α → β | lipschitz_on_with K f s} := begin simp only [lipschitz_on_with, set_of_forall], refine is_closed_bInter (λ x hx, is_closed_bInter $ λ y hy, is_closed_le _ _), exacts [continuous.edist (continuous_apply x) (continuous_apply y), continuous_const] end lemma is_closed_set_of_lipschitz_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) : is_closed {f : α → β | lipschitz_with K f} := by simp only [← lipschitz_on_univ, is_closed_set_of_lipschitz_on_with] namespace real /-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as `ℝ≥0∞`. -/ lemma ediam_eq {s : set ℝ} (h : bounded s) : emetric.diam s = ennreal.of_real (Sup s - Inf s) := begin rcases eq_empty_or_nonempty s with rfl|hne, { simp }, refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _, { have := real.subset_Icc_Inf_Sup_of_bounded h, exact real.dist_le_of_mem_Icc (this hx) (this hy) }, { apply ennreal.of_real_le_of_le_to_real, rw [← metric.diam, ← metric.diam_closure], have h' := real.bounded_iff_bdd_below_bdd_above.1 h, calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _ ... ≤ diam (closure s) : dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) } end /-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/ lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s := begin rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real], rw real.bounded_iff_bdd_below_bdd_above at h, exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2) end @[simp] lemma ediam_Ioo (a b : ℝ) : emetric.diam (Ioo a b) = ennreal.of_real (b - a) := begin rcases le_or_lt b a with h|h, { simp [h] }, { rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] }, end @[simp] lemma ediam_Icc (a b : ℝ) : emetric.diam (Icc a b) = ennreal.of_real (b - a) := begin rcases le_or_lt a b with h|h, { rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] }, { simp [h, h.le] } end @[simp] lemma ediam_Ico (a b : ℝ) : emetric.diam (Ico a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self) @[simp] lemma ediam_Ioc (a b : ℝ) : emetric.diam (Ioc a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self) end real /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
12779e4332a9f9332f74d84aa5f0ec96f42acf1a
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/groupes/cpge_groupe_9_a_bis.lean
0b82de9d94f7723bc32316844d7b2a9a97d59791
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
193
lean
import group_theory.subgroup theorem cpge_groupe_9_a_bis {G1 : Type*} [group G1] {G2 : Type*} [group G2] (f : G1 →* G2) : (∀ (a ∈ f.ker), ∀ (x : G1), f (x * a * x⁻¹) = 1) := sorry
150fda0a3e1da3f3a2c8da42fcd34b6e04462b97
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/DiscrTree.lean
016d51da553cca49b7e612dfafa99f36e1d1f1a1
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
21,490
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.Meta.Basic import Lean.Meta.FunInfo import Lean.Meta.InferType import Lean.Meta.WHNF namespace Lean.Meta.DiscrTree /- (Imperfect) discrimination trees. We use a hybrid representation. - A `PersistentHashMap` for the root node which usually contains many children. - A sorted array of key/node pairs for inner nodes. The edges are labeled by keys: - Constant names (and arity). Universe levels are ignored. - Free variables (and arity). Thus, an entry in the discrimination tree may reference hypotheses from the local context. - Literals - Star/Wildcard. We use them to represent metavariables and terms we want to ignore. We ignore implicit arguments and proofs. - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc). We reduce terms using `TransparencyMode.reducible`. Thus, all reducible definitions in an expression `e` are unfolded before we insert it into the discrimination tree. Recall that projections from classes are **NOT** reducible. For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x` and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys respctively ``` ⟨Add.add, 4⟩, *, *, *, * ⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩ ``` That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`. We say the `Add.add` applications are the de-facto canonical forms in the metaprogramming framework. Moreover, it is the metaprogrammer's responsibility to re-pack applications such as `Nat.add a b` into `Add.add Nat inst a b`. Remark: we store the arity in the keys 1- To be able to implement the "skip" operation when retrieving "candidate" unifiers. 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`. -/ def Key.ctorIdx : Key → Nat | Key.star => 0 | Key.other => 1 | Key.lit .. => 2 | Key.fvar .. => 3 | Key.const .. => 4 | Key.arrow => 5 | Key.proj .. => 6 def Key.lt : Key → Key → Bool | Key.lit v₁, Key.lit v₂ => v₁ < v₂ | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁.name n₂.name || (n₁ == n₂ && a₁ < a₂) | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | Key.proj s₁ i₁, Key.proj s₂ i₂ => Name.quickLt s₁ s₂ || (s₁ == s₂ && i₁ < i₂) | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx instance : LT Key := ⟨fun a b => Key.lt a b⟩ instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b)) def Key.format : Key → Format | Key.star => "*" | Key.other => "◾" | Key.lit (Literal.natVal v) => Std.format v | Key.lit (Literal.strVal v) => repr v | Key.const k _ => Std.format k | Key.proj s i => Std.format s ++ "." ++ Std.format i | Key.fvar k _ => Std.format k.name | Key.arrow => "→" instance : ToFormat Key := ⟨Key.format⟩ def Key.arity : Key → Nat | Key.const _ a => a | Key.fvar _ a => a | Key.arrow => 2 | Key.proj .. => 1 | _ => 0 instance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩ def empty : DiscrTree α := { root := {} } partial def Trie.format [ToFormat α] : Trie α → Format | Trie.node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ Std.format vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (Std.format k ++ " => " ++ format c)) instance [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩ partial def format [ToFormat α] (d : DiscrTree α) : Format := let (_, r) := d.root.foldl (fun (p : Bool × Format) k c => (false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (Std.format k ++ " => " ++ Std.format c))) (true, Format.nil) Format.group r instance [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩ /- The discrimination tree ignores implicit arguments and proofs. We use the following auxiliary id as a "mark". -/ private def tmpMVarId : MVarId := { name := `_discr_tree_tmp } private def tmpStar := mkMVar tmpMVarId instance : Inhabited (DiscrTree α) where default := {} /-- Return true iff the argument should be treated as a "wildcard" by the discrimination tree. - We ignore proofs because of proof irrelevance. It doesn't make sense to try to index their structure. - We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical. Moreover, we may have many definitionally equal terms floating around. Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`. - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them, and may not even understand why some simplification rule is not firing. However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`, where `Nat` is an implicit argument. Thus, we would add the path ``` Decidable -> Eq -> * -> * -> * -> [Nat.decEq] ``` to the discrimination tree IF we ignored the implict `Nat` argument. This would be BAD since **ALL** decidable equality instances would be in the same path. So, we index implicit arguments if they are types. This setting seems sensible for simplification lemmas such as: ``` forall (x y : Unit), (@Eq Unit x y) = true ``` If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate simplification lemma for any equality in our goal. Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation, and `ignoreArg` would return true for any term of the form `noIndexing t`. -/ private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do if h : i < infos.size then let info := infos.get ⟨i, h⟩ if info.isInstImplicit then return true else if info.isImplicit || info.isStrictImplicit then return not (← isType a) else isProof a else isProof a private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr) | i, Expr.app f a _, todo => do if (← ignoreArg a i infos) then pushArgsAux infos (i-1) f (todo.push tmpStar) else pushArgsAux infos (i-1) f (todo.push a) | _, _, todo => return todo /-- Return true if `e` is one of the following - A nat literal (numeral) - `Nat.zero` - `Nat.succ x` where `isNumeral x` - `OfNat.ofNat _ x _` where `isNumeral x` -/ private partial def isNumeral (e : Expr) : Bool := if e.isNatLit then true else let f := e.getAppFn if !f.isConst then false else let fName := f.constName! if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg! else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1) else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true else false private def isNatType (e : Expr) : MetaM Bool := return (← whnf e).isConstOf ``Nat /-- Return true if `e` is one of the following - `Nat.add _ k` where `isNumeral k` - `Add.add Nat _ _ k` where `isNumeral k` - `HAdd.hAdd _ Nat _ _ k` where `isNumeral k` - `Nat.succ _` This function assumes `e.isAppOf fName` -/ private def isOffset (fName : Name) (e : Expr) : MetaM Bool := do if fName == ``Nat.add && e.getAppNumArgs == 2 then return isNumeral e.appArg! else if fName == ``Add.add && e.getAppNumArgs == 4 then if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false else return fName == ``Nat.succ && e.getAppNumArgs == 1 /- TODO: add hook for users adding their own functions for controlling `shouldAddAsStar` Different `DiscrTree` users may populate this set using, for example, attributes. Remark: we currently tag `Nat.zero` and "offset" terms to avoid having to add special support for `Expr.lit` and offset terms. Example, suppose the discrimination tree contains the entry `Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`. In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/ private def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do if fName == `Nat.zero then return true else isOffset fName e def mkNoindexAnnotation (e : Expr) : Expr := mkAnnotation `noindex e def hasNoindexAnnotation (e : Expr) : Bool := annotation? `noindex e |>.isSome private partial def whnfEta (e : Expr) : MetaM Expr := do let e ← whnf e match e.etaExpandedStrict? with | some e => whnfEta e | none => return e /-- Return `true` if `fn` is a "bad" key. That is, `pushArgs` would add `Key.other` or `Key.star`. We use this function when processing "root terms, and will avoid unfolding terms. Note that without this trick the pattern `List.map f ∘ List.map g` would be mapped into the key `Key.other` since the function composition `∘` would be unfolded and we would get `fun x => List.map g (List.map f x)` -/ private def isBadKey (fn : Expr) : Bool := match fn with | Expr.lit .. => false | Expr.const .. => false | Expr.fvar .. => false | Expr.proj .. => false | Expr.forallE _ d b _ => b.hasLooseBVars | _ => true /-- Reduce `e` until we get an irreducible term (modulo current reducibility setting) or the resulting term is a bad key (see comment at `isBadKey`). We use this method instead of `whnfEta` for root terms at `pushArgs`. -/ private partial def whnfUntilBadKey (e : Expr) : MetaM Expr := do let e ← step e match e.etaExpandedStrict? with | some e => whnfUntilBadKey e | none => return e where step (e : Expr) := do let e ← whnfCore e match (← unfoldDefinition? e) with | some e' => if isBadKey e'.getAppFn then return e else step e' | none => return e /-- whnf for the discrimination tree module -/ private def whnfDT (e : Expr) (root : Bool) : MetaM Expr := if root then whnfUntilBadKey e else whnfEta e /- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/ private def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do if hasNoindexAnnotation e then return (Key.star, todo) else let e ← whnfDT e root let fn := e.getAppFn let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do let info ← getFunInfoNArgs fn nargs let todo ← pushArgsAux info.paramInfo (nargs-1) e todo return (k, todo) match fn with | Expr.lit v _ => return (Key.lit v, todo) | Expr.const c _ _ => unless root do if (← shouldAddAsStar c e) then return (Key.star, todo) let nargs := e.getAppNumArgs push (Key.const c nargs) nargs | Expr.proj s i a .. => return (Key.proj s i, todo.push a) | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs push (Key.fvar fvarId nargs) nargs | Expr.mvar mvarId _ => if mvarId == tmpMVarId then -- We use `tmp to mark implicit arguments and proofs return (Key.star, todo) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then return (Key.other, todo) else return (Key.star, todo) | Expr.forallE _ d b _ => if b.hasLooseBVars then return (Key.other, todo) else return (Key.arrow, todo.push d |>.push b) | _ => return (Key.other, todo) partial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do if todo.isEmpty then return keys else let e := todo.back let todo := todo.pop let (k, todo) ← pushArgs root todo e mkPathAux false todo (keys.push k) private def initCapacity := 8 def mkPath (e : Expr) : MetaM (Array Key) := do withReducible do let todo : Array Expr := Array.mkEmpty initCapacity let keys : Array Key := Array.mkEmpty initCapacity mkPathAux (root := true) (todo.push e) keys private partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := createNodes keys v (i+1) Trie.node #[] #[(k, c)] else Trie.node #[v] #[] private def insertVal [BEq α] (vs : Array α) (v : α) : Array α := if vs.contains v then vs else vs.push v private partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α | i, Trie.node vs cs => if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing (fun _ => let c := createNodes keys v (i+1); (k, c)) (k, arbitrary) Trie.node vs c else Trie.node (insertVal vs v) cs def insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α := if keys.isEmpty then panic! "invalid key sequence" else let k := keys[0] match d.root.find? k with | none => let c := createNodes keys v 1 { root := d.root.insert k c } | some c => let c := insertAux keys v 1 c { root := d.root.insert k c } def insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do let keys ← mkPath e return d.insertCore keys v private def getKeyArgs (e : Expr) (isMatch root : Bool) : MetaM (Key × Array Expr) := do let e ← whnfDT e root match e.getAppFn with | Expr.lit v _ => return (Key.lit v, #[]) | Expr.const c _ _ => let nargs := e.getAppNumArgs return (Key.const c nargs, e.getAppRevArgs) | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs return (Key.fvar fvarId nargs, e.getAppRevArgs) | Expr.mvar mvarId _ => if isMatch then return (Key.other, #[]) else do let ctx ← read if ctx.config.isDefEqStuckEx then /- When the configuration flag `isDefEqStuckEx` is set to true, we want `isDefEq` to throw an exception whenever it tries to assign a read-only metavariable. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`. That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)` where `?m` is a read-only metavariable, and the discrimination tree contains the keys `HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as a regular metavariable here, otherwise we return the empty set of candidates. This is incorrect because it is equivalent to saying that there is no solution even if the caller assigns `?m` and try again. -/ return (Key.star, #[]) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then return (Key.other, #[]) else return (Key.star, #[]) | Expr.proj s i a .. => return (Key.proj s i, #[a]) | Expr.forallE _ d b _ => if b.hasLooseBVars then return (Key.other, #[]) else return (Key.arrow, #[d, b]) | _ => return (Key.other, #[]) private abbrev getMatchKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) := getKeyArgs e (isMatch := true) (root := root) private abbrev getUnifyKeyArgs (e : Expr) (root : Bool) : MetaM (Key × Array Expr) := getKeyArgs e (isMatch := false) (root := root) private def getStarResult (d : DiscrTree α) : Array α := let result : Array α := Array.mkEmpty initCapacity match d.root.find? Key.star with | none => result | some (Trie.node vs _) => result ++ vs private abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) := cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1) private partial def getMatchLoop (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do match c with | Trie.node vs cs => if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let first := cs[0] /- Recall that `Key.star` is the minimal key -/ let (k, args) ← getMatchKeyArgs e (root := false) /- We must always visit `Key.star` edges since they are wildcards. Thus, `todo` is not used linearly when there is `Key.star` edge and there is an edge for `k` and `k != Key.star`. -/ let visitStar (result : Array α) : MetaM (Array α) := if first.1 == Key.star then getMatchLoop todo first.2 result else return result let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) := match findKey cs k with | none => result | some c => getMatchLoop (todo ++ args) c.2 result let result ← visitStar result match k with | Key.star => result /- Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`. A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child. -/ | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result) | _ => visitNonStar k args result private def getMatchRoot (d : DiscrTree α) (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) := match d.root.find? k with | none => return result | some c => getMatchLoop args c result /-- Find values that match `e` in `d`. -/ partial def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let result := getStarResult d let (k, args) ← getMatchKeyArgs e (root := true) match k with | Key.star => return result | _ => getMatchRoot d k args result /-- Similar to `getMatch`, but returns solutions that are prefixes of `e`. We store the number of ignored arguments in the result.-/ partial def getMatchWithExtra (d : DiscrTree α) (e : Expr) : MetaM (Array (α × Nat)) := withReducible do let result := getStarResult d |>.map (., 0) let (k, args) ← getMatchKeyArgs e (root := true) match k with | Key.star => return result | _ => process k args.toSubarray 0 result where process (k : Key) (args : Subarray Expr) (numExtraArgs : Nat) (result : Array (α × Nat)) : MetaM (Array (α × Nat)) := do -- Remark: the args are stored in reverse order let result := if d.root.find? k |>.isSome then result ++ ((← getMatchRoot d k args.toArray #[]).map (., numExtraArgs)) else result match k with | Key.const f 0 => return result | Key.const f (n+1) => process (Key.const f n) args.popFront (numExtraArgs + 1) result | Key.fvar f 0 => return result | Key.fvar f (n+1) => process (Key.fvar f n) args.popFront (numExtraArgs + 1) result | _ => return result partial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let (k, args) ← getUnifyKeyArgs e (root := true) match k with | Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result | _ => let result := getStarResult d match d.root.find? k with | none => return result | some c => process 0 args c result where process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do match skip, c with | skip+1, Trie.node vs cs => if cs.isEmpty then return result else cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result | 0, Trie.node vs cs => do if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let (k, args) ← getUnifyKeyArgs e (root := false) let visitStar (result : Array α) : MetaM (Array α) := let first := cs[0] if first.1 == Key.star then process 0 todo first.2 result else return result let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) := match findKey cs k with | none => result | some c => process 0 (todo ++ args) c.2 result match k with | Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result)) | _ => visitNonStar k args (← visitStar result) end Lean.Meta.DiscrTree
8c76b6b068e42a9506677b99e60d14f004455f55
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/sort.lean
f0292bd51b07625fbc06b7a4f2081dce6921539e
[ "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
38
lean
#check Sort #check Sort 0 #check Prop
aa9ad8f5d7634d7655e67ce71d14fa8683fc796d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/pi.lean
5d2567d628bb6f73f789339efa5588da121c48e0
[ "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
18,224
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.basic import logic.equiv.fin /-! # Pi types of modules This file defines constructors for linear maps whose domains or codomains are pi types. It contains theorems relating these to each other, as well as to `linear_map.ker`. ## Main definitions - pi types in the codomain: - `linear_map.pi` - `linear_map.single` - pi types in the domain: - `linear_map.proj` - `linear_map.diag` -/ universes u v w x y z u' v' w' x' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} {ι' : Type x'} open function submodule open_locale big_operators namespace linear_map universe i variables [semiring R] [add_comm_monoid M₂] [module R M₂] [add_comm_monoid M₃] [module R M₃] {φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, module R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := { to_fun := λ c i, f i c, map_add' := λ c d, funext $ λ i, (f i).map_add _ _, map_smul' := λ c d, funext $ λ i, (f i).map_smul _ _ } @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. Note: known here as `linear_map.proj`, this construction is in other categories called `eval`, for example `pi.eval_monoid_hom`, `pi.eval_ring_hom`. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := { to_fun := function.eval i, map_add' := λ f g, rfl, map_smul' := λ c f, rfl } @[simp] lemma coe_proj (i : ι) : ⇑(proj i : (Πi, φ i) →ₗ[R] φ i) = function.eval i := rfl lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i : (Πi, φ i) →ₗ[R] φ i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ set_like.le_def.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end /-- Linear map between the function spaces `I → M₂` and `I → M₃`, induced by a linear map `f` between `M₂` and `M₃`. -/ @[simps] protected def comp_left (f : M₂ →ₗ[R] M₃) (I : Type*) : (I → M₂) →ₗ[R] (I → M₃) := { to_fun := λ h, f ∘ h, map_smul' := λ c h, by { ext x, exact f.map_smul' c (h x) }, .. f.to_add_monoid_hom.comp_left I } lemma apply_single [add_comm_monoid M] [module R M] [decidable_eq ι] (f : Π i, φ i →ₗ[R] M) (i j : ι) (x : φ i) : f j (pi.single i x j) = pi.single i (f i x) j := pi.apply_single (λ i, f i) (λ i, (f i).map_zero) _ _ _ /-- The `linear_map` version of `add_monoid_hom.single` and `pi.single`. -/ def single [decidable_eq ι] (i : ι) : φ i →ₗ[R] (Πi, φ i) := { to_fun := pi.single i, map_smul' := pi.single_smul i, .. add_monoid_hom.single φ i} @[simp] lemma coe_single [decidable_eq ι] (i : ι) : ⇑(single i : φ i →ₗ[R] (Π i, φ i)) = pi.single i := rfl variables (R φ) /-- The linear equivalence between linear functions on a finite product of modules and families of functions on these modules. See note [bundled maps over different rings]. -/ @[simps] def lsum (S) [add_comm_monoid M] [module R M] [fintype ι] [decidable_eq ι] [semiring S] [module S M] [smul_comm_class R S M] : (Π i, φ i →ₗ[R] M) ≃ₗ[S] ((Π i, φ i) →ₗ[R] M) := { to_fun := λ f, ∑ i : ι, (f i).comp (proj i), inv_fun := λ f i, f.comp (single i), map_add' := λ f g, by simp only [pi.add_apply, add_comp, finset.sum_add_distrib], map_smul' := λ c f, by simp only [pi.smul_apply, smul_comp, finset.smul_sum, ring_hom.id_apply], left_inv := λ f, by { ext i x, simp [apply_single] }, right_inv := λ f, begin ext, suffices : f (∑ j, pi.single j (x j)) = f x, by simpa [apply_single], rw finset.univ_sum_single end } variables {R φ} section ext variables [finite ι] [decidable_eq ι] [add_comm_monoid M] [module R M] {f g : (Π i, φ i) →ₗ[R] M} lemma pi_ext (h : ∀ i x, f (pi.single i x) = g (pi.single i x)) : f = g := to_add_monoid_hom_injective $ add_monoid_hom.functions_ext _ _ _ h lemma pi_ext_iff : f = g ↔ ∀ i x, f (pi.single i x) = g (pi.single i x) := ⟨λ h i x, h ▸ rfl, pi_ext⟩ /-- This is used as the ext lemma instead of `linear_map.pi_ext` for reasons explained in note [partially-applied ext lemmas]. -/ @[ext] lemma pi_ext' (h : ∀ i, f.comp (single i) = g.comp (single i)) : f = g := begin refine pi_ext (λ i x, _), convert linear_map.congr_fun (h i) x end lemma pi_ext'_iff : f = g ↔ ∀ i, f.comp (single i) = g.comp (single i) := ⟨λ h i, h ▸ rfl, pi_ext'⟩ end ext section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i : (Πi, φ i) →ₗ[R] φ i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, subtype.coe_prop], ext b ⟨j, hj⟩, simp only [dif_pos, function.comp_app, function.eval_apply, linear_map.cod_restrict_apply, linear_map.coe_comp, linear_map.coe_proj, linear_map.pi_apply, submodule.subtype_apply, subtype.coe_prop], refl }, { ext1 ⟨b, hb⟩, apply subtype.ext, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { refl }, { exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end end linear_map namespace submodule variables [semiring R] {φ : ι → Type*} [∀ i, add_comm_monoid (φ i)] [∀ i, module R (φ i)] open linear_map /-- A version of `set.pi` for submodules. Given an index set `I` and a family of submodules `p : Π i, submodule R (φ i)`, `pi I s` is the submodule of dependent functions `f : Π i, φ i` such that `f i` belongs to `p a` whenever `i ∈ I`. -/ def pi (I : set ι) (p : Π i, submodule R (φ i)) : submodule R (Π i, φ i) := { carrier := set.pi I (λ i, p i), zero_mem' := λ i hi, (p i).zero_mem, add_mem' := λ x y hx hy i hi, (p i).add_mem (hx i hi) (hy i hi), smul_mem' := λ c x hx i hi, (p i).smul_mem c (hx i hi) } variables {I : set ι} {p q : Π i, submodule R (φ i)} {x : Π i, φ i} @[simp] lemma mem_pi : x ∈ pi I p ↔ ∀ i ∈ I, x i ∈ p i := iff.rfl @[simp, norm_cast] lemma coe_pi : (pi I p : set (Π i, φ i)) = set.pi I (λ i, p i) := rfl @[simp] lemma pi_empty (p : Π i, submodule R (φ i)) : pi ∅ p = ⊤ := set_like.coe_injective $ set.empty_pi _ @[simp] lemma pi_top (s : set ι) : pi s (λ i : ι, (⊤ : submodule R (φ i))) = ⊤ := set_like.coe_injective $ set.pi_univ _ lemma pi_mono {s : set ι} (h : ∀ i ∈ s, p i ≤ q i) : pi s p ≤ pi s q := set.pi_mono h lemma binfi_comap_proj : (⨅ i ∈ I, comap (proj i : (Πi, φ i) →ₗ[R] φ i) (p i)) = pi I p := by { ext x, simp } lemma infi_comap_proj : (⨅ i, comap (proj i : (Πi, φ i) →ₗ[R] φ i) (p i)) = pi set.univ p := by { ext x, simp } lemma supr_map_single [decidable_eq ι] [finite ι] : (⨆ i, map (linear_map.single i : φ i →ₗ[R] (Πi, φ i)) (p i)) = pi set.univ p := begin casesI nonempty_fintype ι, refine (supr_le $ λ i, _).antisymm _, { rintro _ ⟨x, hx : x ∈ p i, rfl⟩ j -, rcases em (j = i) with rfl|hj; simp * }, { intros x hx, rw [← finset.univ_sum_single x], exact sum_mem_supr (λ i, mem_map_of_mem (hx i trivial)) } end end submodule namespace linear_equiv variables [semiring R] {φ ψ χ : ι → Type*} [∀ i, add_comm_monoid (φ i)] [∀ i, module R (φ i)] variables [∀ i, add_comm_monoid (ψ i)] [∀ i, module R (ψ i)] variables [∀ i, add_comm_monoid (χ i)] [∀ i, module R (χ i)] /-- Combine a family of linear equivalences into a linear equivalence of `pi`-types. This is `equiv.Pi_congr_right` as a `linear_equiv` -/ @[simps apply] def Pi_congr_right (e : Π i, φ i ≃ₗ[R] ψ i) : (Π i, φ i) ≃ₗ[R] (Π i, ψ i) := { to_fun := λ f i, e i (f i), inv_fun := λ f i, (e i).symm (f i), map_smul' := λ c f, by { ext, simp }, .. add_equiv.Pi_congr_right (λ j, (e j).to_add_equiv) } @[simp] lemma Pi_congr_right_refl : Pi_congr_right (λ j, refl R (φ j)) = refl _ _ := rfl @[simp] lemma Pi_congr_right_symm (e : Π i, φ i ≃ₗ[R] ψ i) : (Pi_congr_right e).symm = (Pi_congr_right $ λ i, (e i).symm) := rfl @[simp] lemma Pi_congr_right_trans (e : Π i, φ i ≃ₗ[R] ψ i) (f : Π i, ψ i ≃ₗ[R] χ i) : (Pi_congr_right e).trans (Pi_congr_right f) = (Pi_congr_right $ λ i, (e i).trans (f i)) := rfl variables (R φ) /-- Transport dependent functions through an equivalence of the base space. This is `equiv.Pi_congr_left'` as a `linear_equiv`. -/ @[simps {simp_rhs := tt}] def Pi_congr_left' (e : ι ≃ ι') : (Π i', φ i') ≃ₗ[R] (Π i, φ $ e.symm i) := { map_add' := λ x y, rfl, map_smul' := λ x y, rfl, .. equiv.Pi_congr_left' φ e } /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". This is `equiv.Pi_congr_left` as a `linear_equiv` -/ def Pi_congr_left (e : ι' ≃ ι) : (Π i', φ (e i')) ≃ₗ[R] (Π i, φ i) := (Pi_congr_left' R φ e.symm).symm /-- This is `equiv.pi_option_equiv_prod` as a `linear_equiv` -/ def pi_option_equiv_prod {ι : Type*} {M : option ι → Type*} [Π i, add_comm_group (M i)] [Π i, module R (M i)] : (Π i : option ι, M i) ≃ₗ[R] (M none × Π i : ι, M (some i)) := { map_add' := by simp [function.funext_iff], map_smul' := by simp [function.funext_iff], ..equiv.pi_option_equiv_prod } variables (ι R M) (S : Type*) [fintype ι] [decidable_eq ι] [semiring S] [add_comm_monoid M] [module R M] [module S M] [smul_comm_class R S M] /-- Linear equivalence between linear functions `Rⁿ → M` and `Mⁿ`. The spaces `Rⁿ` and `Mⁿ` are represented as `ι → R` and `ι → M`, respectively, where `ι` is a finite type. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ def pi_ring : ((ι → R) →ₗ[R] M) ≃ₗ[S] (ι → M) := (linear_map.lsum R (λ i : ι, R) S).symm.trans (Pi_congr_right $ λ i, linear_map.ring_lmap_equiv_self R S M) variables {ι R M} @[simp] lemma pi_ring_apply (f : (ι → R) →ₗ[R] M) (i : ι) : pi_ring R M ι S f i = f (pi.single i 1) := rfl @[simp] lemma pi_ring_symm_apply (f : ι → M) (g : ι → R) : (pi_ring R M ι S).symm f g = ∑ i, g i • f i := by simp [pi_ring, linear_map.lsum] /-- `equiv.sum_arrow_equiv_prod_arrow` as a linear equivalence. -/ -- TODO additive version? def sum_arrow_lequiv_prod_arrow (α β R M : Type*) [semiring R] [add_comm_monoid M] [module R M] : ((α ⊕ β) → M) ≃ₗ[R] (α → M) × (β → M) := { map_add' := by { intros f g, ext; refl }, map_smul' := by { intros r f, ext; refl, }, .. equiv.sum_arrow_equiv_prod_arrow α β M, } @[simp] lemma sum_arrow_lequiv_prod_arrow_apply_fst {α β} (f : (α ⊕ β) → M) (a : α) : (sum_arrow_lequiv_prod_arrow α β R M f).1 a = f (sum.inl a) := rfl @[simp] lemma sum_arrow_lequiv_prod_arrow_apply_snd {α β} (f : (α ⊕ β) → M) (b : β) : (sum_arrow_lequiv_prod_arrow α β R M f).2 b = f (sum.inr b) := rfl @[simp] lemma sum_arrow_lequiv_prod_arrow_symm_apply_inl {α β} (f : α → M) (g : β → M) (a : α) : ((sum_arrow_lequiv_prod_arrow α β R M).symm (f, g)) (sum.inl a) = f a := rfl @[simp] lemma sum_arrow_lequiv_prod_arrow_symm_apply_inr {α β} (f : α → M) (g : β → M) (b : β) : ((sum_arrow_lequiv_prod_arrow α β R M).symm (f, g)) (sum.inr b) = g b := rfl /-- If `ι` has a unique element, then `ι → M` is linearly equivalent to `M`. -/ @[simps { simp_rhs := tt, fully_applied := ff }] def fun_unique (ι R M : Type*) [unique ι] [semiring R] [add_comm_monoid M] [module R M] : (ι → M) ≃ₗ[R] M := { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. equiv.fun_unique ι M } variables (R M) /-- Linear equivalence between dependent functions `Π i : fin 2, M i` and `M 0 × M 1`. -/ @[simps { simp_rhs := tt, fully_applied := ff }] def pi_fin_two (M : fin 2 → Type v) [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] : (Π i, M i) ≃ₗ[R] M 0 × M 1 := { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, .. pi_fin_two_equiv M } /-- Linear equivalence between vectors in `M² = fin 2 → M` and `M × M`. -/ @[simps { simp_rhs := tt, fully_applied := ff }] def fin_two_arrow : (fin 2 → M) ≃ₗ[R] M × M := { .. fin_two_arrow_equiv M, .. pi_fin_two R (λ _, M) } end linear_equiv section extend variables (R) {η : Type x} [semiring R] (s : ι → η) /-- `function.extend s f 0` as a bundled linear map. -/ @[simps] noncomputable def function.extend_by_zero.linear_map : (ι → R) →ₗ[R] (η → R) := { to_fun := λ f, function.extend s f 0, map_smul' := λ r f, by { simpa using function.extend_smul r s f 0 }, ..function.extend_by_zero.hom R s } end extend /-! ### Bundled versions of `matrix.vec_cons` and `matrix.vec_empty` The idea of these definitions is to be able to define a map as `x ↦ ![f₁ x, f₂ x, f₃ x]`, where `f₁ f₂ f₃` are already linear maps, as `f₁.vec_cons $ f₂.vec_cons $ f₃.vec_cons $ vec_empty`. While the same thing could be achieved using `linear_map.pi ![f₁, f₂, f₃]`, this is not definitionally equal to the result using `linear_map.vec_cons`, as `fin.cases` and function application do not commute definitionally. Versions for when `f₁ f₂ f₃` are bilinear maps are also provided. -/ section fin section semiring variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] /-- The linear map defeq to `matrix.vec_empty` -/ def linear_map.vec_empty : M →ₗ[R] (fin 0 → M₃) := { to_fun := λ m, matrix.vec_empty, map_add' := λ x y, subsingleton.elim _ _, map_smul' := λ r x, subsingleton.elim _ _ } @[simp] lemma linear_map.vec_empty_apply (m : M) : (linear_map.vec_empty : M →ₗ[R] (fin 0 → M₃)) m = ![] := rfl /-- A linear map into `fin n.succ → M₃` can be built out of a map into `M₃` and a map into `fin n → M₃`. -/ def linear_map.vec_cons {n} (f : M →ₗ[R] M₂) (g : M →ₗ[R] (fin n → M₂)) : M →ₗ[R] (fin n.succ → M₂) := { to_fun := λ m, matrix.vec_cons (f m) (g m), map_add' := λ x y, begin rw [f.map_add, g.map_add, matrix.cons_add_cons (f x)] end, map_smul' := λ c x, by rw [f.map_smul, g.map_smul, ring_hom.id_apply, matrix.smul_cons c (f x)] } @[simp] lemma linear_map.vec_cons_apply {n} (f : M →ₗ[R] M₂) (g : M →ₗ[R] (fin n → M₂)) (m : M) : f.vec_cons g m = matrix.vec_cons (f m) (g m) := rfl end semiring section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] /-- The empty bilinear map defeq to `matrix.vec_empty` -/ @[simps] def linear_map.vec_empty₂ : M →ₗ[R] M₂ →ₗ[R] (fin 0 → M₃) := { to_fun := λ m, linear_map.vec_empty, map_add' := λ x y, linear_map.ext $ λ z, subsingleton.elim _ _, map_smul' := λ r x, linear_map.ext $ λ z, subsingleton.elim _ _, } /-- A bilinear map into `fin n.succ → M₃` can be built out of a map into `M₃` and a map into `fin n → M₃` -/ @[simps] def linear_map.vec_cons₂ {n} (f : M →ₗ[R] M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂ →ₗ[R] (fin n → M₃)) : M →ₗ[R] M₂ →ₗ[R] (fin n.succ → M₃) := { to_fun := λ m, linear_map.vec_cons (f m) (g m), map_add' := λ x y, linear_map.ext $ λ z, by simp only [f.map_add, g.map_add, linear_map.add_apply, linear_map.vec_cons_apply, matrix.cons_add_cons (f x z)], map_smul' := λ r x, linear_map.ext $ λ z, by simp [matrix.smul_cons r (f x z)], } end comm_semiring end fin
c058f534fd124fd84a2f4b5362b0d434a5b08ea5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/closed/functor.lean
44589883772c83819ec638a6b7e9bb6a661de1ab
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,615
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.closed.cartesian import category_theory.limits.preserves.shapes.binary_products import category_theory.adjunction.fully_faithful /-! # Cartesian closed functors Define the exponential comparison morphisms for a functor which preserves binary products, and use them to define a cartesian closed functor: one which (naturally) preserves exponentials. Define the Frobenius morphism, and show it is an isomorphism iff the exponential comparison is an isomorphism. ## TODO Some of the results here are true more generally for closed objects and for closed monoidal categories, and these could be generalised. ## References https://ncatlab.org/nlab/show/cartesian+closed+functor https://ncatlab.org/nlab/show/Frobenius+reciprocity ## Tags Frobenius reciprocity, cartesian closed functor -/ namespace category_theory open category limits cartesian_closed universes v u u' variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v} D] variables [has_finite_products C] [has_finite_products D] variables (F : C ⥤ D) {L : D ⥤ C} noncomputable theory /-- The Frobenius morphism for an adjunction `L ⊣ F` at `A` is given by the morphism L(FA ⨯ B) ⟶ LFA ⨯ LB ⟶ A ⨯ LB natural in `B`, where the first morphism is the product comparison and the latter uses the counit of the adjunction. We will show that if `C` and `D` are cartesian closed, then this morphism is an isomorphism for all `A` iff `F` is a cartesian closed functor, i.e. it preserves exponentials. -/ def frobenius_morphism (h : L ⊣ F) (A : C) : prod.functor.obj (F.obj A) ⋙ L ⟶ L ⋙ prod.functor.obj A := prod_comparison_nat_trans L (F.obj A) ≫ whisker_left _ (prod.functor.map (h.counit.app _)) /-- If `F` is full and faithful and has a left adjoint `L` which preserves binary products, then the Frobenius morphism is an isomorphism. -/ instance frobenius_morphism_iso_of_preserves_binary_products (h : L ⊣ F) (A : C) [preserves_limits_of_shape (discrete walking_pair) L] [full F] [faithful F] : is_iso (frobenius_morphism F h A) := begin apply nat_iso.is_iso_of_is_iso_app _, intro B, dsimp [frobenius_morphism], apply_instance, end variables [cartesian_closed C] [cartesian_closed D] variables [preserves_limits_of_shape (discrete walking_pair) F] /-- The exponential comparison map. `F` is a cartesian closed functor if this is an iso for all `A`. -/ def exp_comparison (A : C) : exp A ⋙ F ⟶ F ⋙ exp (F.obj A) := transfer_nat_trans (exp.adjunction A) (exp.adjunction (F.obj A)) (prod_comparison_nat_iso F A).inv lemma exp_comparison_ev (A B : C) : limits.prod.map (𝟙 (F.obj A)) ((exp_comparison F A).app B) ≫ (exp.ev (F.obj A)).app (F.obj B) = inv (prod_comparison F _ _) ≫ F.map ((exp.ev _).app _) := begin convert transfer_nat_trans_counit _ _ (prod_comparison_nat_iso F A).inv B, ext, simp, end lemma coev_exp_comparison (A B : C) : F.map ((exp.coev A).app B) ≫ (exp_comparison F A).app (A ⨯ B) = (exp.coev _).app (F.obj B) ≫ (exp (F.obj A)).map (inv (prod_comparison F A B)) := begin convert unit_transfer_nat_trans _ _ (prod_comparison_nat_iso F A).inv B, ext, dsimp, simp, end lemma uncurry_exp_comparison (A B : C) : cartesian_closed.uncurry ((exp_comparison F A).app B) = inv (prod_comparison F _ _) ≫ F.map ((exp.ev _).app _) := by rw [uncurry_eq, exp_comparison_ev] /-- The exponential comparison map is natural in `A`. -/ lemma exp_comparison_whisker_left {A A' : C} (f : A' ⟶ A) : exp_comparison F A ≫ whisker_left _ (pre (F.map f)) = whisker_right (pre f) _ ≫ exp_comparison F A' := begin ext B, dsimp, apply uncurry_injective, rw [uncurry_natural_left, uncurry_natural_left, uncurry_exp_comparison, uncurry_pre, prod.map_swap_assoc, ←F.map_id, exp_comparison_ev, ←F.map_id, ←prod_comparison_inv_natural_assoc, ←prod_comparison_inv_natural_assoc, ←F.map_comp, ←F.map_comp, prod_map_pre_app_comp_ev], end /-- The functor `F` is cartesian closed (ie preserves exponentials) if each natural transformation `exp_comparison F A` is an isomorphism -/ class cartesian_closed_functor := (comparison_iso : ∀ A, is_iso (exp_comparison F A)) attribute [instance] cartesian_closed_functor.comparison_iso lemma frobenius_morphism_mate (h : L ⊣ F) (A : C) : transfer_nat_trans_self (h.comp (exp.adjunction A)) ((exp.adjunction (F.obj A)).comp h) (frobenius_morphism F h A) = exp_comparison F A := begin rw ←equiv.eq_symm_apply, ext B : 2, dsimp [frobenius_morphism, transfer_nat_trans_self, transfer_nat_trans, adjunction.comp], simp only [id_comp, comp_id], rw [←L.map_comp_assoc, prod.map_id_comp, assoc, exp_comparison_ev, prod.map_id_comp, assoc, ← F.map_id, ← prod_comparison_inv_natural_assoc, ← F.map_comp, exp.ev_coev, F.map_id (A ⨯ L.obj B), comp_id], apply prod.hom_ext, { rw [assoc, assoc, ←h.counit_naturality, ←L.map_comp_assoc, assoc, inv_prod_comparison_map_fst], simp }, { rw [assoc, assoc, ←h.counit_naturality, ←L.map_comp_assoc, assoc, inv_prod_comparison_map_snd], simp }, end /-- If the exponential comparison transformation (at `A`) is an isomorphism, then the Frobenius morphism at `A` is an isomorphism. -/ lemma frobenius_morphism_iso_of_exp_comparison_iso (h : L ⊣ F) (A : C) [i : is_iso (exp_comparison F A)] : is_iso (frobenius_morphism F h A) := begin rw ←frobenius_morphism_mate F h at i, exact @@transfer_nat_trans_self_of_iso _ _ _ _ _ i, end /-- If the Frobenius morphism at `A` is an isomorphism, then the exponential comparison transformation (at `A`) is an isomorphism. -/ lemma exp_comparison_iso_of_frobenius_morphism_iso (h : L ⊣ F) (A : C) [i : is_iso (frobenius_morphism F h A)] : is_iso (exp_comparison F A) := by { rw ← frobenius_morphism_mate F h, apply_instance } /-- If `F` is full and faithful, and has a left adjoint which preserves binary products, then it is cartesian closed. TODO: Show the converse, that if `F` is cartesian closed and its left adjoint preserves binary products, then it is full and faithful. -/ def cartesian_closed_functor_of_left_adjoint_preserves_binary_products (h : L ⊣ F) [full F] [faithful F] [preserves_limits_of_shape (discrete walking_pair) L] : cartesian_closed_functor F := { comparison_iso := λ A, exp_comparison_iso_of_frobenius_morphism_iso F h _ } end category_theory
7db8acfbbbaf76ae19c7623666cd106e68966b23
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_877.lean
06959d055fe0925826963dbba2adbe28d6f86baa
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
204
lean
import algebra.ring namespace my_ring variables {R : Type*} [ring R] -- BEGIN lemma one_add_one_eq_two : 1 + 1 = (2 : R) := by refl theorem two_mul (a : R) : 2 * a = a + a := sorry -- END end my_ring
8363cae6846da38d2eb6c5f2e0057969b8b20604
c021f28e58f8acea72ed5cf5cc1a92c725760ea5
/src/Gröbner.lean
07584d4c999c2008887efc4b27a5366c4e63c8e2
[]
no_license
robertylewis/ring_equational_reasoner
3233b9f3578d0d0d2f38551062b2c37c747f0e0d
beb35c80a69d74c9551aeed3e17aa2071b5842c3
refs/heads/master
1,599,224,363,883
1,572,960,322,000
1,572,960,322,000
219,737,924
0
0
null
1,572,956,310,000
1,572,956,307,000
null
UTF-8
Lean
false
false
25,874
lean
import group_theory.coset ring_theory.ideals data.int.modeq group_theory.quotient_group tactic.fin_cases tactic.tidy data.mv_polynomial tactic.find open tactic prod native environment interactive lean.parser ideal classical lattice declaration rbtree local infixl ` ⬝ ` := has_mul.mul local notation x`²`:99 := x⬝x local notation ` ` binders ` ↦ ` f:(scoped f, f) := f local notation `⟮` binders ` ↦ ` f:(scoped f, f) `⟯`:= f def flip_over_2 {A B C D} (f: A→B→C→D) := z x y ↦ f x y z infixl ` @₁`:99 := flip infixl ` @₂`:99 := flip_over_2 infixr ` ∘₂ `:80 := (∘)∘(∘) instance {X} : monoid (list X) := { one := [], mul := (++), one_mul := by safe, mul_one := list.append_nil, mul_assoc := list.append_assoc, } instance endomonoid {t} : monoid (t → t) := { one := id, mul := (∘), mul_assoc := function.comp.assoc, one_mul := function.comp.left_id, mul_one := function.comp.right_id, } --option.cases_on has typing problems. def option.maybe {A B} (no: B) (yes: A→B) : option A → B | none := no | (some a) := yes a def ifoldl_help {S T} (f: ℕ→S→T→T) : ℕ → list S → T → T | i [] r := r | i (x::s) r := ifoldl_help (i+1) s (f i x r) def list.ifoldl {S T} (f: ℕ→S→T→T) := ifoldl_help f 0 def list.imap {S T} (f: ℕ→S→T) (s: list S) := (s.ifoldl (list.cons ∘₂ f) []).reverse universe U def list.mfilter_map {A B : Type U} {M} [monad M] (f: A → M (option B)) : list A → M (list B) | [] := pure[] | (a::s) := do fa ← f a, s' ← s.mfilter_map, pure (fa.maybe s' ⟮b ↦ b::s'⟯) @[simp] def map₂_default {X Z} (d) (f: X → X → Z) : list X → list X → list Z | [] [] := [] --| s l := f ((s.nth 0).get_or_else d) ((l.nth 0).get_or_else d) :: map₂_default s.tail l.tail | [] (y::ys) := f d y :: map₂_default [] ys | (x::xs) [] := f x d :: map₂_default xs [] | (x::xs) (y::ys) := f x y :: map₂_default xs ys using_well_founded wf_tacs def trim_tail {X} [decidable_eq X] (x) (s: list X) := (s.reverse.drop_while (=x)).reverse --unique_pairs[xⱼ | j] = [(xᵢ,xⱼ) | i<j] def list.unique_pairs {T} : list T → list (T×T) | [] := [] | (x::xs) := xs.map⟮y↦ (x,y)⟯ ++ xs.unique_pairs @[priority 0] instance to_string_of_repr {X} [has_repr X] : has_to_string X := ⟨repr⟩ @[priority 0] meta instance format_of_repr {X} [has_repr X] : has_to_tactic_format X := ⟨has_to_tactic_format.to_tactic_format ∘ repr⟩ -- infixr ` ∷ `:67 := (++)∘repr -- --set_option pp.all true -- def replace_1_: list char → string -- --| ('+'::' '::'-'::s) := "- "++ replace_minus s -- | [] := "" -- | (a::s) := match if a≠' ' then none else match s with -- | [] := none -- | (b::s) := if b≠'1' then none else match s with -- | [] := none -- | (c::s) := if c≠' ' then none else -- have hint: s.sizeof < a.val+ (1+s.sizeof), from by {simp[has_lt.lt,nat.lt], rw (_:nat.succ _=0+_), rw (_:1+_=nat.succ _), apply nat.add_le_add_right, tidy, rw nat.add_comm}, -- some (' '∷ replace_1_ s) -- end end with -- | none := a ∷ replace_1_ s -- | some s := s --–Monomials are now represented by lists, which are thought to be zero extended. Trailing zeros are normalized away. def monomial := list ℕ namespace monomial def deg (m: monomial) := list.sum m def variable_name: ℕ → string | 0 := "x" | 1 := "y" | 2 := "z" | n := (char.of_nat (121-n)).to_string def rise_digit (n: char) := ("⁰¹²³⁴⁵⁶⁷⁸⁹".to_list.nth n.to_string.to_nat).get_or_else '?' def rise_number (n: string) := (n.to_list.map rise_digit).as_string instance monomial.has_repr: has_repr monomial := ⟨ m ↦ m.ifoldl⟮j e ↦ ite (e=0) id (++ variable_name j ++ ite (e=1) "" (rise_number (repr e)))⟯ "" ⟩ instance: has_one monomial := ⟨[]⟩ instance: has_mul monomial := ⟨map₂_default 0 (+)⟩ --no need to trim instance: has_div monomial := ⟨trim_tail 0 ∘₂ map₂_default 0 ⟮x y ↦ x-y⟯⟩ def gcd (n m : monomial) : monomial := trim_tail 0 (list.map₂ min n m) --no need to extend def lcm (n m : monomial) : monomial := map₂_default 0 max n m --no need to trim def dvd': monomial → monomial → bool | [] _ := tt | (n::ns) m := n ≤ (m.nth 0).get_or_else 0 ∧ dvd' ns m.tail def dvd := n m ↦ (dvd' n m : Prop) instance: has_dvd monomial := ⟨dvd⟩ instance: decidable_rel dvd := by unfold dvd; apply_instance --–Orders should be admissible (unit least and multiplication monotonous). class order := (lt: monomial → monomial → Prop) (decidable: decidable_rel lt) def lex: order := { lt := list.lex (<), decidable := infer_instance, } def deg_lex: order := { lt := n m ↦ deg n < deg m ∨ (deg n = deg m ∧ list.lex (<) n m), decidable := _ _↦ by apply or.decidable, } end monomial @[reducible] private def mo := monomial.order --–Polynomials (this ended up essentially reimplementing very basics of rbmap equivalently, because I didn't find rbmap early enough) --Reverse order to have the leading term first. def poly.less [mo] {K} (x y : K×monomial) := monomial.order.lt y.snd x.snd def poly [mo] (K) [ring K] := rbtree (K×monomial) poly.less namespace poly --K ∈ Type 0 because otherwise combination with tactics gets problematic. variables {K: Type} [ring K] [decidable_eq K] [o:mo] (P R : poly K) instance [mo] : has_lt monomial := ⟨monomial.order.lt⟩ instance [mo] : has_le monomial := ⟨ n m ↦ ¬n>m ⟩ instance decidable_lt [mo] : @decidable_rel monomial (<) := monomial.order.decidable instance decidable_le [mo] : @decidable_rel monomial (≤) := by apply_instance instance decidable_less : decidable_rel (@less o K) := _ _↦ by unfold less; apply_instance def coef (m) := ((P.find (0,m)).get_or_else (0,m)).fst --Value 0 should not be inserted, but rbtree lacks removal rutines. Since full simplification will rebuild a polynomial from scratch, extra zeros should not add up too badly. def update (m) (f: K→K) : poly K := let k := f (coef P m) in P.insert (k,m) def monom [mo] (m) : poly K := rbtree_of[m]less instance[mo] : has_coe monomial (poly K) := ⟨ m↦ monom (1,m) ⟩ --Let f' = (f; 0↦id). Then combine@₂f maps Σ pⱼ⬝mⱼ and Σ rⱼ⬝mⱼ to Σ f' pⱼ rⱼ ⬝ mⱼ (...assuming unsoundly that there's no explicit 0 coefficients...exact behavior depends on what the representation happens to be). def combine (f: K→K→K) : poly K := P.fold⟮p R' ↦ update R' p.snd (f p.fst)⟯ R def map_poly (f: K→K) : poly K := combine P P _↦f instance[mo] : has_zero (poly K) := ⟨rbtree_of[]less⟩ instance[mo] : has_one (poly K) := ⟨monom (1,1)⟩ instance[mo] : has_add (poly K) := ⟨combine @₂ (+)⟩ instance[mo] : has_neg (poly K) := ⟨map_poly @₁ k↦-k⟩ instance[mo] : has_sub (poly K) := ⟨ P R ↦ P + -R ⟩ instance[mo] : has_mul (poly K) := ⟨ P↦ fold⟮m↦ P.fold⟮n↦ (+monom (m⬝n))⟯⟯ @₁0 ⟩ instance[mo] : has_scalar K (poly K) := ⟨ k↦ map_poly @₁ (⬝k) ⟩ instance[mo] : has_pow (poly K) ℕ := ⟨ P n ↦ (list.repeat P n).foldl (⬝)1 ⟩ instance[mo] [has_repr K] : has_repr (poly K) := ⟨ P↦ match P.to_list.filter⟮p:K×_ ↦ p.fst ≠ 0⟯ with | [] := "0" | (m::ms) := ms.foldl⟮s p ↦ s ++" + "++ repr p.fst ++" "++ repr p.snd⟯ (repr m.fst ++" "++ repr m.snd) end⟩ def lead_term := (P.fold⟮p:K×_ ↦ option.maybe (if p.fst = 0 then none else some p) some⟯ none).maybe (0,1) id def lead_coef := P.lead_term.fst def lead_mono := P.lead_term.snd def is0 := lead_coef P = 0 instance decidable_is0: decidable P.is0 := by unfold is0; apply_instance def is_const := lead_mono P = 1 instance decidable_is_const: decidable P.is_const := by unfold is_const; apply_instance attribute [derive decidable_eq] rbnode instance[mo] : decidable_eq (poly K) := by apply_instance instance[mo] : inhabited (poly K) := ⟨0⟩ variable [has_repr K] def see {X Y} [has_repr X] [has_repr Y] (m:Y) (x:X) := _root_.trace (repr m ++ repr x) x private def proof[mo] (K)[ring K] := list (poly K) def poly_mem[mo] (K)[ring K] := poly K × proof K def polys[mo] (K)[ring K] := list (poly_mem K) instance hrp[mo] : has_repr (proof K) := by unfold proof; apply_instance--TODO remove after debug def poly_mem.is0[mo] (P: poly_mem K) := is0 P.fst instance[mo] (P: poly_mem K) : decidable P.is0 := by unfold poly_mem.is0; apply_instance instance evvk[mo] : inhabited (poly_mem K) := ⟨ (0,[])⟩ --Construct trivial proof by cloning a proof from non-empty list. def proof_triv[mo] (B: polys K. assumption) : proof K := B.head.snd.map⟮_↦0⟯ def is_triv[mo] : proof K → bool | [] := tt | (p::ps) := is0 p ∧ is_triv ps def proof_add[mo] (p₁ p₂ : proof K) (f: poly K → poly K) := p₁.map₂ (+) (p₂.map f) --Compute the S-polynomial of monic polynomials with membership proof. def monicS[mo] : poly_mem K → poly_mem K → poly_mem K | (P,pP) (R,pR) := let p:= lead_mono P, r:= lead_mono R, m:= p.lcm r, mp:= monom ((1:K), m/p), mr:= monom ((1:K), m/r) in (P⬝mp - R⬝mr, proof_add (pP.map (⬝mp)) pR (⬝ (-mr))) --Accumulates proof to show that if P→R then R - P ∈ ⟨B⟩. meta def simplify_leading_loop[mo] (B: polys K) : poly_mem K → poly_mem K | (P, proof) := let p := P.lead_mono in match B.filter ((∣p)∘lead_mono∘fst) with | [] := (P, proof) | (b,prf) ::_ := let c := -monom (lead_coef P, p / lead_mono b) in simplify_leading_loop (P + b⬝c, proof_add proof prf (⬝c)) end --B must be a non-empty list of monic (and ≠0) polynomials. meta def simplify_leading[mo] (B: polys K) (P: poly_mem K) : poly_mem K := match B.filter (is_const ∘ fst) with | (_,prf) ::_ := (0, proof_add P.snd prf (⬝ (-P.fst))) | _ := simplify_leading_loop B P end meta def simplify_loop[mo] (B) : poly K → poly_mem K → poly_mem K | R P := if P.is0 then (R, P.snd) else let (P,prf) := simplify_leading B P, p := monom P.lead_term in simplify_loop (R+p) (P-p, prf) --Return fully simplified R←P and proof that R - P ∈ ⟨B⟩. Input P comes without membership proof, because simplification should be applicable to arbitrary polynomials. meta def simplify[mo] (B: polys K) (P) := simplify_loop B 0 (P, proof_triv) variable[field K] --scale_monic 0 := 0 def scale_monic[mo] : poly_mem K → poly_mem K | (P,prf) := let c := P.lead_coef ⁻¹ in (c•P, prf.map ((•)c)) meta def simplify_basis_loop[mo] (simp: polys K → poly_mem K → poly_mem K) : ℕ → polys K → polys K | 0 B := B | l [] := sorry -- l ≤ B.length | l (P::B) := let P' := simp B P, B' := ite P'.is0 B (B++[scale_monic P']) in simplify_basis_loop (if is_triv (P.snd.map₂⟮x y ↦ x-y⟯ P'.snd) then l-1 else B'.length) B' --For each element of B, if S simplifies the leading term, then simplify additionally with other elements of the basis. meta def simplify_basis_by[mo] (S: poly_mem K) (B: polys K) := simplify_basis_loop⟮B P ↦ let P' := simplify_leading [S] P in if is_triv P'.snd then P else simplify_leading B P'⟯ B.length B --Interreduce B. meta def simplify_basis[mo] (B: polys K) := simplify_basis_loop (simplify_loop @₁0) B.length B --main loop private meta def go[mo] : polys K → list (poly_mem K × poly_mem K) → polys K | G [] := G | G ( (p₁,p₂) ::ps) := let S := scale_monic (simplify_leading G (monicS p₁ p₂)) in if S.is0 then go G ps else let G := simplify_basis_by S G in go (S::G) (ps ++ G.map⟮P↦ (P,S)⟯) meta def «Gröbner basis of»[mo] (B: list (poly K)) := let B := B.filter (not∘is0), B1 := B.imap⟮i b ↦ scale_monic (b, (B.map⟮_↦ (0: poly K)⟯).update_nth i 1)⟯ in simplify_basis (go B1 B1.unique_pairs) notation `Gröbner_basis_of` := «Gröbner basis of» --Lean's letter recognition is broken! It is not just an implementation mistake, but it is even specified in an adhoc way – see https://leanprover.github.io/reference/lexical_structure.html#identifiers – which is incompatible with Unicode. Not only a huge number of letters is ignored but also some non-letters included (though correctly called just letterlike) : def ℡⅋℀ := "Telephone sign ǝʇ “account” are letters only in Lean!" --Inclusion of non-letters means that Lean can't be said to support a subset of Unicode. FYI: Unicode is about semantics of code points (numbers). UTF-8 is a character encoding (mapping between bytes and numbers) that Lean does use. Observations here hold at the time of writing and hopefully not in the future. --Tästä voisi johtaa tyyliin ringa-taktiikan. Sievennetään kaikkia ... hmm, miten sievennyskelpoiset lausekkeet määrätään? Kertoimien tulee olla kunnasta, mutta muuttujia saa käsitellä vain rengasoperaatioilla. Teoreettisesti nättiä olisi yleistää hieman ja ratkaista renkaiden ehdolliset sanaongelmat, mutta sehän edellyttäisi paljon lisää koodausta! --Sitten pitää ratkaista, miten termien triviaali sievennys kuten x+y-x=y hoidetaan. Koska tulos tiedetään aina, voidaan turvallisesti turvautua ring-taktiikkaan. --Luetaan tavoitetta kunnes vastaan tulee +,⬝,- (tärkeää on, että löydetään maksimaalinen termi sievennettäväksi—tämän pitäisi riittää siihen, koska tietenkään päälioperaatio ei tällöin voi olla jokin sellainen, jota ei osata käsitellä). Huom. - voi esiintyä sekä unaarisena että binäärisenä. Seuraavaksi tarkistetaan, että alitermi on kuntatyyppiä...mutta tämä rajoittaa käytettävyyttä melko merkittävästi. Teoriassa voisi vaatia, että tyyppi on vaihdannainen rengas ja K-moduli jonkin kunnan K suhteen, ja K:lta vaaditaan lisäksi päätettävä yhtyvyys. Jotta tästä teoriasta tulee käytäntöä, lienee vaadittava, että käyttäjä syöttää kunnan (ℚ voi olla oletusarvo). meta def 𝔼 (pre) := to_expr pre tt ff --meta def childs (e: expr) := (e.mfoldl⟮c s ↦ [list.cons s c]⟯ []).head meta def childs: expr → list expr | (expr.app f p) := [f,p] | (expr.pi _ _ S T) := [S,T] | (expr.elet _ t v b) := [t,v,b] --Does this work with infer_type? | (expr.macro _ cs) := cs | _ := [] notation `~`x := pure x notation `ᵘᵖ ` m := monad_lift m @[reducible] meta def ST := state_t (list expr) tactic --Run reaction if state is not []. meta def if_not_found (reaction: ST unit) : ST unit := do s ← state_t.get, when (s=[]) reaction meta def fbs_loop {T} (t) (test: (expr → ST T) → expr → ST T) (atoms: rb_set expr) : bool → expr → ST unit | layer's_top e := when (¬ atoms.contains e) (test⟮x ↦ t<$ if x≠e then fbs_loop ff x else (childs x).mmap' (if_not_found ∘ fbs_loop tt) ⟯ e >> if_not_found (when layer's_top (test⟮e' ↦ when (e≠e') (state_t.put[e]) $>t⟯ e $> ()))) --Finds some minimal subterm accepted by test while treating terms in the set atoms as such. Parameter t is just an inhabitance proof. meta def find_bottom_simplifiable {T} (t:T) (test) (atoms) : expr → tactic (option expr) | e := prod.fst <$> (do fbs_loop t test atoms tt e, g ← state_t.get, ~ g.nth 0 ).run[] meta def prepare_loop {T} (var: ℕ→T) (test: (expr → ST T) → expr → ST T) : expr → ST T | e := test⟮x ↦ if x≠e then prepare_loop x else do vs ← state_t.get, let i := vs.index_of x, when (i = vs.length) (state_t.put (vs++[x])) $> var i ⟯e --Transform (top layer of) e to its T-representation according to test, with alien subterms replaced by variables generated from var with syntactic equality preserved. Second component of the return value is list of the replaced alien terms. meta def prepare {T} (var: ℕ→T) (test) (e) := (prepare_loop var test e).run[] --Like mapping the above, but naming of the alien terms is consistent. meta def prepares {T} (var: ℕ → T) (test) (es: list expr) := (es.mmap (prepare_loop var test)).run[] meta def simplify_by_loop {T} (var: ℕ→T) (test: (expr → ST T) → expr → ST T) (simp: expr → T → tactic expr) : rb_set expr → tactic unit | simplified := do e ← target, x ← find_bottom_simplifiable (var 0) test simplified e, x.maybe (~())⟮x ↦ do (x',g) ← prepare var test x, proof ← simp x x', rewrite_target proof, `(%%_ = %%s) ← infer_type proof, simplify_by_loop (simplified.insert s)⟯ --Warning: in practise this interface turned out to behave ugly! This is a simplifier skeleton whose advantage over simp is that pattern matching and rule selection can be done programmatically. (For example simp could often do nothing with a Gröbner basis represented as simplifying equations, because non-syntactic pattern matching is needed to use them.) This functions like simp only [...]. The actual (single step) simplifier is given as a parameter. Its operation is extended by searching the proof target for simplifiable terms and calling the simplifier for all of these bottom up. --Parameters --T: an auxiliarity term representation that the simplifier may choose as it likes. --var: a stream of distinct variables. --test recursor ∈ expr → a_monad T : transforms a top operation of an input term into T-representation calling recursor for the childs, or for the whole term if it is alien. See test_poly for an example. --simp: from original expression E and its T-representation produce a proof that E = simplified E. Failed: Variable var i should be represented by a metavariable whose name ends with mk_numeral i, (or var 0, ..., var n may be represented by quantifying ∀x₀...∀xₙ ???). meta def simplify_by {T} (var: ℕ→T) (test) (simp) := simplify_by_loop var test simp mk_rb_set --Notes: Examining term structure and mapping it to T was combined into test. Original term is given to simp, because T-representation may be lossy. However if orig. rep. is needed (Gröbner bases avoid it by using ring), examination of it usually repeats. It even turned out that due to consistent alien term naming the second parameter of simp is practically useless. Currently test can work in ST, though safer would be to require polymorphicity over monad transformer on top of tactic. The tedious part (in addition to the core simplification in T) is producing the proof term in simp. Could this be simplified in a suitable monad? meta def test_instance (i) := (𝔼 i >>= mk_instance) $> tt <|> ~ff meta def test_poly[mo] [reflected K] (r: expr → ST (poly K)) (e: expr) : ST (poly K) := match e with | `(%%x ⬝ %%y) := (⬝) <$> r x <*> r y | `(%%x + %%y) := (+) <$> r x <*> r y | `(%%x - %%y) := ⟮x y ↦ x-y⟯ <$> r x <*> r y | `(- %%x) := ⟮x ↦ -x⟯ <$> r x | `(%%x ^ %%n) := do N ←ᵘᵖ infer_type n, if N ≠ `(ℕ) ∨ n.has_var ∨ n.has_local then r e else do n ←ᵘᵖ eval_expr ℕ n, (^n) <$> r x | e := do E ←ᵘᵖ infer_type e, if E ≠ reflect K ∨ e.has_var ∨ e.has_local then r e else do k ←ᵘᵖ eval_expr K e, ~monom (k,[]) end meta def test_poly_typed[mo] [reflected K] (M: option expr) (r: expr → ST (poly K)) (e) : ST (poly K) := do E ←ᵘᵖ infer_type e, ok ← match M with some M := ~(E=M : bool) | _ :=ᵘᵖ band <$> test_instance``(ring %%E) <*> test_instance``(module %%(reflect K) %%E) end, (ite ok test_poly id) r e --X' i is the iᵗʰ variable "Xᵢ". def X'[mo] (i:ℕ) : poly K := monom (1, ((list.cons 0)^i) [1]) meta def represent_mono[mo] (r: has_reflect K) (M:expr) (vs: list expr) (m: monomial) : tactic expr := m.ifoldl ⟮x p e ↦ if p=0 then e else do e←e, 𝔼``(%%e ⬝ %%(vs.nth x).iget ^ %%(reflect p))⟯ (𝔼``(1:%%M)) meta def represent_poly[mo] [r: has_reflect K] (M:expr) (vs: list expr) (P: poly K) : tactic expr := P.fold ⟮m e ↦ let c:= m.fst in if c=0 then e else do e←e, mono ← represent_mono r M vs m.snd, 𝔼``(%%e + %%(reflect c)⬝%%mono)⟯ (𝔼``(0:%%M)) --TODO Use module product • to multiply mono by c. Problem is that then ring doesn't work! meta def local_equations_of_type (M) := do ls ← local_context, ls.mfilter⟮a ↦ do b ← infer_type a, match b with `(%%x = %%y) := do Y ← infer_type y, ~Y=M | _:=~ff end⟯ --Return a proof of goal found by the given tactic solve. meta def prove_by (solve: tactic unit) (goal: tactic expr) := do n ← get_unused_name, goal >>= assert n, solve, proof ← get_local n, --clear proof, --TODO How to clean the local context while keeping proof usable? ~proof namespace proof_building_blocks lemma mul_sub_is_0 {M} [ring M] [module K M] {x y O : M} (c: M) (o0: O=0) (h: x=y) : O - c⬝(x-y) = 0 := by simp[*] lemma combines {M} [add_comm_group M] [module K M] {P R O : M} (pr: P-R = O) (o0: O = 0) : P = R := by rw (by simp : P = P-R + R);simp[*] end proof_building_blocks open proof_building_blocks --Compute a Gröbner basis from polynomial equations E and return a reducer suitable for simplify_by that uses the computed basis. meta def verifying_reducer[mo] [reflected K] [r: has_reflect K] (M) (E: list expr) : tactic (expr → poly K → tactic expr) := do let test: (expr → ST (poly K)) → _ := test_poly_typed (option.some M), be ← E.mmap⟮p ↦ do e ← infer_type p, match e with `(%%x = %%y) := 𝔼``(%%x - %%y) | _:=sorry end⟯, ((B: list (poly K)), vs) ← prepares X' test be, let G := Gröbner_basis_of B, ~ pe _ ↦ do --TODO There should be nicer way to keep track of alien subterms. Either variables in polynomials should have arbitrary names (ideal solution) or everything should work inside ST. (P, vs) ← (prepare_loop X' test pe).run vs, let (R, coef) := simplify G P, --R = P + coef•(fⱼ - gⱼ)ⱼ --P - R =ʳⁱⁿᵍ= -coef•(fⱼ - gⱼ)ⱼ = “coef•0” = 0 ⟹ P=R re ← represent_poly M vs R, ce ← coef.mmap(represent_poly M vs), K0is0 ← 𝔼``(rfl : (0:%%(reflect K)) = 0), step2 ← (ce.zip E).mfoldl ⟮prf cb ↦ 𝔼``(@mul_sub_is_0 %%(reflect K) infer_instance infer_instance infer_instance infer_instance %%M infer_instance infer_instance _ _ _ %%cb.fst %%prf %%cb.snd)⟯ K0is0, `(%%ce_be = %%_) ← infer_type step2, ring_step ← prove_by`[ {ring}] (𝔼``(%%pe - %%re = %%ce_be)), 𝔼``(@combines %%(reflect K) infer_instance infer_instance infer_instance infer_instance %%M infer_instance infer_instance _ _ _ %%ring_step %%step2) meta def exactℚ := `[exact ℚ] meta def ringa (K:Type. exactℚ)[reflected K] [has_reflect K] [field K] [decidable_eq K] [has_repr K/-debug-/] [mo] : tactic unit := do t ← target, --"find_top_simplifiable" would be more expected behavior...if it existed e ← find_bottom_simplifiable (0: poly K) (test_poly_typed none) mk_rb_set t, if e=none then fail"nothing to simplify in target" else do M ← infer_type e.iget, B ← local_equations_of_type M, if B=[] then `[ring] else do --Do not fail to preserve composability. reducer ← verifying_reducer M B, simplify_by (X': ℕ → poly K) (test_poly_typed (some M)) reducer, `[try {ring}] #check Gröbner_basis_of --Test cases instance use_this_order := monomial.deg_lex variables {v x y z : ℚ} {f: ℚ→ℚ} --These delegate to ring tactic example: (x+y)⬝(x-y) = x² - y² := by ringa example: f(2⬝x) = f(x+x) := by ringa --These don't example (_:v=z) : (x+y)⬝(x-y) = x² - y² := by ringa example (_:v=z) : f(2⬝x) = f(x+x) := by ringa --Core functionality tests example (_: x+y = z) (_: x² + y² = z²) : x⬝y = 0 := by ringa example (_: x⬝y² = x+y) (_: x²⬝y = x² + y²) : y^5 = (2⬝x-1)⬝(2⬝y-1)/2 - 1/2 := by ringa example (_: x⬝y² = x+y) (_: x²⬝y = x+1) : y = x² := by ringa example (_: z⬝x=y) (_: y=x²) (_: v²=2) : x⬝(2⬝z-x-x) = 0 := by ringa example (_: x²⬝y = x²) (_: x⬝y² = y²) : (x+y)⬝(x-y) + x² = x^3 := by ringa --Iteration tests example (_: x=y) : x⬝f(2⬝x² - y²) - y⬝f(x⬝y) = 0 := by ringa example (_: x=y) : x⬝f(x-y) - y⬝f(x-x) = 0 := by ringa example (_: x=y+1) : (x-1)⬝f(2⬝x-1) - y⬝f(x² - y²) = 0 := by ringa example (_: x²+y² = z²) (_: x^3 + y^3 = z^3) (_: x⬝y = 1) : f(x + y + f(2/3)) = f(f(z²) - 2⬝z) := by ringa --In algebras over ℚ open polynomial example {P: polynomial ℚ} (_: X² - X - 1 = (0: polynomial ℚ)) (_: P = 1-X) : P² = P+1 := by ringa --Is it worth to handle the situation of inconsistent axioms? example (_: x²+3⬝x+1 = 0) (_: y²+3⬝y+1 = 0) (_: x^5 + y^5 = 0) : x-y = 1 := by ringa #check ringa --∛2̅+̅√̅5̅ + ∛2̅-̅√̅5̅ = 1 --example (_: x²=5) (_: y^3 = 2+x) (_: z^3 = 2-x) : y+z = 1 := by ringa end poly open poly instance {K:Type} [field K] [decidable_eq K] [has_repr K] [mo] : has_repr(poly_mem K) := --by unfold poly_mem; apply_instance ⟨ x ↦ repr x.fst ⟩ instance {K:Type} [field K] [decidable_eq K] [has_repr K] [mo] : has_repr(polys K) := by unfold polys; apply_instance instance use_this := monomial.deg_lex def lm (m: list ℕ) : poly ℚ := monom (1,m) def a := lm[2] +3⬝lm[1]+lm[] def b := lm[0,2] +3⬝lm[0,1]+lm[] def c := lm[5] + lm[0,5] #eval simplify(Gröbner_basis_of[a,b]) c --#eval Gröbner_basis_of[a,b,c] --Time out just because the algorithm is so slow! def α := lm[0,0,2] + lm[0,2] - lm[2] def β := lm[0,0,3] + lm[0,3] - lm[3] def γ := lm[0,1,1] - 1 #eval (Gröbner_basis_of[α,β,γ]) #eval simplify(Gröbner_basis_of[α,β,γ]) (lm[2]) def P := lm[2,1] + ((1:ℚ)/2)•lm[2] def R := lm[1,2] + lm[0,2] def S := -lm[2,2] + lm[1,1] + lm[2] #eval (Gröbner_basis_of[P,R]) #eval simplify (Gröbner_basis_of[P,R]) (S²) def B := [lm [3] -1, lm[2]+lm[1,1], lm[2]+lm[1,0,1]+lm[0,0,2]] #eval B #eval Gröbner_basis_of B #eval P²⬝R #eval Gröbner_basis_of$ [lm [3] -1, lm[2]+lm[1,1], lm[2]+lm[1,0,1]+lm[0,0,2], lm [0,3] -1, lm[0,2]+lm[0,1,1]+lm[0,0,2], lm [0,0,3] -1].map(⬝1) #eval Gröbner_basis_of[lm [3] -1, lm[2]+lm[1,1]+lm[0,2], lm[2]+lm[1,0,1]+lm[0,0,2], lm [0,3] -1, lm[0,2]+lm[0,1,1]+lm[0,0,2], lm [0,0,3] -1] #eval Gröbner_basis_of(B++[P²⬝R]) --#eval Gröbner_basis_of(P²⬝R::B) #eval (lm[] + 0).lead_coef #eval (2⬝lm[4,2] + lm[3,4])².fold((++)∘repr) "" #eval (2⬝lm[4,2] + lm[3,4])².lead_mono #eval (P + 3⬝P² + P²)²
4bff569c7c16d40f98aa56c81d240bd00efc405f
367134ba5a65885e863bdc4507601606690974c1
/src/data/nat/prime.lean
38fff598fa0b9d49abd8c5132eebe8fdc7bc58fe
[ "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
30,432
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.nat.sqrt import data.nat.gcd import algebra.group_power import tactic.wlog import tactic.norm_num /-! # Prime numbers This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations All the following declarations exist in the namespace `nat`. - `prime`: the predicate that expresses that a natural number `p` is prime - `primes`: the subtype of natural numbers that are prime - `min_fac n`: the minimal prime factor of a natural number `n ≠ 1` - `exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers - `factors n`: the prime factorization of `n` - `factors_unique`: uniqueness of the prime factorisation -/ open bool subtype open_locale nat namespace nat /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ @[pp_nodot] def prime (p : ℕ) := 2 ≤ p ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.two_le {p : ℕ} : prime p → 2 ≤ p := and.left theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le instance prime.one_lt' (p : ℕ) [hp : _root_.fact p.prime] : _root_.fact (1 < p) := hp.one_lt lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 := ne.symm $ ne_of_lt hp.one_lt theorem prime_def_lt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (decidable.lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ 2 ≤ p ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := by { rintro rfl, revert h, dec_trivial } theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := lt_of_succ_lt pp.one_lt theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < pred p := lt_pred_iff.2 pp.one_lt theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_two_le {p m : ℕ} (pp : prime p) (H : 2 ≤ m) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime_dvd_prime_iff_eq {p q : ℕ} (pp : p.prime) (qp : q.prime) : p ∣ q ↔ p = q := dvd_prime_two_le qp (prime.two_le pp) theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.one_lt) $ le_of_dvd dec_trivial d theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) := λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $ by simpa using (dvd_prime_two_le h a1).1 (dvd_mul_right _ _) lemma not_prime_mul' {a b n : ℕ} (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ prime n := by { rw ← h, exact not_prime_mul h₁ h₂ } section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ n < k * k) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial /-- If `n < k * k`, then `min_fac_aux n k = n`, if `k | n`, then `min_fac_aux n k = k`. Otherwise, `min_fac_aux n k = min_fac_aux n (k+2)` using well-founded recursion. If `n` is odd and `1 < n`, then then `min_fac_aux n 3` is the smallest prime factor of `n`. -/ def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} /-- Returns the smallest prime factor of `n ≠ 1`. -/ def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 0 := rfl | 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl | (n+2) := have 2 ∣ n + 2 ↔ 2 ∣ n, from (nat.dvd_add_iff_left (by refl)).symm, by simp [min_fac, this]; congr private def min_fac_prop (n k : ℕ) := 2 ≤ k ∧ k ∣ n ∧ ∀ m, 2 ≤ m → m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : 2 ≤ n) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m, 2 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases h : n < k*k; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_two_le pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases dk : k ∣ n; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq], by_cases d2 : 2 ∣ n; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, 2 ≤ m → m ∣ n → min_fac n ≤ m := by by_cases n1 : n = 1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : 0 < min_fac n := by by_cases n1 : n = 1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ 2 ≤ p ∧ min_fac p = p := ⟨λ pp, ⟨pp.two_le, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.one_lt in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ /-- This instance is faster in the virtual machine than `decidable_prime_1`, but slower in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : 2 ≤ n) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm lemma min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬ prime n) : min_fac n ≤ n / min_fac n := match min_fac_dvd n with | ⟨0, h0⟩ := absurd pos $ by rw [h0, mul_zero]; exact dec_trivial | ⟨1, h1⟩ := begin rw mul_one at h1, rw [prime_def_min_fac, not_and_distrib, ← h1, eq_self_iff_true, not_true, or_false, not_le] at np, rw [le_antisymm (le_of_lt_succ np) (succ_le_of_lt pos), min_fac_one, nat.div_one] end | ⟨(x+2), hx⟩ := begin conv_rhs { congr, rw hx }, rw [nat.mul_div_cancel_left _ (min_fac_pos _)], exact min_fac_le_of_dvd dec_trivial ⟨min_fac n, by rwa mul_comm⟩ end end /-- The square of the smallest prime factor of a composite number `n` is at most `n`. -/ lemma min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬ prime n) : (min_fac n)^2 ≤ n := have t : (min_fac n) ≤ (n/min_fac n) := min_fac_le_div w h, calc (min_fac n)^2 = (min_fac n) * (min_fac n) : pow_two (min_fac n) ... ≤ (n/min_fac n) * (min_fac n) : mul_le_mul_right (min_fac n) t ... ≤ n : div_mul_le_self n (min_fac n) @[simp] lemma min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 := begin split, { intro h, by_contradiction hn, have := min_fac_prime hn, rw h at this, exact not_prime_one this, }, { rintro rfl, refl, } end @[simp] lemma min_fac_eq_two_iff (n : ℕ) : min_fac n = 2 ↔ 2 ∣ n := begin split, { intro h, convert min_fac_dvd _, rw h, }, { intro h, have ub := min_fac_le_of_dvd (le_refl 2) h, have lb := min_fac_pos n, -- If `interval_cases` and `norm_num` were already available here, -- this would be easy and pleasant. -- But they aren't, so it isn't. cases h : n.min_fac with m, { rw h at lb, cases lb, }, { cases m with m, { simp at h, subst h, cases h with n h, cases n; cases h, }, { cases m with m, { refl, }, { rw h at ub, cases ub with _ ub, cases ub with _ ub, cases ub, } } } } end end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).one_lt, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : 2 ≤ n) (np : ¬ prime n) : ∃ m, m ∣ n ∧ 2 ≤ m ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).two_le, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : 2 ≤ n) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ /-- Euclid's theorem. There exist infinitely many prime numbers. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ p, n ≤ p ∧ prime p := let p := min_fac (n! + 1) in have f1 : n! + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ factorial_pos _, have pp : prime p, from min_fac_prime f1, have np : n ≤ p, from le_of_not_ge $ λ h, have h₁ : p ∣ n!, from dvd_factorial (min_fac_pos _) h, have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _), pp.not_dvd_one h₂, ⟨p, np, pp⟩ lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := (nat.mod_two_eq_zero_or_one p).elim (λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm) or.inr theorem coprime_of_dvd {m n : ℕ} (H : ∀ k, prime k → k ∣ m → ¬ k ∣ n) : coprime m n := begin cases eq_zero_or_pos (gcd m n) with g0 g1, { rw [eq_zero_of_gcd_eq_zero_left g0, eq_zero_of_gcd_eq_zero_right g0] at H, exfalso, exact H 2 prime_two (dvd_zero _) (dvd_zero _) }, apply eq.symm, change 1 ≤ _ at g1, apply (lt_or_eq_of_le g1).resolve_left, intro g2, obtain ⟨p, hp, hpdvd⟩ := exists_prime_and_dvd g2, apply H p hp; apply dvd_trans hpdvd, { exact gcd_dvd_left _ _ }, { exact gcd_dvd_right _ _ } end theorem coprime_of_dvd' {m n : ℕ} (H : ∀ k, prime k → k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd $ λk kp km kn, not_le_of_gt kp.one_lt $ le_of_dvd zero_lt_one $ H k kp km kn theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 := div_lt_self dec_trivial (min_fac_prime dec_trivial).one_lt /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → list ℕ | 0 := [] | 1 := [] | n@(k+2) := let m := min_fac n in have n / m < n := factors_lemma, m :: factors (n / m) lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p | 0 := λ p, false.elim | 1 := λ p, false.elim | n@(k+2) := λ p h, let m := min_fac n in have n / m < n := factors_lemma, have h₁ : p = m ∨ p ∈ (factors (n / m)) := (list.mem_cons_iff _ _ _).1 h, or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial) mem_factors lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n | 0 := (lt_irrefl _).elim | 1 := λ h, rfl | n@(k+2) := λ h, let m := min_fac n in have n / m < n := factors_lemma, show list.prod (m :: factors (n / m)) = n, from have h₁ : 0 < n / m := nat.pos_of_ne_zero $ λ h, have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h, by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this, by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)] lemma factors_prime {p : ℕ} (hp : nat.prime p) : p.factors = [p] := begin have : p = (p - 2) + 2 := (nat.sub_eq_iff_eq_add hp.1).mp rfl, rw [this, nat.factors], simp only [eq.symm this], have : nat.min_fac p = p := (nat.prime_def_min_fac.mp hp).2, split, { exact this, }, { simp only [this, nat.factors, nat.div_self (nat.prime.pos hp)], }, end /-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/ lemma factors_add_two (n : ℕ) : factors (n+2) = (min_fac (n+2)) :: (factors ((n+2) / (min_fac (n+2)))) := rfl theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((prime_dvd_prime_iff_eq m2 pp).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.not_coprime_iff_dvd {m n : ℕ} : ¬ coprime m n ↔ ∃p, prime p ∧ p ∣ m ∧ p ∣ n := begin apply iff.intro, { intro h, exact ⟨min_fac (gcd m n), min_fac_prime h, (dvd.trans (min_fac_dvd (gcd m n)) (gcd_dvd_left m n)), (dvd.trans (min_fac_dvd (gcd m n)) (gcd_dvd_right m n))⟩ }, { intro h, cases h with p hp, apply nat.not_coprime_of_dvd_of_dvd (prime.one_lt hp.1) hp.2.1 hp.2.2 } end theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim id IH] lemma prime.pow_not_prime {x n : ℕ} (hn : 2 ≤ n) : ¬ (x ^ n).prime := λ hp, (hp.2 x $ dvd_trans ⟨x, pow_two _⟩ (pow_dvd_pow _ hn)).elim (λ hx1, hp.ne_one $ hx1.symm ▸ one_pow _) (λ hxn, lt_irrefl x $ calc x = x ^ 1 : (pow_one _).symm ... < x ^ n : nat.pow_right_strict_mono (hxn.symm ▸ hp.two_le) hn ... = x : hxn.symm) lemma prime.mul_eq_prime_pow_two_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ 2 ↔ x = p ∧ y = p := ⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [pow_two], begin wlog := hp.dvd_mul.1 pdvdxy using x y, cases case with a ha, have hap : a ∣ p, from ⟨y, by rwa [ha, pow_two, mul_assoc, nat.mul_right_inj hp.pos, eq_comm] at h⟩, exact ((nat.dvd_prime hp).1 hap).elim (λ _, by clear_aux_decl; simp [*, pow_two, nat.mul_right_inj hp.pos] at * {contextual := tt}) (λ _, by clear_aux_decl; simp [*, pow_two, mul_comm, mul_assoc, nat.mul_right_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at * {contextual := tt}) end, λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (pow_two _).symm⟩ lemma prime.dvd_factorial : ∀ {n p : ℕ} (hp : prime p), p ∣ n! ↔ p ≤ n | 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos) | (n+1) p hp := begin rw [factorial_succ, hp.dvd_mul, prime.dvd_factorial hp], exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le, λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ) (λ h, or.inl $ by rw h)⟩ end theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_two_le pq pp.two_le theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ', nat.mul_left_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ lemma eq_prime_pow_of_dvd_least_prime_pow {a p k : ℕ} (pp : prime p) (h₁ : ¬(a ∣ p^k)) (h₂ : a ∣ p^(k+1)) : a = p^(k+1) := begin obtain ⟨l, ⟨h, rfl⟩⟩ := (dvd_prime_pow pp).1 h₂, congr, exact le_antisymm h (not_le.1 ((not_congr (pow_dvd_pow_iff_le_right (prime.one_lt pp))).1 h₁)), end section open list lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) : ∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l | [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp) | (q :: l) := λ h₁ h₂, have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂, have hq : prime q := h₁ q (mem_cons_self _ _), or.cases_on ((prime.dvd_mul hp).1 h₃) (λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h; exact h ▸ mem_cons_self _ _) (λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)), (mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h))) lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := ⟨λ h, prod_factors hn ▸ list.dvd_prod h, λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩ lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_cons_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := (nat.mul_right_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $ by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq], perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n := have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin rw h at *, clear h, induction l with a l hi, { exact absurd h₁ dec_trivial }, { rw prod_cons at h₁, exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm (hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ } end, perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _) end lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) : p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n := have hpd : p^(k+l)*p ∣ m*n, by rwa pow_succ' at hpmn, have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd, have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [pow_add] using hpd2, have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3, have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4, suffices p^k*p ∣ m ∨ p^l*p ∣ n, by rwa [pow_succ', pow_succ'], hpd5.elim (assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this) (assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this) /-- The type of prime numbers -/ def primes := {p : ℕ // p.prime} namespace primes instance : has_repr nat.primes := ⟨λ p, repr p.val⟩ instance : inhabited primes := ⟨⟨2, prime_two⟩⟩ instance coe_nat : has_coe nat.primes ℕ := ⟨subtype.val⟩ theorem coe_nat_inj (p q : nat.primes) : (p : ℕ) = (q : ℕ) → p = q := λ h, subtype.eq h end primes instance monoid.prime_pow {α : Type*} [monoid α] : has_pow α primes := ⟨λ x p, x^p.val⟩ end nat /-! ### Primality prover -/ namespace tactic namespace norm_num open norm_num lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] /-- A predicate representing partial progress in a proof of `min_fac`. -/ def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) dec_trivial lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' c : ℕ) (e : k + 1 = k') (nc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, refine mt _ (ne_of_gt c0), intro e₁, rw [← nc, ← nat.dvd_iff_mod_eq_zero, ← e₁], apply nat.min_fac_dvd end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 n % bit1 k = 0) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw ← nat.dvd_iff_mod_eq_zero at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end /-- Given `e` a natural numeral and `d : nat` a factor of it, return `⊢ ¬ prime e`. -/ meta def prove_non_prime (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt_nat c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (c, e', p) ← prove_mul_nat c e₁ e₂, guard (e' =ₐ e), (c, p₂) ← prove_lt_nat c `(1) e₂, return $ `(@nat.not_prime_mul').mk_app [e₁, e₂, e, p, p₁, p₂] /-- Given `a`,`a1 := bit1 a`, `n1` the value of `a1`, `b` and `p : min_fac_helper a b`, returns `(c, ⊢ min_fac a1 = c)`. -/ meta def prove_min_fac_aux (a a1 : expr) (n1 : ℕ) : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic b p := do k ← b.to_nat, let k1 := bit1 k, let b1 := `(bit1:ℕ→ℕ).mk_app [b], if n1 < k1*k1 then do (ic, e', p₁) ← prove_mul_nat ic b1 b1, (ic, p₂) ← prove_lt_nat ic a1 e', return (ic, a1, `(min_fac_helper_5).mk_app [a, b, e', p₁, p₂, p]) else let d := k1.min_fac in if to_bool (d < k1) then do let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', p₂ ← prove_non_prime b1 k1 d, prove_min_fac_aux ic e' $ `(min_fac_helper_2).mk_app [a, b, e', p₁, p₂, p] else do let nc := n1 % k1, (ic, c, pc) ← prove_div_mod ic a1 b1 tt, if nc = 0 then return (ic, b1, `(min_fac_helper_4).mk_app [a, b, pc, p]) else do (ic, p₀) ← prove_pos ic c, let k' := k+1, let e' := reflect k', (ic, p₁) ← prove_succ ic b e', prove_min_fac_aux ic e' $ `(min_fac_helper_3).mk_app [a, b, e', c, p₁, pc, p₀, p] /-- Given `a` a natural numeral, returns `(b, ⊢ min_fac a = b)`. -/ meta def prove_min_fac (ic : instance_cache) (e : expr) : tactic (instance_cache × expr × expr) := match match_numeral e with | match_numeral_result.zero := return (ic, `(2:ℕ), `(nat.min_fac_zero)) | match_numeral_result.one := return (ic, `(1:ℕ), `(nat.min_fac_one)) | match_numeral_result.bit0 e := return (ic, `(2), `(min_fac_bit0).mk_app [e]) | match_numeral_result.bit1 e := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, let a1 := `(bit1:ℕ→ℕ).mk_app [e], prove_min_fac_aux e a1 (bit1 n) c `(1) (`(min_fac_helper_0).mk_app [e, p]) | _ := failed end /-- Evaluates the `prime` and `min_fac` functions. -/ @[norm_num] meta def eval_prime : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt_nat c `(1) e₁, (c, e₁, p) ← prove_min_fac c e, true_intro $ `(is_prime_helper).mk_app [e, p₁, p] end | `(nat.min_fac %%e) := do ic ← mk_instance_cache `(ℕ), prod.snd <$> prove_min_fac ic e | _ := failed end norm_num end tactic
cde5a9c022fe4c7935ccaa54f9dae6b5a6e0611f
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/eval/math_eval.lean
272c07b8d5fb3aaf80c2a30dac55f8c287b52a64
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
435
lean
import ..environment.environment variables {K : Type*} [field K] [inhabited K]{f : fm K TIME} (sp : spc K f) open lang.math namespace lang.math_eval def fm_eval {K : Type*} [field K] [inhabited K] (f : fm K TIME) : env K f → fm_expr K → fm K TIME | e (fm_expr.lit f) := f | e (fm_expr.var v) := e.f v def sp_eval : env K f → sp_expr f → spc K f | e (sp_expr.lit f) := sp | e (sp_expr.var v) := e.sp v end lang.math_eval
e69359dba8aabd73bcd9f0b77383512114a9b0ad
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Tactic/ShowTerm.lean
a01ca8836444cc029ace3b95e94ba7b203566d44
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
807
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison -/ import Lean.Elab.Tactic.Basic import Mathlib.Tactic.TryThis open Lean open Lean.Meta open Lean.Elab.Tactic open Tactic.TryThis namespace Lean.Elab.Tactic /-- `showTerm tac` runs `tac`, then prints the generated term in the form "Try this: exact X Y Z" or "Try this: refine X ?_ Z" if there are remaining subgoals. (For some tactics, the printed term will not be human readable.) -/ elab (name := showTerm) tk:"showTerm " t:tacticSeq : tactic => withMainContext do let g ← getMainGoal evalTactic t addExactSuggestion tk /- FIXME: we'd like the range for the whole tactic -/ (← instantiateMVars (mkMVar g)).headBeta end Lean.Elab.Tactic
35a227bbc1c74554092015e596035456d018ae80
57c233acf9386e610d99ed20ef139c5f97504ba3
/archive/imo/imo2001_q6.lean
73dbd931eacb86fa91f1e7eb04577e33a0309022
[ "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
2,070
lean
/- Copyright (c) 2021 Sara Díaz Real. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sara Díaz Real -/ import data.int.basic import algebra.associated import tactic.linarith import tactic.ring /-! # IMO 2001 Q6 Let $a$, $b$, $c$, $d$ be integers with $a > b > c > d > 0$. Suppose that $$ a*c + b*d = (a + b - c + d) * (-a + b + c + d). $$ Prove that $a*b + c*d$ is not prime. -/ variables {a b c d : ℤ} theorem imo2001_q6 (hd : 0 < d) (hdc : d < c) (hcb : c < b) (hba : b < a) (h : a*c + b*d = (a + b - c + d) * (-a + b + c + d)) : ¬ prime (a*b + c*d) := begin assume h0 : prime (a*b + c*d), have ha : 0 < a, { linarith }, have hb : 0 < b, { linarith }, have hc : 0 < c, { linarith }, -- the key step is to show that `a*c + b*d` divides the product `(a*b + c*d) * (a*d + b*c)` have dvd_mul : a*c + b*d ∣ (a*b + c*d) * (a*d + b*c), { use b^2 + b*d + d^2, have equivalent_sums : a^2 - a*c + c^2 = b^2 + b*d + d^2, { ring_nf at h, nlinarith only [h], }, calc (a * b + c * d) * (a * d + b * c) = a*c * (b^2 + b*d + d^2) + b*d * (a^2 - a*c + c^2) : by ring ... = a*c * (b^2 + b*d + d^2) + b*d * (b^2 + b*d + d^2) : by rw equivalent_sums ... = (a * c + b * d) * (b ^ 2 + b * d + d ^ 2) : by ring, }, -- since `a*b + c*d` is prime (by assumption), it must divide `a*c + b*d` or `a*d + b*c` obtain (h1 : a*b + c*d ∣ a*c + b*d) | (h2 : a*c + b*d ∣ a*d + b*c) := h0.left_dvd_or_dvd_right_of_dvd_mul dvd_mul, -- in both cases, we derive a contradiction { have aux : 0 < a*c + b*d, { nlinarith only [ha, hb, hc, hd] }, have : a*b + c*d ≤ a*c + b*d, { from int.le_of_dvd aux h1 }, have : ¬ (a*b + c*d ≤ a*c + b*d), { nlinarith only [hba, hcb, hdc, h] }, contradiction, }, { have aux : 0 < a*d + b*c, { nlinarith only [ha, hb, hc, hd] }, have : a*c + b*d ≤ a*d + b*c, { from int.le_of_dvd aux h2 }, have : ¬ (a*c + b*d ≤ a*d + b*c), { nlinarith only [hba, hdc, h] }, contradiction, }, end
053f97a9b7fb29ebf69bac70cb0ff75703375afe
80d0f8071ea62262937ab36f5887a61735adea09
/src/certigrad/prove_model_ok.lean
b6254c0ac2c92474a2ad720e1432f238c12b8948
[ "Apache-2.0" ]
permissive
wudcscheme/certigrad
94805fa6a61f993c69a824429a103c9613a65a48
c9a06e93f1ec58196d6d3b8563b29868d916727f
refs/heads/master
1,679,386,475,077
1,551,651,022,000
1,551,651,022,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,743
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Tactics to prove specific models satisfy the preconditions of backprop_correct. -/ import data.list.set .tfacts .graph .predicates .expected_value .reparam .kl .tactics .program .mvn .tactics #print "compiling prove_model_ok..." namespace certigrad open T tactic list lemma mem_of_ne_mem_cons {α : Type*} {xs : list α} {x y : α} : x ∈ y :: xs → x ≠ y → x ∈ xs := begin intros H_in H_neq, dunfold has_mem.mem list.mem at H_in, cases H_in with H_eq H_in, exfalso, exact H_neq H_eq, exact H_in end @[cgsimp] lemma true_of_not_false : (¬ false) = true := begin apply propext, split, intro H, exact trivial, intros Ht Hf, exact Hf end @[cgsimp] lemma label_of (x y : label) : (ID.str x = ID.str y) = (x = y) := begin apply propext, split, intro H, injection H, intro H, rw H end @[cgsimp] lemma eq_of_self_eq {α : Type*} (x : α) : (x = x) = true := propext (eq_self_iff_true _) @[cgsimp] lemma and_true_left {P : Prop} : (true ∧ P) = P := propext (true_and _) @[cgsimp] lemma and_true_right {P : Prop} : (P ∧ true) = P := propext (and_true _) @[cgsimp] lemma and_false_left {P : Prop} : (false ∧ P) = false := propext (false_and _) @[cgsimp] lemma and_false_right {P : Prop} : (P ∧ false) = false := propext (and_false _) @[cgsimp] lemma or_false_left {P : Prop} : (false ∨ P) = P := propext (false_or _) @[cgsimp] lemma or_false_right {P : Prop} : (P ∨ false) = P := propext (or_false _) @[cgsimp] lemma or_true_left {P : Prop} : (true ∨ P) = true := propext (true_or _) @[cgsimp] lemma or_true_right {P : Prop} : (P ∨ true) = true := propext (or_true _) @[cgsimp] lemma true_of_imp_true {α : Sort*} : (α → true) = true := propext (iff.intro (λ H, trivial) (λ H x, trivial)) @[cgsimp] lemma simp_nodup_nil {α : Type*} : @list.nodup α [] = true := pextt list.nodup_nil @[cgsimp] lemma simp_nodup_singleton {α : Type*} (a : α) : list.nodup [a] = true := pextt (list.nodup_singleton _) @[cgsimp] lemma simp_nodup_cons {α : Type*} {a : α} {l : list α} (H : a ∉ l) : list.nodup (a::l) = list.nodup l := begin apply propext, split, intro H', cases H' with H1 H2 H3 H4, exact H4, apply list.nodup_cons, exact H end @[cgsimp] lemma false_imp {P : Prop} : (false → P) = true := begin apply propext, split, intro H, exact trivial, intros Ht Hf, exfalso, exact Hf end @[cgsimp] lemma true_imp {P : Prop} : (true → P) = P := begin apply propext, split, intro H, exact H trivial, intros H Ht, exact H end @[cgsimp] lemma simp_mem_nil {α : Type*} (x : α) : (x ∈ @list.nil α) = false := begin apply pextf, apply list.not_mem_nil end @[cgsimp] lemma simp_mem_cons_neq {α : Type*} (x y : α) (xs : list α) : x ≠ y → (x ∈ y :: xs) = (x ∈ xs) := begin intro H_neq, apply propext, split, intro H_in, exact mem_of_ne_mem_cons H_in H_neq, intro H_in, exact or.inr H_in end @[cgsimp] lemma simp_mem_cons_eq {α : Type*} (x y : α) (xs : list α) : x = y → (x ∈ y :: xs) = true := begin intro H_eq, apply pextt, dunfold has_mem.mem list.mem, left, exact H_eq end @[cgsimp] lemma simp_nmem_nil {α : Type*} (x : α) : (x ∉ @list.nil α) = true := begin apply pextt, apply list.not_mem_nil end @[cgsimp] lemma simp_nmem_cons_eq {α : Type*} (x y : α) (xs : list α) : x ≠ y → (x ∉ y :: xs) = (x ∉ xs) := begin intro H_neq, apply propext, split, intros H_nin H_in, exact H_nin (or.inr H_in), intros H_nin H_in, exact H_nin (mem_of_ne_mem_cons H_in H_neq) end @[cgsimp] lemma simp_nmem_cons_neq {α : Type*} (x y : α) (xs : list α) : x = y → (x ∉ y :: xs) = false := begin intro H_eq, apply pextf, intro H, exact H (or.inl H_eq) end @[cgsimp] lemma false_of_cons_eq_nil {α : Type*} {x : α} {xs : list α} : (list.cons x xs = list.nil) = false := begin apply pextf, intro H, injection H end @[cgsimp] lemma simp_at_idx_nil {α : Type*} [inhabited α] (x : α) (idx : ℕ) : list.at_idx list.nil idx x = false := begin apply pextf, intro H, dunfold list.at_idx at H, cases H with H1 H2, exact (nat.not_lt_zero idx) H1 end @[cgsimp] lemma simp_at_idx_0 {α : Type*} [inhabited α] {x : α} {xs : list α} : list.at_idx (x::xs) 0 x = true := begin apply pextt, apply list.at_idx_0 end @[cgsimp] lemma simp_at_idx_cons {α : Type*} [inhabited α] {x : α} {xs : list α} {y : α} {idx : ℕ} : list.at_idx (x::xs) (idx+1) y = list.at_idx xs idx y := begin apply propext, split, apply list.at_idx_of_cons, apply list.at_idx_cons end @[cgsimp] lemma of_in_list_forall_cons {α : Type*} (ys : list α) (P : α → Prop) (y : α) : (∀ x, x ∈ list.cons y ys → P x) = (P y ∧ (∀ x, x ∈ ys → P x)) := begin apply propext, split, intro H, { split, exact H y list.mem_of_cons_same, intros x H_in, exact H x (or.inr H_in) }, { intro H, cases H with HPy H, intros x H_in, cases classical.em (x = y) with H_eq H_neq, rw H_eq, exact HPy, exact H x (mem_of_ne_mem_cons H_in H_neq) } end @[cgsimp] lemma of_in_list_forall_nil {α : Type*} (P : α → Prop) (y : α) : (∀ (x : α), x ∈ @list.nil α → P x) = true := begin apply pextt, intros x H_in_nil, exfalso, exact (list.not_mem_nil _) H_in_nil end @[cgsimp] lemma of_in_list_cons_neq {α : Type*} {P : Prop} (ys : list α) (x y : α) : x ≠ y → (x ∈ list.cons y ys → P) = (x ∈ ys → P) := begin intro H_neq, apply propext, split, intro H, intro H_in, apply H, exact or.inr H_in, intro H, intro H_in, apply H, exact mem_of_ne_mem_cons H_in H_neq end @[cgsimp] lemma of_in_list_cons_eq {α : Type*} {P : Prop} (ys : list α) (x y : α) : x = y → (x ∈ list.cons y ys → P) = P := begin intro H_eq, apply propext, split, intro H_in, exact H_in (or.inl H_eq), intros HP H_in, exact HP end @[cgsimp] lemma simp_sublist_cons {α : Type*} (xs : list α) (x : α) : (xs <+ x :: xs) = true := begin apply pextt, apply list.sublist_cons end @[cgsimp] lemma simp_sqrt_pos {shape : S} {x : T shape}: (0 < sqrt x) = (0 < x) := begin apply propext, split, apply pos_of_sqrt_pos, apply sqrt_pos end @[cgsimp] lemma simp_exp_pos {shape : S} {x : T shape} : (0 < exp x) = true := begin apply pextt, apply exp_pos end @[cgsimp] lemma simp_integrable_const (shape₁ shape₂ : S) (y : T shape₂) : is_integrable (λ (x : T shape₁), y) = true := begin apply pextt, apply is_integrable_const end @[cgsimp] lemma simp_nneg_of_pos {shape : S} {x : T shape} : x ≠ 0 = (0 < x ∨ x < 0) := begin apply propext, apply nz_iff end @[cgsimp] lemma simp_one_pos {shape : S} : (0 < (1 : T shape)) = true := pextt one_pos @[cgsimp] lemma simp_sigmoid_pos {shape : S} {x : T shape} : (0 < sigmoid x) = true := pextt sigmoid_pos @[cgsimp] lemma simp_sigmoid_lt1 {shape : S} {x : T shape} : (sigmoid x < 1) = true := pextt sigmoid_lt1 -- TODO(dhs): weird lemma @[cgsimp] lemma simp_one_plus_pos {shape : S} {x : T shape} : 0 < 1 + x = (0 < x ∨ - 1 < x) := begin apply propext, split, intro H, right, exact iff.mp one_plus_pos_iff H, intro H, cases H with H H, apply one_plus_pos, exact H, exact iff.mpr one_plus_pos_iff H end @[cgsimp] lemma simp_has_key_insert_same (ref : reference) {x : T ref.2} (m : env) : env.has_key ref (env.insert ref x m) = true := pextt (by apply env.has_key_insert_same) @[cgsimp] lemma simp_has_key_insert_diff (ref₁ ref₂ : reference) {x : T ref₂.2} (m : env) : ref₁ ≠ ref₂ → env.has_key ref₁ (env.insert ref₂ x m) = env.has_key ref₁ m := begin intro H_neq, apply propext, split, apply env.has_key_insert_diff, exact H_neq, apply env.has_key_insert end @[cgsimp] lemma simp_has_key_empty (ref : reference) : env.has_key ref env.mk = false := begin apply pextf, apply env.not_has_key_empty end def is_not_used_downstream (tgt : reference) : list node → Prop | [] := true | (⟨ref, parents, op⟩ :: nodes) := tgt ∉ parents ∧ is_not_used_downstream nodes def is_used_downstream (tgt : reference) : list node → Prop | [] := false | (⟨ref, parents, op⟩ :: nodes) := tgt ∈ parents ∨ is_used_downstream nodes attribute [cgsimp] is_not_used_downstream is_used_downstream lemma costs_helper : Π (costs : list ID) (tgt : reference) (m : env), tgt.1 ∉ costs → compute_grad_slow costs [] m tgt = 0 | [] tgt m H_nin := rfl | (c::cs) tgt m H_nin := begin dunfold compute_grad_slow, assert H : (tgt ≠ (c, [])), { cases tgt with tgt_1 tgt_2, dsimp at H_nin, apply pair_neq_of_neq₁, exact list.ne_of_not_mem_cons H_nin }, simph, dunfold list.sumr, rw zero_add, exact costs_helper cs tgt m (list.not_mem_of_not_mem_cons H_nin) end lemma compute_grad_slow_det_not_used_helper (costs : list ID) : Π (nodes : list node) (m : env) (tgt : reference), is_not_used_downstream tgt nodes → tgt.1 ∉ costs → compute_grad_slow costs nodes m tgt = 0 | [] m tgt H_not_used H_tgt_nin_costs := begin apply costs_helper, all_goals { assumption } end | (⟨ref, parents, operator.det op⟩::nodes) m tgt H_not_used H_tgt_nin_costs := begin dunfold compute_grad_slow, dunfold is_not_used_downstream at H_not_used, rw compute_grad_slow_det_not_used_helper nodes _ tgt H_not_used^.right H_tgt_nin_costs, rw zero_add, rw list.not_in_filter_of_match_riota, reflexivity, exact H_not_used^.left end | (⟨ref, parents, operator.rand op⟩::nodes) m tgt H_not_used H_tgt_nin_costs := begin dunfold compute_grad_slow, dunfold is_not_used_downstream at H_not_used, rw compute_grad_slow_det_not_used_helper, rw zero_add, rw list.not_in_filter_of_match_riota, reflexivity, exact H_not_used^.left, exact H_not_used^.right, exact H_tgt_nin_costs end @[cgsimp] lemma compute_grad_slow_det_not_used (costs : list ID) (ref : reference) (parents : list reference) (op : det.op parents^.p2 ref^.2) : Π (nodes : list node) (m : env) (tgt : reference), is_not_used_downstream tgt nodes → tgt.1 ∉ costs → compute_grad_slow costs (⟨ref, parents, operator.det op⟩ :: nodes) m tgt = list.sumr (list.map (λ (idx : ℕ), op^.pb (env.get_ks parents m) (env.get ref m) (compute_grad_slow costs nodes m ref) idx tgt.2) (list.filter (λ idx, tgt = list.dnth parents idx) (list.riota $ list.length parents))) := begin intros nodes m tgt H_not_used H_tgt_nin_costs, dunfold_occs compute_grad_slow [1], rw [compute_grad_slow_det_not_used_helper _ _ _ _ H_not_used H_tgt_nin_costs, zero_add] end @[cgsimp] lemma compute_grad_slow_det_used (costs : list ID) (ref : reference) (parents : list reference) (op : det.op parents^.p2 ref^.2) : Π (nodes : list node) (m : env) (tgt : reference), is_used_downstream tgt nodes ∨ tgt.1 ∈ costs → compute_grad_slow costs (⟨ref, parents, operator.det op⟩ :: nodes) m tgt = compute_grad_slow costs nodes m tgt + list.sumr (list.map (λ (idx : ℕ), op^.pb (env.get_ks parents m) (env.get ref m) (compute_grad_slow costs nodes m ref) idx tgt.2) (list.filter (λ idx, tgt = list.dnth parents idx) (list.riota $ list.length parents))) := begin intros nodes m tgt H_is_used_or_cost, reflexivity end @[cgsimp] lemma compute_grad_slow_rand_not_used (costs : list ID) (ref : reference) (parents : list reference) (op : rand.op parents^.p2 ref^.2) : Π (nodes : list node) (m : env) (tgt : reference), is_not_used_downstream tgt nodes → tgt.1 ∉ costs → compute_grad_slow costs (⟨ref, parents, operator.rand op⟩ :: nodes) m tgt = list.sumr (list.map (λ (idx : ℕ), sum_downstream_costs nodes costs ref m ⬝ op^.glogpdf (env.get_ks parents m) (env.get ref m) idx tgt.2) (list.filter (λ idx, tgt = list.dnth parents idx) (list.riota $ list.length parents))) := begin intros nodes m tgt H_not_used H_tgt_nin_costs, dunfold_occs compute_grad_slow [1], rw [compute_grad_slow_det_not_used_helper _ _ _ _ H_not_used H_tgt_nin_costs, zero_add] end @[cgsimp] lemma compute_grad_slow_rand_used (costs : list ID) (ref : reference) (parents : list reference) (op : rand.op parents^.p2 ref^.2) : Π (nodes : list node) (m : env) (tgt : reference), is_used_downstream tgt nodes ∨ tgt.1 ∈ costs → compute_grad_slow costs (⟨ref, parents, operator.rand op⟩ :: nodes) m tgt = compute_grad_slow costs nodes m tgt + list.sumr (list.map (λ (idx : ℕ), sum_downstream_costs nodes costs ref m ⬝ op^.glogpdf (env.get_ks parents m) (env.get ref m) idx tgt.2) (list.filter (λ idx, tgt = list.dnth parents idx) (list.riota $ list.length parents))) := begin intros nodes m tgt H_used_or_cost, reflexivity end attribute [cgsimp] compute_grad_slow.equations._eqn_1 lemma grads_exist_at_simp_helper : Π (nodes : list node) (m : env) (tgt : reference), is_not_used_downstream tgt nodes → grads_exist_at nodes m tgt | [] m tgt H_not_used := trivial | (⟨ref, parents, operator.det op⟩::nodes) m tgt H_not_used := begin dunfold grads_exist_at, dunfold is_not_used_downstream at H_not_used, dsimp, split, apply grads_exist_at_simp_helper nodes _ tgt H_not_used^.right, intro H_in_parents, exfalso, exact H_not_used^.left H_in_parents end | (⟨ref, parents, operator.rand op⟩::nodes) m tgt H_not_used := begin dunfold grads_exist_at, dunfold is_not_used_downstream at H_not_used, dsimp, split, intro H_in_parents, exfalso, exact H_not_used^.left H_in_parents, intro y, apply grads_exist_at_simp_helper nodes _ tgt H_not_used^.right end @[cgsimp] lemma grads_exist_at_det_not_used (ref : reference) (parents : list reference) (op : det.op parents^.p2 ref^.2) : Π (nodes : list node) (m : env) (tgt : reference), is_not_used_downstream tgt nodes → grads_exist_at (⟨ref, parents, operator.det op⟩ :: nodes) m tgt = let m' := env.insert ref (op^.f (env.get_ks parents m)) m in (tgt ∈ parents → op^.pre (env.get_ks parents m) ∧ grads_exist_at nodes (env.insert ref (op^.f (env.get_ks parents m)) m) ref) := begin intros nodes m tgt H_not_used, dunfold grads_exist_at, dsimp, rw (pextt (grads_exist_at_simp_helper _ _ _ H_not_used)), simp end @[cgsimp] lemma grads_exist_at_det_used (ref : reference) (parents : list reference) (op : det.op parents^.p2 ref^.2) : Π (nodes : list node) (m : env) (tgt : reference), is_used_downstream tgt nodes → grads_exist_at (⟨ref, parents, operator.det op⟩ :: nodes) m tgt = let m' := env.insert ref (op^.f (env.get_ks parents m)) m in grads_exist_at nodes m' tgt ∧ (tgt ∈ parents → op^.pre (env.get_ks parents m) ∧ grads_exist_at nodes (env.insert ref (op^.f (env.get_ks parents m)) m) ref) := begin intros nodes m tgt H, reflexivity end attribute [cgsimp] grads_exist_at.equations._eqn_1 grads_exist_at.equations._eqn_3 attribute [cgsimp] all_pdfs_std can_diff_under_ints_pdfs_std attribute [cgsimp] T.smul_zero T.one_smul attribute [cgsimp] if_pos if_neg if_true if_false attribute [cgsimp] dif_pos dif_neg dif_ctx_simp_congr attribute [cgsimp] mvn_mvn_empirical_kl_int mvn_bernoulli_neglogpdf_int attribute [cgsimp] force_ok attribute [cgsimp] list.sumr list.map list.concat list.head list.tail list.riota list.filter list.length list.dnth list.sublist.refl list.nil_subset list.sublist_cons list.cons_append list.append_nil list.nil_append list.p1 list.p2 attribute [cgsimp] hash_map.find_insert_eq hash_map.find_insert_ne attribute [cgsimp] zero_add add_zero attribute [cgsimp] dvec.head dvec.head2 dvec.head3 attribute [cgsimp] integrate_kl integrate_mvn_kl integrate_kl_pre integrate_mvn_kl_pre reparameterize attribute [cgsimp] reparam reparameterize reparameterize_pre attribute [cgsimp] all_parents_in_env all_costs_scalars /- grads_exist_at -/ pdfs_exist_at uniq_ids is_gintegrable is_nabla_gintegrable is_gdifferentiable /- can_differentiate_under_integrals -/ attribute [cgsimp] graph.to_dist operator.to_dist sum_costs /- compute_grad_slow -/ attribute [cgsimp] E.E_bind E.E_ret attribute [cgsimp] ops.neg ops.exp ops.log ops.sqrt ops.add ops.sub ops.mul ops.div ops.sum ops.gemm ops.sigmoid ops.softplus ops.scale ops.mul_add ops.mvn_kl ops.bernoulli_neglogpdf attribute [cgsimp] det.op.f ops.neg.f ops.exp.f ops.log.f ops.sqrt.f ops.add.f ops.sub.f ops.mul.f ops.div.f ops.sum.f ops.gemm.f ops.sigmoid.f ops.softplus.f ops.scale.f ops.mul_add.f ops.mvn_kl.f ops.bernoulli_neglogpdf.f attribute [cgsimp] det.op.pre ops.neg.f_pre ops.exp.f_pre ops.log.f_pre ops.sqrt.f_pre ops.add.f_pre ops.sub.f_pre ops.mul.f_pre ops.div.f_pre ops.sum.f_pre ops.gemm.f_pre ops.sigmoid.f_pre ops.softplus.f_pre ops.scale.f_pre ops.mul_add.f_pre ops.mvn_kl.f_pre ops.bernoulli_neglogpdf.f_pre attribute [cgsimp] det.op.pb ops.neg.f_pb ops.exp.f_pb ops.log.f_pb ops.sqrt.f_pb ops.add.f_pb ops.sub.f_pb ops.mul.f_pb ops.div.f_pb ops.sum.f_pb ops.gemm.f_pb ops.sigmoid.f_pb ops.softplus.f_pb ops.scale.f_pb ops.mul_add.f_pb ops.mvn_kl.f_pb ops.bernoulli_neglogpdf.f_pb attribute [cgsimp] det.op.is_odiff det.op.pb_correct det.op.is_ocont attribute [cgsimp] rand.op.pdf rand.pdf.mvn rand.pdf.mvn_std rand.op.pre rand.op.mvn rand.op.mvn_std rand.pre.mvn rand.pre.mvn_std attribute [cgsimp] env.get_ks env.insert_all env.get_insert_same env.get_insert_diff attribute [cgsimp] list.insertion_sort list.ordered_insert attribute [cgsimp] program_to_graph program.program_to_graph_core program.get_id -- program.unary_to_cwise1 program.binary_to_cwise2 program.process_term program.empty_state program.process_rterm program_to_graph._match_1 program.program_to_graph_core._match_1 program.program_to_graph_core._match_2 program.process_rterm._match_1 program.process_term._match_6 program.process_term._match_10 program.process_term._match_13 -- program.process_term._match_16 -- program.process_term._match_17 program.exp program.log program.sqrt program.softplus program.sigmoid @[cgsimp] lemma lift_t_label_to_term (x : label) : (lift_t x : program.term) = (program.term.id x) := rfl namespace tactic open tactic run_cmd mk_simp_attr `pcgsimp attribute [pcgsimp] to_dist_congr_insert meta def dcgsimp : tactic unit := do s ← join_user_simp_lemmas tt [`cgsimp], dsimp_core s meta def gsimpt_core : Π (tac : tactic unit) (s_pre s_post : simp_lemmas) (e : expr), tactic (expr × expr) := λ tac s_pre s_post e, do (a, new_tgt, pf) ← ext_simplify_core () {} s_post (λ u, failed) --pre --(λ a s r p e, failed) (λ a s r p e, do ⟨u, new_e, pr⟩ ← conv.apply_lemmas_core reducible s_pre tac r e, return ((), new_e, pr, tt)) --post (λ a s r p e, do ⟨u, new_e, pr⟩ ← conv.apply_lemmas_core reducible s tac r e, return ((), new_e, pr, tt)) `eq e, return (new_tgt, pf) meta def gsimpt (tac : tactic unit) : tactic unit := do s_pre ← join_user_simp_lemmas tt [`pcgsimp], s_post ← join_user_simp_lemmas tt [`cgsimp], tgt ← target, (new_tgt, pf) ← gsimpt_core tac s_pre s_post tgt, replace_target new_tgt pf --------------- run_cmd mk_simp_attr `idne attribute [idne] id_str_ne_nat id_nat_ne_str id_str_ne_str id_nat_ne_nat label.neq_of_to_nat label.to_nat meta def prove_ids_neq : tactic unit := do s ← join_user_simp_lemmas tt [`idne, `natne], tgt ← target, (new_tgt, pf) ← simplify s tgt, replace_target new_tgt pf meta def prove_refs_neq : tactic unit := do applyc `pair_neq_of_neq₁, prove_ids_neq meta def cgsimpt (tac : tactic unit) : tactic unit := do repeat $ first [gsimpt tac, prove_refs_neq, prove_ids_neq, triv] meta def cgsimpn : ℕ → tactic unit | 0 := cgsimpt skip | (n+1) := cgsimpt (cgsimpn n) meta def cgsimp : tactic unit := cgsimpn 100 meta def forall_idxs (tac_base tac_step : tactic unit) : expr → tactic unit | idx := tac_base <|> (do cases idx [`_idx], solve1 tac_step, get_local `_idx >>= forall_idxs) meta def prove_model_base : tactic unit := do exfalso, H_at_idx ← get_local `H_at_idx, to_expr ```(list.at_idx_over %%H_at_idx dec_trivial) >>= exact meta def prove_model_step : tactic unit := do H_at_idx ← get_local `H_at_idx, mk_app `and.right [H_at_idx] >>= note `H_tgt_eq, H_tgt_eq_type ← get_local `H_tgt_eq >>= infer_type, s ← join_user_simp_lemmas true [`cgsimp], (H_tgt_eq_new_type, pr) ← simplify s H_tgt_eq_type {}, get_local `H_tgt_eq >>= λ H_tgt_eq, replace_hyp H_tgt_eq H_tgt_eq_new_type pr, get_local `H_tgt_eq >>= subst, applyc `certigrad.backprop_correct, trace "nodup tgts nodes", solve1 cgsimp, trace "at_idx...", solve1 cgsimp, trace "well_formed_at...", solve1 (constructor >> all_goals cgsimp), trace "grads_exist_at...", solve1 (cgsimp), trace "pdfs_exist_at...", solve1 (cgsimp), trace "is_gintegrable...", solve1 (cgsimp >> prove_is_mvn_integrable), trace "can_diff_under_ints...", solve1 (applyc `certigrad.can_diff_under_ints_of_all_pdfs_std >> cgsimp >> prove_is_mvn_uintegrable), trace "prove_for_tgt done" meta def prove_model_ok : tactic unit := do -- unfold lets whnf_target, -- introduce hypotheses [tgt, idx, H_at_idx] ← intros | fail "can't intro hyps", -- repeated case-analysis on idx -- TODO(dhs): async would be great but I run out of memory forall_idxs prove_model_base prove_model_step idx end tactic end certigrad
b9906e16900da9d8c970c28ebc95a9ba56ddf5a9
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/perfect.lean
f788259dc54aef6ee4ef7d1ae3f8c2c35d2686aa
[ "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,999
lean
/- Copyright (c) 2022 Felix Weilacher. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Felix Weilacher -/ import topology.separation import topology.bases /-! # Perfect Sets In this file we define perfect subsets of a topological space, and prove some basic properties, including a version of the Cantor-Bendixson Theorem. ## Main Definitions * `perfect C`: A set `C` is perfect, meaning it is closed and every point of it is an accumulation point of itself. ## Main Statements * `perfect.splitting`: A perfect nonempty set contains two disjoint perfect nonempty subsets. The main inductive step in the construction of an embedding from the Cantor space to a perfect nonempty complete metric space. * `exists_countable_union_perfect_of_is_closed`: One version of the **Cantor-Bendixson Theorem**: A closed set in a second countable space can be written as the union of a countable set and a perfect set. ## Implementation Notes We do not require perfect sets to be nonempty. We define a nonstandard predicate, `preperfect`, which drops the closed-ness requirement from the definition of perfect. In T1 spaces, this is equivalent to having a perfect closure, see `preperfect_iff_perfect_closure`. ## References * [kechris1995] (Chapter 6) ## Tags accumulation point, perfect set, Cantor-Bendixson. -/ open_locale topological_space filter open topological_space filter set variables {α : Type*} [topological_space α] {C : set α} /-- If `x` is an accumulation point of a set `C` and `U` is a neighborhood of `x`, then `x` is an accumulation point of `U ∩ C`. -/ theorem acc_pt.nhds_inter {x : α} {U : set α} (h_acc : acc_pt x (𝓟 C)) (hU : U ∈ 𝓝 x) : acc_pt x (𝓟 (U ∩ C)) := begin have : 𝓝[≠] x ≤ 𝓟 U, { rw le_principal_iff, exact mem_nhds_within_of_mem_nhds hU, }, rw [acc_pt, ← inf_principal, ← inf_assoc, inf_of_le_left this], exact h_acc, end /-- A set `C` is preperfect if all of its points are accumulation points of itself. If `C` is nonempty and `α` is a T1 space, this is equivalent to the closure of `C` being perfect. See `preperfect_iff_perfect_closure`.-/ def preperfect (C : set α) : Prop := ∀ x ∈ C, acc_pt x (𝓟 C) /-- A set `C` is called perfect if it is closed and all of its points are accumulation points of itself. Note that we do not require `C` to be nonempty.-/ structure perfect (C : set α) : Prop := (closed : is_closed C) (acc : preperfect C) lemma preperfect_iff_nhds : preperfect C ↔ ∀ x ∈ C, ∀ U ∈ 𝓝 x, ∃ y ∈ U ∩ C, y ≠ x := by simp only [preperfect, acc_pt_iff_nhds] /-- The intersection of a preperfect set and an open set is preperfect-/ theorem preperfect.open_inter {U : set α} (hC : preperfect C) (hU : is_open U) : preperfect (U ∩ C) := begin rintros x ⟨xU, xC⟩, apply (hC _ xC).nhds_inter, exact hU.mem_nhds xU, end /-- The closure of a preperfect set is perfect. For a converse, see `preperfect_iff_perfect_closure`-/ theorem preperfect.perfect_closure (hC : preperfect C) : perfect (closure C) := begin split, { exact is_closed_closure }, intros x hx, by_cases h : x ∈ C; apply acc_pt.mono _ (principal_mono.mpr subset_closure), { exact hC _ h }, have : {x}ᶜ ∩ C = C := by simp [h], rw [acc_pt, nhds_within, inf_assoc, inf_principal, this], rw [closure_eq_cluster_pts] at hx, exact hx, end /-- In a T1 space, being preperfect is equivalent to having perfect closure.-/ theorem preperfect_iff_perfect_closure [t1_space α] : preperfect C ↔ perfect (closure C) := begin split; intro h, { exact h.perfect_closure }, intros x xC, have H : acc_pt x (𝓟 (closure C)) := h.acc _ (subset_closure xC), rw acc_pt_iff_frequently at *, have : ∀ y , y ≠ x ∧ y ∈ closure C → ∃ᶠ z in 𝓝 y, z ≠ x ∧ z ∈ C, { rintros y ⟨hyx, yC⟩, simp only [← mem_compl_singleton_iff, @and_comm _ (_ ∈ C) , ← frequently_nhds_within_iff, hyx.nhds_within_compl_singleton, ← mem_closure_iff_frequently], exact yC, }, rw ← frequently_frequently_nhds, exact H.mono this, end theorem perfect.closure_nhds_inter {U : set α} (hC : perfect C) (x : α) (xC : x ∈ C) (xU : x ∈ U) (Uop : is_open U) : perfect (closure (U ∩ C)) ∧ (closure (U ∩ C)).nonempty := begin split, { apply preperfect.perfect_closure, exact (hC.acc).open_inter Uop, }, apply nonempty.closure, exact ⟨x, ⟨xU, xC⟩⟩, end /-- Given a perfect nonempty set in a T2.5 space, we can find two disjoint perfect subsets This is the main inductive step in the proof of the Cantor-Bendixson Theorem-/ lemma perfect.splitting [t2_5_space α] (hC : perfect C) (hnonempty : C.nonempty) : ∃ C₀ C₁ : set α, (perfect C₀ ∧ C₀.nonempty ∧ C₀ ⊆ C) ∧ (perfect C₁ ∧ C₁.nonempty ∧ C₁ ⊆ C) ∧ disjoint C₀ C₁ := begin cases hnonempty with y yC, obtain ⟨x, xC, hxy⟩ : ∃ x ∈ C, x ≠ y, { have := hC.acc _ yC, rw acc_pt_iff_nhds at this, rcases this univ (univ_mem) with ⟨x, xC, hxy⟩, exact ⟨x, xC.2, hxy⟩, }, obtain ⟨U, xU, Uop, V, yV, Vop, hUV⟩ := exists_open_nhds_disjoint_closure hxy, use [closure (U ∩ C), closure (V ∩ C)], split; rw ← and_assoc, { refine ⟨hC.closure_nhds_inter x xC xU Uop, _⟩, rw hC.closed.closure_subset_iff, exact inter_subset_right _ _, }, split, { refine ⟨hC.closure_nhds_inter y yC yV Vop, _⟩, rw hC.closed.closure_subset_iff, exact inter_subset_right _ _, }, apply disjoint.mono _ _ hUV; apply closure_mono; exact inter_subset_left _ _, end section kernel /-- The **Cantor-Bendixson Theorem**: Any closed subset of a second countable space can be written as the union of a countable set and a perfect set.-/ theorem exists_countable_union_perfect_of_is_closed [second_countable_topology α] (hclosed : is_closed C) : ∃ V D : set α, (V.countable) ∧ (perfect D) ∧ (C = V ∪ D) := begin obtain ⟨b, bct, bnontrivial, bbasis⟩ := topological_space.exists_countable_basis α, let v := {U ∈ b | (U ∩ C).countable}, let V := ⋃ U ∈ v, U, let D := C \ V, have Vct : (V ∩ C).countable, { simp only [Union_inter, mem_sep_iff], apply countable.bUnion, { exact countable.mono (inter_subset_left _ _) bct, }, { exact inter_subset_right _ _, }, }, refine ⟨V ∩ C, D, Vct, ⟨_, _⟩, _⟩, { refine hclosed.sdiff (is_open_bUnion (λ U, _)), exact λ ⟨Ub, _⟩, is_topological_basis.is_open bbasis Ub, }, { rw preperfect_iff_nhds, intros x xD E xE, have : ¬ (E ∩ D).countable, { intro h, obtain ⟨U, hUb, xU, hU⟩ : ∃ U ∈ b, x ∈ U ∧ U ⊆ E, { exact (is_topological_basis.mem_nhds_iff bbasis).mp xE, }, have hU_cnt : (U ∩ C).countable, { apply @countable.mono _ _ ((E ∩ D) ∪ (V ∩ C)), { rintros y ⟨yU, yC⟩, by_cases y ∈ V, { exact mem_union_right _ (mem_inter h yC), }, { exact mem_union_left _ (mem_inter (hU yU) ⟨yC, h⟩), }, }, exact countable.union h Vct, }, have : U ∈ v := ⟨hUb, hU_cnt⟩, apply xD.2, exact mem_bUnion this xU, }, by_contradiction h, push_neg at h, exact absurd (countable.mono h (set.countable_singleton _)) this, }, { rw [inter_comm, inter_union_diff], }, end /-- Any uncountable closed set in a second countable space contains a nonempty perfect subset.-/ theorem exists_perfect_nonempty_of_is_closed_of_not_countable [second_countable_topology α] (hclosed : is_closed C) (hunc : ¬ C.countable) : ∃ D : set α, perfect D ∧ D.nonempty ∧ D ⊆ C := begin rcases exists_countable_union_perfect_of_is_closed hclosed with ⟨V, D, Vct, Dperf, VD⟩, refine ⟨D, ⟨Dperf, _⟩⟩, split, { rw nonempty_iff_ne_empty, by_contradiction, rw [h, union_empty] at VD, rw VD at hunc, contradiction, }, rw VD, exact subset_union_right _ _, end end kernel
0f712d97813ecdcd7084bf955d7bae5d08d7e1af
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/fintype/basic.lean
832434c04f5828880f4865a9a02f3fc09eec6e50
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
43,711
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 tactic.wlog import data.finset.powerset import data.finset.lattice import data.finset.pi import data.array.lemmas 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 instance : order_top (finset α) := { top := univ, le_top := subset_univ, .. finset.partial_order } instance [decidable_eq α] : bounded_distrib_lattice (finset α) := { .. finset.distrib_lattice, .. finset.semilattice_inf_bot, .. finset.order_top } theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := begin apply eq_univ_iff_forall.mpr, intro b, rw [mem_map], use e.symm b, simp, end end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : 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 {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (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 /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ 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⟩ /-- 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 (equiv_fin_of_forall_mem_list h nd)) 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_iff, 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 /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset 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 α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ end set 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) := ⟨finset.fin_range n, finset.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[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 () theorem fintype.univ_unit : @univ unit _ = {()} := rfl 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 _ = {tt, ff} := 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 noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[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] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl 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)) 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]⟩ /-- A `fintype` with cardinality zero is (constructively) equivalent to `pempty`. -/ def fintype.card_eq_zero_equiv_equiv_pempty {α : Type v} [fintype α] : fintype.card α = 0 ≃ (α ≃ pempty.{v+1}) := { to_fun := λ h, { to_fun := λ a, false.elim (fintype.card_eq_zero_iff.1 h a), inv_fun := λ a, pempty.elim a, left_inv := λ a, false.elim (fintype.card_eq_zero_iff.1 h a), right_inv := λ a, pempty.elim a, }, inv_fun := λ e, by { simp only [←fintype.of_equiv_card e], convert fintype.card_pempty, }, left_inv := λ h, rfl, right_inv := λ e, by { ext x, cases e x, } } 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.card_le_one_iff_subsingleton [fintype α] : fintype.card α ≤ 1 ↔ subsingleton α := iff.trans fintype.card_le_one_iff subsingleton_iff.symm lemma fintype.one_lt_card_iff_nontrivial [fintype α] : 1 < fintype.card α ↔ nontrivial α := begin classical, rw ← not_iff_not, push_neg, rw [not_nontrivial_iff_subsingleton, fintype.card_le_one_iff_subsingleton] end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := by { haveI : nontrivial α := fintype.one_lt_card_iff_nontrivial.1 h, exact exists_ne a } lemma fintype.exists_pair_of_one_lt_card [fintype α] (h : 1 < fintype.card α) : ∃ (a b : α), a ≠ b := by { haveI : nontrivial α := fintype.one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α } 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, has_left_inverse.injective ⟨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 e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } 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 lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma finset.card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [classical.or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨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) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype variables [fintype α] [decidable_eq α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl 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 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 _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := set_fintype _ @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } @[simp] lemma set.to_finset_empty [fintype α] : (∅ : set α).to_finset = ∅ := by { ext, simp only [set.mem_empty_eq, set.mem_to_finset, not_mem_empty] } 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 _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ 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*} [decidable α] [∀ a, fintype (β a)] : 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} [∀ a, decidable (β a)] [fintype α] : 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 α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl end⟩ 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]⟩ lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp lemma card_lt_card_of_injective_of_not_mem {α β : Type*} [fintype α] [fintype β] (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : fintype.card α < fintype.card β := begin classical, calc fintype.card α = (univ : finset α).card : rfl ... = (image f univ).card : (card_image_of_injective univ h).symm ... < (insert b (image f univ)).card : card_lt_card (ssubset_insert (mt mem_image_univ_iff_mem_range.mp w)) ... ≤ (univ : finset β).card : card_le_of_subset (subset_univ _) ... = fintype.card β : rfl end 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 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) := begin rw [length_cons, nat.fact_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end 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_cancel) 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 $ by simp [mem_perms_of_list_iff, hab.mem_iff])) 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 lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin apply symm, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end 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) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ 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⟩ @[priority 100] -- see Note [lower instance priority] 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 lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj) section trunc /-- For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`. -/ def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α := quotient.rec_on_subsingleton s $ λ l h, match l, h with | [], _ := false.elim (by tauto) | (a :: _), _ := trunc.mk a end /-- A `nonempty` `fintype` constructively contains an element. -/ def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α := trunc_of_multiset_exists_mem finset.univ.val (by simp) /-- A `fintype` with positive cardinality constructively contains an element. -/ def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α := by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α } /-- By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a` to `trunc (Σ' a, P a)`, containing data. -/ def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) : trunc (Σ' a, P a) := @trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _ end trunc
1b0441b4d2171340a430a8bbbd21a22f8df0b1db
675b8263050a5d74b89ceab381ac81ce70535688
/src/field_theory/galois.lean
9fe65dda9c500ccabd5135bb4fd32688113cd121
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,646
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning and Patrick Lutz -/ import field_theory.normal import field_theory.primitive_element import field_theory.fixed import ring_theory.power_basis /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `is_galois F E` where `E` is an extension of `F` - `fixed_field H` where `H : subgroup (E ≃ₐ[F] E)` - `fixing_subgroup K` where `K : intermediate_field F E` - `galois_correspondence` where `E/F` is finite dimensional and Galois ## Main results - `fixing_subgroup_of_fixed_field` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixing_subgroup (fixed_field H) = H` - `fixed_field_of_fixing_subgroup`: If `E/F` is finite dimensional and Galois then `fixed_field (fixing_subgroup K) = K` Together, these two result prove the Galois correspondence -/ noncomputable theory open_locale classical open finite_dimensional alg_equiv section variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] /-- A field extension E/F is galois if it is both separable and normal -/ @[class] def is_galois : Prop := is_separable F E ∧ normal F E namespace is_galois instance self : is_galois F F := ⟨is_separable_self F, normal_self F⟩ @[priority 100] -- see Note [lower instance priority] instance to_is_separable [h : is_galois F E] : is_separable F E := h.1 @[priority 100] -- see Note [lower instance priority] instance to_normal [h : is_galois F E] : normal F E := h.2 variables {F} {E} lemma integral (h : is_galois F E) (x : E) : is_integral F x := Exists.cases_on (h.1 x) (λ H _, H) lemma separable (h : is_galois F E) (x : E) : (minimal_polynomial (integral h x)).separable := Exists.cases_on (h.1 x) (λ _ H, H) lemma normal (h : is_galois F E) (x : E) : (minimal_polynomial (integral h x)).splits (algebra_map F E) := Exists.cases_on (h.2 x) (λ _ H, H) variables (F) (E) instance of_fixed_field (G : Type*) [group G] [fintype G] [mul_semiring_action G E] : is_galois (mul_action.fixed_points G E) E := ⟨fixed_points.separable G E, fixed_points.normal G E⟩ lemma intermediate_field.adjoin_simple.card_aut_eq_findim [finite_dimensional F E] {α : E} (hα : is_integral F α) (h_sep : (minimal_polynomial hα).separable) (h_splits : (minimal_polynomial hα).splits (algebra_map F F⟮α⟯)) : fintype.card (F⟮α⟯ ≃ₐ[F] F⟮α⟯) = findim F F⟮α⟯ := begin letI : fintype (F⟮α⟯ →ₐ[F] F⟮α⟯) := intermediate_field.fintype_of_alg_hom_adjoin_integral F hα, rw intermediate_field.adjoin.findim hα, rw ← intermediate_field.card_alg_hom_adjoin_integral F hα h_sep h_splits, exact fintype.card_congr (alg_equiv_equiv_alg_hom F F⟮α⟯) end lemma card_aut_eq_findim [finite_dimensional F E] [h : is_galois F E] : fintype.card (E ≃ₐ[F] E) = findim F E := begin cases field.exists_primitive_element h.1 with α hα, let iso : F⟮α⟯ ≃ₐ[F] E := { to_fun := λ e, e.val, inv_fun := λ e, ⟨e, by { rw hα, exact intermediate_field.mem_top }⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, rfl, map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, commutes' := λ _, rfl }, have H : is_integral F α := h.integral α, have h_sep : (minimal_polynomial H).separable := h.separable α, have h_splits : (minimal_polynomial H).splits (algebra_map F E) := h.normal α, replace h_splits : polynomial.splits (algebra_map F F⟮α⟯) (minimal_polynomial H), { convert polynomial.splits_comp_of_splits (algebra_map F E) iso.symm.to_alg_hom.to_ring_hom h_splits }, rw ← linear_equiv.findim_eq iso.to_linear_equiv, rw ← intermediate_field.adjoin_simple.card_aut_eq_findim F E H h_sep h_splits, apply fintype.card_congr, apply equiv.mk (λ ϕ, iso.trans (trans ϕ iso.symm)) (λ ϕ, iso.symm.trans (trans ϕ iso)), { intro ϕ, ext1, simp only [trans_apply, apply_symm_apply] }, { intro ϕ, ext1, simp only [trans_apply, symm_apply_apply] }, end end is_galois end section is_galois_tower variables (F K E : Type*) [field F] [field K] [field E] {E' : Type*} [field E'] [algebra F E'] variables [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_galois.tower_top_of_is_galois [h : is_galois F E] : is_galois K E := ⟨is_separable_tower_top_of_is_separable K h.1, normal.tower_top_of_normal F K E h.2⟩ variables {F E} @[priority 100] -- see Note [lower instance priority] instance is_galois.tower_top_intermediate_field (K : intermediate_field F E) [h : is_galois F E] : is_galois K E := is_galois.tower_top_of_is_galois F K E lemma is_galois_iff_is_galois_bot : is_galois (⊥ : intermediate_field F E) E ↔ is_galois F E := begin split, { introI h, exact is_galois.tower_top_of_is_galois (⊥ : intermediate_field F E) F E }, { introI h, apply_instance }, end lemma is_galois.of_alg_equiv [h : is_galois F E] (f : E ≃ₐ[F] E') : is_galois F E' := ⟨h.1.of_alg_hom f.symm, normal.of_alg_equiv f⟩ lemma alg_equiv.transfer_galois (f : E ≃ₐ[F] E') : is_galois F E ↔ is_galois F E' := ⟨λ h, by exactI is_galois.of_alg_equiv f, λ h, by exactI is_galois.of_alg_equiv f.symm⟩ lemma is_galois_iff_is_galois_top : is_galois F (⊤ : intermediate_field F E) ↔ is_galois F E := (intermediate_field.top_equiv).transfer_galois instance is_galois_bot : is_galois F (⊥ : intermediate_field F E) := intermediate_field.bot_equiv.transfer_galois.mpr (is_galois.self F) end is_galois_tower section galois_correspondence variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] variables (H : subgroup (E ≃ₐ[F] E)) (K : intermediate_field F E) namespace intermediate_field instance subgroup_action : faithful_mul_semiring_action H E := { smul := λ h x, h x, smul_zero := λ _, map_zero _, smul_add := λ _, map_add _, one_smul := λ _, rfl, smul_one := λ _, map_one _, mul_smul := λ _ _ _, rfl, smul_mul := λ _, map_mul _, eq_of_smul_eq_smul' := λ x y z, subtype.ext (alg_equiv.ext z) } /-- The intermediate_field fixed by a subgroup -/ def fixed_field : intermediate_field F E := { carrier := mul_action.fixed_points H E, zero_mem' := λ g, smul_zero g, add_mem' := λ a b hx hy g, by rw [smul_add g a b, hx, hy], neg_mem' := λ a hx g, by rw [smul_neg g a, hx], one_mem' := λ g, smul_one g, mul_mem' := λ a b hx hy g, by rw [smul_mul' g a b, hx, hy], inv_mem' := λ a hx g, by rw [smul_inv _ g a, hx], algebra_map_mem' := λ a g, commutes g a } lemma findim_fixed_field_eq_card [finite_dimensional F E] : findim (fixed_field H) E = fintype.card H := fixed_points.findim_eq_card H E /-- The subgroup fixing an intermediate_field -/ def fixing_subgroup : subgroup (E ≃ₐ[F] E) := { carrier := λ ϕ, ∀ x : K, ϕ x = x, one_mem' := λ _, rfl, mul_mem' := λ _ _ hx hy _, (congr_arg _ (hy _)).trans (hx _), inv_mem' := λ _ hx _, (equiv.symm_apply_eq (to_equiv _)).mpr (hx _).symm } lemma le_iff_le : K ≤ fixed_field H ↔ H ≤ fixing_subgroup K := ⟨λ h g hg x, h (subtype.mem x) ⟨g, hg⟩, λ h x hx g, h (subtype.mem g) ⟨x, hx⟩⟩ /-- The fixing_subgroup of `K : intermediate_field F E` is isomorphic to `E ≃ₐ[K] E` -/ def fixing_subgroup_equiv : fixing_subgroup K ≃* (E ≃ₐ[K] E) := { to_fun := λ ϕ, of_bijective (alg_hom.mk ϕ (map_one ϕ) (map_mul ϕ) (map_zero ϕ) (map_add ϕ) (ϕ.mem)) (bijective ϕ), inv_fun := λ ϕ, ⟨of_bijective (alg_hom.mk ϕ (ϕ.map_one) (ϕ.map_mul) (ϕ.map_zero) (ϕ.map_add) (λ r, ϕ.commutes (algebra_map F K r))) (ϕ.bijective), ϕ.commutes⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl }, map_mul' := λ _ _, by { ext, refl } } theorem fixing_subgroup_fixed_field [finite_dimensional F E] : fixing_subgroup (fixed_field H) = H := begin have H_le : H ≤ (fixing_subgroup (fixed_field H)) := (le_iff_le _ _).mp (le_refl _), suffices : fintype.card H = fintype.card (fixing_subgroup (fixed_field H)), { exact subgroup.ext' (set.eq_of_inclusion_surjective ((fintype.bijective_iff_injective_and_card (set.inclusion H_le)).mpr ⟨set.inclusion_injective H_le, this⟩).2).symm }, apply fintype.card_congr, refine (fixed_points.to_alg_hom_equiv H E).trans _, refine (alg_equiv_equiv_alg_hom (fixed_field H) E).symm.trans _, exact (fixing_subgroup_equiv (fixed_field H)).to_equiv.symm end instance fixed_field.algebra : algebra K (fixed_field (fixing_subgroup K)) := { smul := λ x y, ⟨x*y, λ ϕ, by rw [smul_mul', (show ϕ • ↑x = ↑x, by exact subtype.mem ϕ x), (show ϕ • ↑y = ↑y, by exact subtype.mem y ϕ)]⟩, to_fun := λ x, ⟨x, λ ϕ, subtype.mem ϕ x⟩, map_zero' := rfl, map_add' := λ _ _, rfl, map_one' := rfl, map_mul' := λ _ _, rfl, commutes' := λ _ _, mul_comm _ _, smul_def' := λ _ _, rfl } instance fixed_field.is_scalar_tower : is_scalar_tower K (fixed_field (fixing_subgroup K)) E := ⟨λ _ _ _, mul_assoc _ _ _⟩ end intermediate_field namespace is_galois theorem fixed_field_fixing_subgroup [finite_dimensional F E] [h : is_galois F E] : intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) = K := begin have K_le : K ≤ intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) := (intermediate_field.le_iff_le _ _).mpr (le_refl _), suffices : findim K E = findim (intermediate_field.fixed_field (intermediate_field.fixing_subgroup K)) E, { exact (intermediate_field.eq_of_le_of_findim_eq' K_le this).symm }, rw [intermediate_field.findim_fixed_field_eq_card, fintype.card_congr (intermediate_field.fixing_subgroup_equiv K).to_equiv], exact (card_aut_eq_findim K E).symm, end lemma card_fixing_subgroup_eq_findim [finite_dimensional F E] [is_galois F E] : fintype.card (intermediate_field.fixing_subgroup K) = findim K E := by conv { to_rhs, rw [←fixed_field_fixing_subgroup K, intermediate_field.findim_fixed_field_eq_card] } /-- The Galois correspondence from intermediate fields to subgroups -/ def intermediate_field_equiv_subgroup [finite_dimensional F E] [is_galois F E] : intermediate_field F E ≃o order_dual (subgroup (E ≃ₐ[F] E)) := { to_fun := intermediate_field.fixing_subgroup, inv_fun := intermediate_field.fixed_field, left_inv := λ K, fixed_field_fixing_subgroup K, right_inv := λ H, intermediate_field.fixing_subgroup_fixed_field H, map_rel_iff' := λ K L, by { rw [←fixed_field_fixing_subgroup L, intermediate_field.le_iff_le, fixed_field_fixing_subgroup L, ←order_dual.dual_le], refl } } /-- The Galois correspondence as a galois_insertion -/ def galois_insertion_intermediate_field_subgroup [finite_dimensional F E] : galois_insertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ K _, intermediate_field.fixing_subgroup K, gc := λ K H, (intermediate_field.le_iff_le H K).symm, le_l_u := λ H, le_of_eq (intermediate_field.fixing_subgroup_fixed_field H).symm, choice_eq := λ K _, rfl } /-- The Galois correspondence as a galois_coinsertion -/ def galois_coinsertion_intermediate_field_subgroup [finite_dimensional F E] [is_galois F E] : galois_coinsertion (order_dual.to_dual ∘ (intermediate_field.fixing_subgroup : intermediate_field F E → subgroup (E ≃ₐ[F] E))) ((intermediate_field.fixed_field : subgroup (E ≃ₐ[F] E) → intermediate_field F E) ∘ order_dual.to_dual) := { choice := λ H _, intermediate_field.fixed_field H, gc := λ K H, (intermediate_field.le_iff_le H K).symm, u_l_le := λ K, le_of_eq (fixed_field_fixing_subgroup K), choice_eq := λ H _, rfl } end is_galois end galois_correspondence section galois_equivalent_definitions variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E] namespace is_galois lemma is_separable_splitting_field [finite_dimensional F E] [h : is_galois F E] : ∃ p : polynomial F, p.separable ∧ p.is_splitting_field F E := begin cases field.exists_primitive_element h.1 with α h1, have h2 : is_integral F α := h.integral α, have h3 : (minimal_polynomial h2).separable := h.separable α, have h4 : (minimal_polynomial h2).splits (algebra_map F E) := h.normal α, use [minimal_polynomial h2, h3, h4], rw [eq_top_iff, ←intermediate_field.top_to_subalgebra, ←h1], rw intermediate_field.adjoin_simple_to_subalgebra_of_integral F α h2, apply algebra.adjoin_mono, rw [set.singleton_subset_iff, finset.mem_coe, multiset.mem_to_finset, polynomial.mem_roots], { dsimp only [polynomial.is_root], rw [polynomial.eval_map, ←polynomial.aeval_def], exact minimal_polynomial.aeval h2 }, { exact polynomial.map_ne_zero (minimal_polynomial.ne_zero h2) } end lemma of_fixed_field_eq_bot [finite_dimensional F E] (h : intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E)) = ⊥) : is_galois F E := begin rw [←is_galois_iff_is_galois_bot, ←h], exact is_galois.of_fixed_field E (⊤ : subgroup (E ≃ₐ[F] E)), end lemma of_card_aut_eq_findim [finite_dimensional F E] (h : fintype.card (E ≃ₐ[F] E) = findim F E) : is_galois F E := begin apply of_fixed_field_eq_bot, have p : 0 < findim (intermediate_field.fixed_field (⊤ : subgroup (E ≃ₐ[F] E))) E := findim_pos, rw [←intermediate_field.findim_eq_one_iff, ←mul_left_inj' (ne_of_lt p).symm, findim_mul_findim, ←h, one_mul, intermediate_field.findim_fixed_field_eq_card], exact fintype.card_congr { to_fun := λ g, ⟨g, subgroup.mem_top g⟩, inv_fun := coe, left_inv := λ g, rfl, right_inv := λ _, by { ext, refl } }, end variables {F} {E} {p : polynomial F} lemma of_separable_splitting_field_aux [hFE : finite_dimensional F E] [sp : p.is_splitting_field F E] (hp : p.separable) (K : intermediate_field F E) {x : E} (hx : x ∈ (p.map (algebra_map F E)).roots) : fintype.card ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) = fintype.card (K →ₐ[F] E) * findim K K⟮x⟯ := begin have h : is_integral K x := is_integral_of_is_scalar_tower x (is_integral_of_noetherian hFE x), have h1 : p ≠ 0 := λ hp, by rwa [hp, polynomial.map_zero, polynomial.roots_zero] at hx, have h2 : (minimal_polynomial h) ∣ p.map (algebra_map F K), { apply minimal_polynomial.dvd, rw [polynomial.aeval_def, polynomial.eval₂_map, ←polynomial.eval_map], exact (polynomial.mem_roots (polynomial.map_ne_zero h1)).mp hx }, let key_equiv : ((↑K⟮x⟯ : intermediate_field F E) →ₐ[F] E) ≃ Σ (f : K →ₐ[F] E), @alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f) := equiv.trans (alg_equiv.arrow_congr (intermediate_field.lift2_alg_equiv K⟮x⟯) (alg_equiv.refl)) alg_hom_equiv_sigma, haveI : Π (f : K →ₐ[F] E), fintype (@alg_hom K K⟮x⟯ E _ _ _ _ (ring_hom.to_algebra f)) := λ f, by { apply fintype.of_injective (sigma.mk f) (λ _ _ H, eq_of_heq ((sigma.mk.inj H).2)), exact fintype.of_equiv _ key_equiv }, rw [fintype.card_congr key_equiv, fintype.card_sigma, intermediate_field.adjoin.findim h], apply finset.sum_const_nat, intros f hf, rw ← @intermediate_field.card_alg_hom_adjoin_integral K _ E _ _ x E _ (ring_hom.to_algebra f) h, { apply fintype.card_congr, refl }, { exact polynomial.separable.of_dvd ((polynomial.separable_map (algebra_map F K)).mpr hp) h2 }, { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero h1) _ h2, rw [polynomial.splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact sp.splits }, end lemma of_separable_splitting_field [sp : p.is_splitting_field F E] (hp : p.separable) : is_galois F E := begin haveI hFE : finite_dimensional F E := polynomial.is_splitting_field.finite_dimensional E p, let s := (p.map (algebra_map F E)).roots.to_finset, have adjoin_root := intermediate_field.ext (subalgebra.ext_iff.mp (eq.trans (top_le_iff.mp (eq.trans_le sp.adjoin_roots.symm (intermediate_field.algebra_adjoin_le_adjoin F ↑s))) intermediate_field.top_to_subalgebra.symm)), let P : intermediate_field F E → Prop := λ K, fintype.card (K →ₐ[F] E) = findim F K, suffices : P (intermediate_field.adjoin F ↑s), { rw adjoin_root at this, apply of_card_aut_eq_findim, rw ← eq.trans this (linear_equiv.findim_eq intermediate_field.top_equiv.to_linear_equiv), exact fintype.card_congr (equiv.trans (alg_equiv_equiv_alg_hom F E) (alg_equiv.arrow_congr intermediate_field.top_equiv.symm alg_equiv.refl)) }, apply intermediate_field.induction_on_adjoin_finset s P, { have key := intermediate_field.card_alg_hom_adjoin_integral F (show is_integral F (0 : E), by exact is_integral_zero), rw [minimal_polynomial.zero, polynomial.nat_degree_X] at key, specialize key polynomial.separable_X (polynomial.splits_X (algebra_map F E)), rw [←@subalgebra.findim_bot F E _ _ _, ←intermediate_field.bot_to_subalgebra] at key, refine eq.trans _ key, apply fintype.card_congr, rw intermediate_field.adjoin_zero }, intros K x hx hK, simp only [P] at *, rw [of_separable_splitting_field_aux hp K (multiset.mem_to_finset.mp hx), hK, findim_mul_findim], exact (linear_equiv.findim_eq (intermediate_field.lift2_alg_equiv K⟮x⟯).to_linear_equiv).symm, end end is_galois end galois_equivalent_definitions
e116889ab877de2aa2c3a66aa44965acd78f5c3b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebraic_geometry/structure_sheaf.lean
e475436f0c5b5456a1c7a4c830e19649f54434ee
[ "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
25,022
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import algebraic_geometry.prime_spectrum import algebra.category.CommRing.colimits import algebra.category.CommRing.limits import topology.sheaves.local_predicate import topology.sheaves.forget import ring_theory.localization import ring_theory.subring /-! # The structure sheaf on `prime_spectrum R`. We define the structure sheaf on `Top.of (prime_spectrum R)`, for a commutative ring `R`. We define this as a subsheaf of the sheaf of dependent functions into the localizations, cut out by the condition that the function must be locally equal to a ratio of elements of `R`. Because the condition "is equal to a fraction" passes to smaller open subsets, the subset of functions satisfying this condition is automatically a subpresheaf. Because the condition "is locally equal to a fraction" is local, it is also a subsheaf. (It may be helpful to refer back to `topology.sheaves.sheaf_of_functions`, where we show that dependent functions into any type family form a sheaf, and also `topology.sheaves.local_predicate`, where we characterise the predicates which pick out sub-presheaves and sub-sheaves of these sheaves.) We also set up the ring structure, obtaining `structure_sheaf R : sheaf CommRing (Top.of (prime_spectrum R))`. -/ universe u noncomputable theory variables (R : Type u) [comm_ring R] open Top open topological_space open category_theory open opposite namespace algebraic_geometry /-- $Spec R$, just as a topological space. -/ def Spec.Top : Top := Top.of (prime_spectrum R) namespace structure_sheaf /-- The type family over `prime_spectrum R` consisting of the localization over each point. -/ @[derive [comm_ring, local_ring]] def localizations (P : Spec.Top R) : Type u := localization.at_prime P.as_ideal instance (P : Spec.Top R) : inhabited (localizations R P) := ⟨(localization.of _).to_map 1⟩ variables {R} /-- The predicate saying that a dependent function on an open `U` is realised as a fixed fraction `r / s` in each of the stalks (which are localizations at various prime ideals). -/ def is_fraction {U : opens (Spec.Top R)} (f : Π x : U, localizations R x) : Prop := ∃ (r s : R), ∀ x : U, ¬ (s ∈ x.1.as_ideal) ∧ f x * (localization.of _).to_map s = (localization.of _).to_map r variables (R) /-- The predicate `is_fraction` is "prelocal", in the sense that if it holds on `U` it holds on any open subset `V` of `U`. -/ def is_fraction_prelocal : prelocal_predicate (localizations R) := { pred := λ U f, is_fraction f, res := by { rintro V U i f ⟨r, s, w⟩, exact ⟨r, s, λ x, w (i x)⟩ } } /-- We will define the structure sheaf as the subsheaf of all dependent functions in `Π x : U, localizations R x` consisting of those functions which can locally be expressed as a ratio of (the images in the localization of) elements of `R`. Quoting Hartshorne: For an open set $$U ⊆ Spec A$$, we define $$𝒪(U)$$ to be the set of functions $$s : U → ⨆_{𝔭 ∈ U} A_𝔭$$, such that $s(𝔭) ∈ A_𝔭$$ for each $$𝔭$$, and such that $$s$$ is locally a quotient of elements of $$A$$: to be precise, we require that for each $$𝔭 ∈ U$$, there is a neighborhood $$V$$ of $$𝔭$$, contained in $$U$$, and elements $$a, f ∈ A$$, such that for each $$𝔮 ∈ V, f ∉ 𝔮$$, and $$s(𝔮) = a/f$$ in $$A_𝔮$$. Now Hartshorne had the disadvantage of not knowing about dependent functions, so we replace his circumlocution about functions into a disjoint union with `Π x : U, localizations x`. -/ def is_locally_fraction : local_predicate (localizations R) := (is_fraction_prelocal R).sheafify @[simp] lemma is_locally_fraction_pred {U : opens (Spec.Top R)} (f : Π x : U, localizations R x) : (is_locally_fraction R).pred f = ∀ x : U, ∃ (V) (m : x.1 ∈ V) (i : V ⟶ U), ∃ (r s : R), ∀ y : V, ¬ (s ∈ y.1.as_ideal) ∧ f (i y : U) * (localization.of _).to_map s = (localization.of _).to_map r := rfl /-- The functions satisfying `is_locally_fraction` form a subring. -/ def sections_subring (U : (opens (Spec.Top R))ᵒᵖ) : subring (Π x : unop U, localizations R x) := { carrier := { f | (is_locally_fraction R).pred f }, zero_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 0, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, one_mem' := begin refine λ x, ⟨unop U, x.2, 𝟙 _, 1, 1, λ y, ⟨_, _⟩⟩, { rw ←ideal.ne_top_iff_one, exact y.1.is_prime.1, }, { simp, }, end, add_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * sb + rb * sa, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [add_mul, ring_hom.map_add, pi.add_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_assoc], congr' 2, rw [mul_comm], refl, } end, neg_mem' := begin intros a ha x, rcases ha x with ⟨V, m, i, r, s, w⟩, refine ⟨V, m, i, -r, s, _⟩, intro y, rcases w y with ⟨nm, w⟩, fsplit, { exact nm, }, { simp only [ring_hom.map_neg, pi.neg_apply], erw [←w], simp only [neg_mul_eq_neg_mul_symm], } end, mul_mem' := begin intros a b ha hb x, rcases ha x with ⟨Va, ma, ia, ra, sa, wa⟩, rcases hb x with ⟨Vb, mb, ib, rb, sb, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ra * rb, sa * sb, _⟩, intro y, rcases wa (opens.inf_le_left _ _ y) with ⟨nma, wa⟩, rcases wb (opens.inf_le_right _ _ y) with ⟨nmb, wb⟩, fsplit, { intro H, cases y.1.is_prime.mem_or_mem H; contradiction, }, { simp only [pi.mul_apply, ring_hom.map_mul], erw [←wa, ←wb], simp only [mul_left_comm, mul_assoc, mul_comm], refl, } end, } end structure_sheaf open structure_sheaf /-- The structure sheaf (valued in `Type`, not yet `CommRing`) is the subsheaf consisting of functions satisfying `is_locally_fraction`. -/ def structure_sheaf_in_Type : sheaf (Type u) (Spec.Top R):= subsheaf_to_Types (is_locally_fraction R) instance comm_ring_structure_sheaf_in_Type_obj (U : (opens (Spec.Top R))ᵒᵖ) : comm_ring ((structure_sheaf_in_Type R).presheaf.obj U) := (sections_subring R U).to_comm_ring open prime_spectrum /-- The `stalk_to_fiber` map for the structure sheaf is surjective. (In fact, an isomorphism, as constructed below in `stalk_iso_Type`.) -/ lemma structure_sheaf_stalk_to_fiber_surjective (x : Top.of (prime_spectrum R)) : function.surjective (stalk_to_fiber (is_locally_fraction R) x) := begin apply stalk_to_fiber_surjective, intro t, obtain ⟨r, ⟨s, hs⟩, rfl⟩ := (localization.of _).mk'_surjective t, exact ⟨⟨basic_open s, hs⟩, λ y, (localization.of _).mk' r ⟨s, y.2⟩, ⟨prelocal_predicate.sheafify_of ⟨r, s, λ y, ⟨y.2, localization_map.mk'_spec _ _ _⟩⟩, rfl⟩⟩, end /-- The `stalk_to_fiber` map for the structure sheaf is injective. (In fact, an isomorphism, as constructed below in `stalk_iso_Type`.) The proof here follows the argument in Hartshorne's Algebraic Geometry, Proposition II.2.2. -/ lemma structure_sheaf_stalk_to_fiber_injective (x : Top.of (prime_spectrum R)) : function.injective (stalk_to_fiber (is_locally_fraction R) x) := begin apply stalk_to_fiber_injective, intros U V fU hU fV hV e, rcases hU ⟨x, U.2⟩ with ⟨U', mU, iU, ⟨a, b, wU⟩⟩, rcases hV ⟨x, V.2⟩ with ⟨V', mV, iV, ⟨c, d, wV⟩⟩, have wUx := (wU ⟨x, mU⟩).2, dsimp at wUx, have wVx := (wV ⟨x, mV⟩).2, dsimp at wVx, have e' := congr_arg (λ z, z * ((localization.of _).to_map (b * d))) e, dsimp at e', simp only [←mul_assoc, ring_hom.map_mul] at e', rw [mul_right_comm (fV _)] at e', erw [wUx, wVx] at e', simp only [←ring_hom.map_mul] at e', have := @localization_map.mk'_eq_iff_eq _ _ _ _ _ (localization.of (as_ideal x).prime_compl) a c ⟨b, (wU ⟨x, mU⟩).1⟩ ⟨d, (wV ⟨x, mV⟩).1⟩, dsimp at this, rw ←this at e', rw localization_map.eq at e', rcases e' with ⟨⟨h, hh⟩, e''⟩, dsimp at e'', let Wb : opens _ := basic_open b, let Wd : opens _ := basic_open d, let Wh : opens _ := basic_open h, use ((Wb ⊓ Wd) ⊓ Wh) ⊓ (U' ⊓ V'), refine ⟨⟨⟨(wU ⟨x, mU⟩).1, (wV ⟨x, mV⟩).1⟩, hh⟩, ⟨mU, mV⟩⟩, refine ⟨_, _, _⟩, change _ ⟶ U.val, exact (opens.inf_le_right _ _) ≫ (opens.inf_le_left _ _) ≫ iU, change _ ⟶ V.val, exact (opens.inf_le_right _ _) ≫ (opens.inf_le_right _ _) ≫ iV, intro w, dsimp, have wU' := (wU ⟨w.1, w.2.2.1⟩).2, dsimp at wU', have wV' := (wV ⟨w.1, w.2.2.2⟩).2, dsimp at wV', -- We need to prove `fU w = fV w`. -- First we show that is suffices to prove `fU w * b * d * h = fV w * b * d * h`. -- Then we calculate (at w) as follows: -- fU w * b * d * h -- = a * d * h : wU' -- ... = c * b * h : e'' -- ... = fV w * d * b * h : wV' have u : is_unit ((localization.of (as_ideal w.1).prime_compl).to_map (b * d * h)), { simp only [ring_hom.map_mul], apply is_unit.mul, apply is_unit.mul, exact (localization.of (as_ideal w.1).prime_compl).map_units ⟨b, (wU ⟨w, w.2.2.1⟩).1⟩, exact (localization.of (as_ideal w.1).prime_compl).map_units ⟨d, (wV ⟨w, w.2.2.2⟩).1⟩, exact (localization.of (as_ideal w.1).prime_compl).map_units ⟨h, w.2.1.2⟩, }, apply (is_unit.mul_left_inj u).1, conv_rhs { rw [mul_comm b d] }, simp only [ring_hom.map_mul, ←mul_assoc], erw [wU', wV'], dsimp, simp only [←ring_hom.map_mul, ←mul_assoc], rw e'', end /-- The structure presheaf, valued in `CommRing`, constructed by dressing up the `Type` valued structure presheaf. -/ @[simps] def structure_presheaf_in_CommRing : presheaf CommRing (Spec.Top R) := { obj := λ U, CommRing.of ((structure_sheaf_in_Type R).presheaf.obj U), map := λ U V i, { to_fun := ((structure_sheaf_in_Type R).presheaf.map i), map_zero' := rfl, map_add' := λ x y, rfl, map_one' := rfl, map_mul' := λ x y, rfl, }, } /-- Some glue, verifying that that structure presheaf valued in `CommRing` agrees with the `Type` valued structure presheaf. -/ def structure_presheaf_comp_forget : structure_presheaf_in_CommRing R ⋙ (forget CommRing) ≅ (structure_sheaf_in_Type R).presheaf := nat_iso.of_components (λ U, iso.refl _) (by tidy) open Top.presheaf /-- The structure sheaf on $Spec R$, valued in `CommRing`. This is provided as a bundled `SheafedSpace` as `Spec.SheafedSpace R` later. -/ def structure_sheaf : sheaf CommRing (Spec.Top R) := { presheaf := structure_presheaf_in_CommRing R, sheaf_condition := -- We check the sheaf condition under `forget CommRing`. (sheaf_condition_equiv_sheaf_condition_comp _ _).symm (sheaf_condition_equiv_of_iso (structure_presheaf_comp_forget R).symm (structure_sheaf_in_Type R).sheaf_condition), } @[simp] lemma res_apply (U V : opens (Spec.Top R)) (i : V ⟶ U) (s : (structure_sheaf R).presheaf.obj (op U)) (x : V) : ((structure_sheaf R).presheaf.map i.op s).1 x = (s.1 (i x) : _) := rfl /-- The stalk at `x` is equivalent (just as a type) to the localization at `x`. -/ def stalk_iso_Type (x : prime_spectrum R) : (structure_sheaf_in_Type R).presheaf.stalk x ≅ localization.at_prime x.as_ideal := (equiv.of_bijective _ ⟨structure_sheaf_stalk_to_fiber_injective R x, structure_sheaf_stalk_to_fiber_surjective R x⟩).to_iso /- Notation in this comment X = Spec R OX = structure sheaf In the following we construct an isomorphism between OX_p and R_p given any point p corresponding to a prime ideal in R. We do this via 8 steps: 1. def const (f g : R) (V) (hv : V ≤ D_g) : OX(V) [for api] 2. def to_open (U) : R ⟶ OX(U) 3. [2] def to_stalk (p : Spec R) : R ⟶ OX_p 4. [2] def to_basic_open (f : R) : R_f ⟶ OX(D_f) 5. [3] def localization_to_stalk (p : Spec R) : R_p ⟶ OX_p 6. def open_to_localization (U) (p) (hp : p ∈ U) : OX(U) ⟶ R_p 7. [6] def stalk_to_fiber_ring_hom (p : Spec R) : OX_p ⟶ R_p 8. [5,7] def stalk_iso (p : Spec R) : OX_p ≅ R_p In the square brackets we list the dependencies of a construction on the previous steps. -/ /-- The section of `structure_sheaf R` on an open `U` sending each `x ∈ U` to the element `f/g` in the localization of `R` at `x`. -/ def const (f g : R) (U : opens (Spec.Top R)) (hu : ∀ x ∈ U, g ∈ (x : Spec.Top R).as_ideal.prime_compl) : (structure_sheaf R).presheaf.obj (op U) := ⟨λ x, (localization.of _).mk' f ⟨g, hu x x.2⟩, λ x, ⟨U, x.2, 𝟙 _, f, g, λ y, ⟨hu y y.2, localization_map.mk'_spec _ _ _⟩⟩⟩ @[simp] lemma const_apply (f g : R) (U : opens (Spec.Top R)) (hu : ∀ x ∈ U, g ∈ (x : Spec.Top R).as_ideal.prime_compl) (x : U) : (const R f g U hu).1 x = (localization.of _).mk' f ⟨g, hu x x.2⟩ := rfl lemma const_apply' (f g : R) (U : opens (Spec.Top R)) (hu : ∀ x ∈ U, g ∈ (x : Spec.Top R).as_ideal.prime_compl) (x : U) (hx : g ∈ (as_ideal x.1).prime_compl) : (const R f g U hu).1 x = (localization.of _).mk' f ⟨g, hx⟩ := rfl lemma exists_const (U) (s : (structure_sheaf R).presheaf.obj (op U)) (x : Spec.Top R) (hx : x ∈ U) : ∃ (V : opens (Spec.Top R)) (hxV : x ∈ V) (i : V ⟶ U) (f g : R) hg, const R f g V hg = (structure_sheaf R).presheaf.map i.op s := let ⟨V, hxV, iVU, f, g, hfg⟩ := s.2 ⟨x, hx⟩ in ⟨V, hxV, iVU, f, g, λ y hyV, (hfg ⟨y, hyV⟩).1, subtype.eq $ funext $ λ y, (localization.of _).mk'_eq_iff_eq_mul.2 $ eq.symm $ (hfg y).2⟩ @[simp] lemma res_const (f g : R) (U hu V hv i) : (structure_sheaf R).presheaf.map i (const R f g U hu) = const R f g V hv := rfl lemma res_const' (f g : R) (V hv) : (structure_sheaf R).presheaf.map (hom_of_le hv).op (const R f g (basic_open g) (λ _, id)) = const R f g V hv := rfl lemma const_zero (f : R) (U hu) : const R 0 f U hu = 0 := subtype.eq $ funext $ λ x, (localization.of _).mk'_eq_iff_eq_mul.2 $ by erw [ring_hom.map_zero, subtype.val_eq_coe, subring.coe_zero, pi.zero_apply, zero_mul] lemma const_self (f : R) (U hu) : const R f f U hu = 1 := subtype.eq $ funext $ λ x, localization_map.mk'_self _ _ lemma const_one (U) : const R 1 1 U (λ p _, submonoid.one_mem _) = 1 := const_self R 1 U _ lemma const_add (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ + const R f₂ g₂ U hu₂ = const R (f₁ * g₂ + f₂ * g₁) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert (localization.of _).mk'_add f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_mul (f₁ f₂ g₁ g₂ : R) (U hu₁ hu₂) : const R f₁ g₁ U hu₁ * const R f₂ g₂ U hu₂ = const R (f₁ * f₂) (g₁ * g₂) U (λ x hx, submonoid.mul_mem _ (hu₁ x hx) (hu₂ x hx)) := subtype.eq $ funext $ λ x, eq.symm $ by convert (localization.of _).mk'_mul f₁ f₂ ⟨g₁, hu₁ x x.2⟩ ⟨g₂, hu₂ x x.2⟩ lemma const_ext {f₁ f₂ g₁ g₂ : R} {U hu₁ hu₂} (h : f₁ * g₂ = f₂ * g₁) : const R f₁ g₁ U hu₁ = const R f₂ g₂ U hu₂ := subtype.eq $ funext $ λ x, (localization.of _).mk'_eq_of_eq h.symm lemma const_congr {f₁ f₂ g₁ g₂ : R} {U hu} (hf : f₁ = f₂) (hg : g₁ = g₂) : const R f₁ g₁ U hu = const R f₂ g₂ U (hg ▸ hu) := by substs hf hg lemma const_mul_rev (f g : R) (U hu₁ hu₂) : const R f g U hu₁ * const R g f U hu₂ = 1 := by rw [const_mul, const_congr R rfl (mul_comm g f), const_self] lemma const_mul_cancel (f g₁ g₂ : R) (U hu₁ hu₂) : const R f g₁ U hu₁ * const R g₁ g₂ U hu₂ = const R f g₂ U hu₂ := by { rw [const_mul, const_ext], rw mul_assoc } lemma const_mul_cancel' (f g₁ g₂ : R) (U hu₁ hu₂) : const R g₁ g₂ U hu₂ * const R f g₁ U hu₁ = const R f g₂ U hu₂ := by rw [mul_comm, const_mul_cancel] /-- The canonical ring homomorphism interpreting an element of `R` as a section of the structure sheaf. -/ def to_open (U : opens (Spec.Top R)) : CommRing.of R ⟶ (structure_sheaf R).presheaf.obj (op U) := { to_fun := λ f, ⟨λ x, (localization.of _).to_map f, λ x, ⟨U, x.2, 𝟙 _, f, 1, λ y, ⟨(ideal.ne_top_iff_one _).1 y.1.2.1, by { rw [ring_hom.map_one, mul_one], refl } ⟩⟩⟩, map_one' := subtype.eq $ funext $ λ x, ring_hom.map_one _, map_mul' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_mul _ _ _, map_zero' := subtype.eq $ funext $ λ x, ring_hom.map_zero _, map_add' := λ f g, subtype.eq $ funext $ λ x, ring_hom.map_add _ _ _ } @[simp] lemma to_open_res (U V : opens (Spec.Top R)) (i : V ⟶ U) : to_open R U ≫ (structure_sheaf R).presheaf.map i.op = to_open R V := rfl @[simp] lemma to_open_apply (U : opens (Spec.Top R)) (f : R) (x : U) : (to_open R U f).1 x = (localization.of _).to_map f := rfl lemma to_open_eq_const (U : opens (Spec.Top R)) (f : R) : to_open R U f = const R f 1 U (λ x _, (ideal.ne_top_iff_one _).1 x.2.1) := subtype.eq $ funext $ λ x, eq.symm $ (localization.of _).mk'_one f /-- The canonical ring homomorphism interpreting an element of `R` as an element of the stalk of `structure_sheaf R` at `x`. -/ def to_stalk (x : Spec.Top R) : CommRing.of R ⟶ (structure_sheaf R).presheaf.stalk x := (to_open R ⊤ ≫ (structure_sheaf R).presheaf.germ ⟨x, ⟨⟩⟩ : _) @[simp] lemma to_open_germ (U : opens (Spec.Top R)) (x : U) : to_open R U ≫ (structure_sheaf R).presheaf.germ x = to_stalk R x := by { rw [← to_open_res R ⊤ U (hom_of_le le_top : U ⟶ ⊤), category.assoc, presheaf.germ_res], refl } @[simp] lemma germ_to_open (U : opens (Spec.Top R)) (x : U) (f : R) : (structure_sheaf R).presheaf.germ x (to_open R U f) = to_stalk R x f := by { rw ← to_open_germ, refl } lemma germ_to_top (x : Spec.Top R) (f : R) : (structure_sheaf R).presheaf.germ (⟨x, trivial⟩ : (⊤ : opens (Spec.Top R))) (to_open R ⊤ f) = to_stalk R x f := rfl lemma is_unit_to_basic_open_self (f : R) : is_unit (to_open R (basic_open f) f) := is_unit_of_mul_eq_one _ (const R 1 f (basic_open f) (λ _, id)) $ by rw [to_open_eq_const, const_mul_rev] /-- The canonical ring homomorphism interpreting `s ∈ R_f` as a section of the structure sheaf on the basic open defined by `f ∈ R`. -/ def to_basic_open (f : R) : CommRing.of (localization (submonoid.powers f)) ⟶ (structure_sheaf R).presheaf.obj (op $ basic_open f) := localization_map.away_map.lift f (localization.away.of f) (is_unit_to_basic_open_self R f) @[simp] lemma to_basic_open_mk' (s f : R) (g : submonoid.powers s) : to_basic_open R s ((localization.of _).mk' f g) = const R f g (basic_open s) (λ x hx, submonoid.powers_subset hx g.2) := ((localization.of _).lift_mk'_spec _ _ _ _).2 $ by rw [to_open_eq_const, to_open_eq_const, const_mul_cancel'] @[simp] lemma localization_to_basic_open (f : R) : @category_theory.category_struct.comp _ _ (CommRing.of R) (CommRing.of (localization (submonoid.powers f))) _ (localization.of $ submonoid.powers f).to_map (to_basic_open R f) = to_open R (basic_open f) := ring_hom.ext $ λ g, (localization.of _).lift_eq _ _ @[simp] lemma to_basic_open_to_map (s f : R) : to_basic_open R s ((localization.of _).to_map f) = const R f 1 (basic_open s) (λ _ _, submonoid.one_mem _) := ((localization.of _).lift_eq _ _).trans $ to_open_eq_const _ _ _ lemma is_unit_to_stalk (x : Spec.Top R) (f : x.as_ideal.prime_compl) : is_unit (to_stalk R x (f : R)) := by { erw ← germ_to_open R (basic_open (f : R)) ⟨x, f.2⟩ (f : R), exact ring_hom.is_unit_map _ (is_unit_to_basic_open_self R f) } /-- The canonical ring homomorphism from the localization of `R` at `p` to the stalk of the structure sheaf at the point `p`. -/ def localization_to_stalk (x : Spec.Top R) : CommRing.of (localization.at_prime x.as_ideal) ⟶ (structure_sheaf R).presheaf.stalk x := (localization.of _).lift (is_unit_to_stalk R x) @[simp] lemma localization_to_stalk_of (x : Spec.Top R) (f : R) : localization_to_stalk R x ((localization.of _).to_map f) = to_stalk R x f := (localization.of _).lift_eq _ f @[simp] lemma localization_to_stalk_mk' (x : Spec.Top R) (f : R) (s : (as_ideal x).prime_compl) : localization_to_stalk R x ((localization.of _).mk' f s) = (structure_sheaf R).presheaf.germ (⟨x, s.2⟩ : basic_open (s : R)) (const R f s (basic_open s) (λ _, id)) := ((localization.of _).lift_mk'_spec _ _ _ _).2 $ by erw [← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← germ_to_open R (basic_open s) ⟨x, s.2⟩, ← ring_hom.map_mul, to_open_eq_const, to_open_eq_const, const_mul_cancel'] /-- The ring homomorphism that takes a section of the structure sheaf of `R` on the open set `U`, implemented as a subtype of dependent functions to localizations at prime ideals, and evaluates the section on the point corresponding to a given prime ideal. -/ def open_to_localization (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) : (structure_sheaf R).presheaf.obj (op U) ⟶ CommRing.of (localization.at_prime x.as_ideal) := { to_fun := λ s, (s.1 ⟨x, hx⟩ : _), map_one' := rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, map_add' := λ _ _, rfl } @[simp] lemma coe_open_to_localization (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) : (open_to_localization R U x hx : (structure_sheaf R).presheaf.obj (op U) → localization.at_prime x.as_ideal) = (λ s, (s.1 ⟨x, hx⟩ : _)) := rfl lemma open_to_localization_apply (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) (s : (structure_sheaf R).presheaf.obj (op U)) : open_to_localization R U x hx s = (s.1 ⟨x, hx⟩ : _) := rfl /-- The ring homomorphism from the stalk of the structure sheaf of `R` at a point corresponding to a prime ideal `p` to the localization of `R` at `p`, formed by gluing the `open_to_localization` maps. -/ def stalk_to_fiber_ring_hom (x : Spec.Top R) : (structure_sheaf R).presheaf.stalk x ⟶ CommRing.of (localization.at_prime x.as_ideal) := limits.colimit.desc (((open_nhds.inclusion x).op) ⋙ (structure_sheaf R).presheaf) { X := _, ι := { app := λ U, open_to_localization R ((open_nhds.inclusion _).obj (unop U)) x (unop U).2, } } @[simp] lemma germ_comp_stalk_to_fiber_ring_hom (U : opens (Spec.Top R)) (x : U) : (structure_sheaf R).presheaf.germ x ≫ stalk_to_fiber_ring_hom R x = open_to_localization R U x x.2 := limits.colimit.ι_desc _ _ @[simp] lemma stalk_to_fiber_ring_hom_germ' (U : opens (Spec.Top R)) (x : Spec.Top R) (hx : x ∈ U) (s : (structure_sheaf R).presheaf.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).presheaf.germ ⟨x, hx⟩ s) = (s.1 ⟨x, hx⟩ : _) := ring_hom.ext_iff.1 (germ_comp_stalk_to_fiber_ring_hom R U ⟨x, hx⟩ : _) s @[simp] lemma stalk_to_fiber_ring_hom_germ (U : opens (Spec.Top R)) (x : U) (s : (structure_sheaf R).presheaf.obj (op U)) : stalk_to_fiber_ring_hom R x ((structure_sheaf R).presheaf.germ x s) = s.1 x := by { cases x, exact stalk_to_fiber_ring_hom_germ' R U _ _ _ } @[simp] lemma to_stalk_comp_stalk_to_fiber_ring_hom (x : Spec.Top R) : to_stalk R x ≫ stalk_to_fiber_ring_hom R x = (localization.of _).to_map := by { erw [to_stalk, category.assoc, germ_comp_stalk_to_fiber_ring_hom], refl } @[simp] lemma stalk_to_fiber_ring_hom_to_stalk (x : Spec.Top R) (f : R) : stalk_to_fiber_ring_hom R x (to_stalk R x f) = (localization.of _).to_map f := ring_hom.ext_iff.1 (to_stalk_comp_stalk_to_fiber_ring_hom R x) _ /-- The ring isomorphism between the stalk of the structure sheaf of `R` at a point `p` corresponding to a prime ideal in `R` and the localization of `R` at `p`. -/ def stalk_iso (x : Spec.Top R) : (structure_sheaf R).presheaf.stalk x ≅ CommRing.of (localization.at_prime x.as_ideal) := { hom := stalk_to_fiber_ring_hom R x, inv := localization_to_stalk R x, hom_inv_id' := (structure_sheaf R).presheaf.stalk_hom_ext $ λ U hxU, begin ext s, simp only [coe_comp], rw [coe_id, stalk_to_fiber_ring_hom_germ'], obtain ⟨V, hxV, iVU, f, g, hg, hs⟩ := exists_const _ _ s x hxU, erw [← res_apply R U V iVU s ⟨x, hxV⟩, ← hs, const_apply, localization_to_stalk_mk'], refine (structure_sheaf R).presheaf.germ_ext V hxV (hom_of_le hg) iVU _, erw [← hs, res_const'] end, inv_hom_id' := (localization.of x.as_ideal.prime_compl).epic_of_localization_map $ λ f, by simp only [ring_hom.comp_apply, coe_comp, coe_id, localization_to_stalk_of, stalk_to_fiber_ring_hom_to_stalk] } end algebraic_geometry
9f58c6574aee8aab384cc8d6f7ad60e4176a381a
9d00e4b237465921fb33aa10eed92a2495ca2e46
/implRules.lean
53163e8d01ce2c7faaa65ee5eedc652cc763def1
[]
no_license
Bpalkmim/LeanNatD
7756abf1ed7b0e7a3e3b9d16ad756018f5c70c7c
2e73bb44e44b955839e7a0874cd7013fbfb9c4e3
refs/heads/master
1,610,999,141,530
1,475,515,895,000
1,475,515,895,000
69,893,600
0
0
null
null
null
null
UTF-8
Lean
false
false
1,437
lean
namespace implRules print " " print "Provas com IMPL - início" print " " constant Proof : Prop → Type constant implies : Prop → Prop → Prop constants A B C : Prop -- Definições constant impl_intro {X Y : Prop} : (Π x : Proof X, Proof Y) → Proof Y → Proof (implies X Y) constant impl_elim {X Y : Prop} : Proof (implies X Y) → Proof X → Proof Y -- Termos úteis variable a : Proof A variable b : Proof B variable aIMPb : Proof (implies A B) variable aIMPc : Proof (implies A C) variable aDEPb : Π x : Proof A, Proof B variable aIMPbIMPc : Proof (implies A (implies B C)) variable bIMPaIMPc : Proof (implies B (implies A C)) variable concl : Π x : Proof (implies A (implies B C)), Proof (implies B (implies A C)) -- Teste (A → (B → C)) → (B → (A → C)) check impl_intro concl (impl_intro (impl_elim bIMPaIMPc ) (impl_intro (impl_elim aIMPc ) (impl_elim (impl_elim aIMPbIMPc a) b ) ) ) -- Testes iniciais check @impl_intro check @impl_elim check impl_intro aDEPb b check impl_elim aIMPb a print "------" -- Testes parciais check impl_elim aIMPc check impl_elim (impl_elim aIMPbIMPc a) b check impl_intro (impl_elim aIMPc) (impl_elim (impl_elim aIMPbIMPc a) b) check impl_intro (impl_elim bIMPaIMPc) (impl_intro (impl_elim aIMPc) (impl_elim (impl_elim aIMPbIMPc a) b)) print "------" print " " print "Provas com IMPL - fim" print " " end implRules
aaa0a2d8008ff0faeefd7e8a9aac4116fa51207b
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/module/linear_map.lean
ee980b505cbaa0792d6b0924e1bf52f8cbd254ad
[ "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
18,668
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] /-- The `distrib_mul_action_hom` underlying a `linear_map`. -/ def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ := { map_zero' := zero_smul R (0 : M) ▸ zero_smul R (f.to_fun 0) ▸ f.map_smul' 0 0, ..f } instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [semimodule R M] [semimodule R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₗ[R] M₂) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) = f := ext $ λ _, rfl variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := f.to_distrib_mul_action_hom.map_zero variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance compatible_smul.is_scalar_tower {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [semimodule S M] [is_scalar_tower R S M] [has_scalar R M₂] [semimodule S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl variable (R) /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ def restrict_scalars {S : Type*} [semiring S] [semimodule S M] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] theorem ext_ring_iff {f g : R →ₗ[R] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] }⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f } instance compatible_smul.int_module {S : Type*} [semiring S] [semimodule ℤ M] [semimodule S M] [semimodule ℤ M₂] [semimodule S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simpa [add_smul] using ih }, case hn : n ih { simpa [sub_smul] using ih } end⟩ end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk {to_fun inv_fun map_add map_smul left_inv right_inv } : ⇑(⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) = to_fun := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma injective_to_equiv : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := injective_to_equiv.eq_iff lemma injective_to_linear_map : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, injective_to_equiv $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := injective_to_linear_map.eq_iff end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma to_linear_map_eq_coe : e.to_linear_map = ↑e := rfl @[simp, norm_cast] theorem coe_coe : ⇑(e : M →ₗ[R] M₂) = e := rfl @[simp] lemma coe_to_equiv : ⇑e.to_equiv = e := rfl @[simp] lemma coe_to_linear_map : ⇑e.to_linear_map = e := rfl @[simp] lemma to_fun_eq_coe : e.to_fun = e := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := injective_to_equiv (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun [semimodule R M] [semimodule R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := injective_to_equiv e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := injective_to_equiv e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma trans_symm [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [semimodule R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [semimodule R M] [semimodule R M₂] [semimodule R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] lemma mk_coe (h₁ h₂ f h₃ h₄) : (linear_equiv.mk e h₁ h₂ f h₃ h₄ : M ≃ₗ[R] M₂) = e := ext $ λ _, rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } lemma symm_bijective [semimodule R M] [semimodule R M₂] : function.bijective (symm : (M ≃ₗ[R] M₂) → (M₂ ≃ₗ[R] M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (f h₁ h₂ h₃ h₄) : (linear_equiv.mk f h₁ h₂ ⇑e h₃ h₄ : M₂ ≃ₗ[R] M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f h₁ h₂ h₃ h₄) : (⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm = { to_fun := f, inv_fun := e, ..(⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm } := rfl protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl end add_comm_monoid end linear_equiv
7f70213a49d96046166e513d0b8a11803ca243c4
63abd62053d479eae5abf4951554e1064a4c45b4
/test/push_neg.lean
81dfb40898fd444dd648afe688a9bbb3815965db
[ "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
2,038
lean
import tactic.push_neg import data.int.basic example (h : ∃ p: ℕ, ¬ ∀ n : ℕ, n > p) (h' : ∃ p: ℕ, ¬ ∃ n : ℕ, n < p) : ¬ ∀ n : ℕ, n = 0 := begin push_neg at *, guard_target_strict ∃ (n : ℕ), n ≠ 0, guard_hyp_strict h : ∃ (p n : ℕ), n ≤ p, guard_hyp_strict h' : ∃ (p : ℕ), ∀ (n : ℕ), p ≤ n, use 1, end -- In the next example, ℤ should be ℝ in maths, but I don't want to import real numbers -- for testing only local notation `|` x `|` := abs x example (a : ℕ → ℤ) (l : ℤ) (h : ¬ ∀ ε > 0, ∃ N, ∀ n ≥ N, | a n - l | < ε) : true := begin push_neg at h, guard_hyp_strict h : ∃ (ε : ℤ), ε > 0 ∧ ∀ (N : ℕ), ∃ (n : ℕ), n ≥ N ∧ ε ≤ |a n - l|, trivial end example (f : ℤ → ℤ) (x₀ y₀) (h : ¬ ∀ ε > 0, ∃ δ > 0, ∀ x, |x - x₀| ≤ δ → |f x - y₀| ≤ ε) : true := begin push_neg at h, guard_hyp_strict h : ∃ (ε : ℤ), ε > 0 ∧ ∀ δ > 0, (∃ (x : ℤ), |x - x₀| ≤ δ ∧ ε < |f x - y₀| ), trivial end example (n) : n*n ≠ 1 → n ≠ 1 := begin contrapose, rw [not_not, not_not], intro h, rw [h, one_mul] end example (n) : n*n ≠ 1 → n ≠ 1 := begin contrapose!, intro h, rw [h, one_mul] end example (n) (h : n*n ≠ 1) : n ≠ 1 := begin contrapose h, rw not_not at *, rw [h, one_mul] end example (n) (h : n*n ≠ 1) : n ≠ 1 := begin contrapose! h, rw [h, one_mul] end example (n) (h : n*n ≠ 1) : n ≠ 1 := begin contrapose! h with newh, rw [newh, one_mul] end example : 0 = 0 := begin success_if_fail_with_msg { contrapose } "The goal is not an implication, and you didn't specify an assumption", refl end -- Remember that ∀ is the same as Π which is a generalization of → so we need to make sure -- `contrapose` fails with a helpful error message in the next example. example : ∀ x : ℕ, x = x := begin success_if_fail_with_msg { contrapose } "contrapose only applies to nondependent arrows between props", intro, refl end
5c95b977d1d2c9bf34ed4fac8b979b201ad2b3cc
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic6.lean
6ef178c481dfc160a12874ddc290ca50e6411a51
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
180
lean
import standard using tactic (renaming id->id_tac) definition id {A : Type} (a : A) := a theorem tst {A B : Prop} (H1 : A) (H2 : B) : id A := by unfold id; assumption check tst
5021e5c4c8181ecf93914b1f3fdc8f295cb86da9
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/multiset/antidiagonal.lean
e47b30cfdec503374259b939a60ba2475a6708ee
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,053
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.multiset.powerset /-! # The antidiagonal on a multiset. The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ namespace multiset open list variables {α β : Type*} /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem antidiagonal_coe (l : list α) : @antidiagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem antidiagonal_coe' (l : list α) : @antidiagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ x.1 + x.2 = s := quotient.induction_on s $ λ l, begin simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], cases x with x₁ x₂, exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩ end @[simp] theorem antidiagonal_map_fst (s : multiset α) : (antidiagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_map_snd (s : multiset α) : (antidiagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_zero : @antidiagonal α 0 = {(0, 0)} := rfl @[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a ::ₘ s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := quotient.induction_on s $ λ l, begin simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powerset_aux'_cons, cons_coe, coe_map, antidiagonal_coe', coe_add], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_antidiagonal (s : multiset α) : card (antidiagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← antidiagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, have := @sum_map_mul_left α β _, simp [ih, add_mul, mul_comm, mul_left_comm (f a), mul_left_comm (g a), mul_assoc, sum_map_mul_left.symm], cc }, end end multiset
5aa3f9738af8de5bd36b164ab35bb6946fae514d
70f8755415fa7a17f87402cde4651e9f4db1b5bb
/src/qpf.lean
3e2dc8ffa5a459ca853c397d045a62fa2971f4cf
[ "Apache-2.0" ]
permissive
shingarov/qpf
ab935dc2298db12c87ac011a2e4d2c27e0bdef4b
debe2eacb8cf46b21aba2eaf3f2e20940da0263b
refs/heads/master
1,653,705,576,607
1,570,136,035,000
1,570,136,035,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,370
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad We assume the following: `P` : a polynomial functor `W` : its W-type `M` : its M-type `F` : a functor We define: `q` : `qpf` data, representing `F` as a quotient of `P` The main goal is to construct: `fix` : the initial algebra with structure map `F fix → fix`. `cofix` : the final coalgebra with structure map `cofix → F cofix` We also show that the composition of qpfs is a qpf, and that the quotient of a qpf is a qpf. -/ import tactic.interactive data.multiset pfunctor universe u /- Quotients of polynomial functors. Roughly speaking, saying that `F` is a quotient of a polynomial functor means that for each `α`, elements of `F α` are represented by pairs `⟨a, f⟩`, where `a` is the shape of the object and `f` indexes the relevant elements of `α`, in a suitably natural manner. -/ class qpf (F : Type u → Type u) [functor F] := (P : pfunctor.{u}) (abs : Π {α}, P.apply α → F α) (repr : Π {α}, F α → P.apply α) (abs_repr : ∀ {α} (x : F α), abs (repr x) = x) (abs_map : ∀ {α β} (f : α → β) (p : P.apply α), abs (f <$> p) = f <$> abs p) namespace qpf variables {F : Type u → Type u} [functor F] [q : qpf F] include q open functor (liftp liftr) /- Show that every qpf is a lawful functor. Note: every functor has a field, map_comp, and is_lawful_functor has the defining characterization. We can only propagate the assumption. -/ theorem id_map {α : Type*} (x : F α) : id <$> x = x := by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map], reflexivity } theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) (x : F α) : (g ∘ f) <$> x = g <$> f <$> x := by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map, ←abs_map, ←abs_map], reflexivity } theorem is_lawful_functor (h : ∀ α β : Type u, @functor.map_const F _ α _ = functor.map ∘ function.const β) : is_lawful_functor F := { map_const_eq := h, id_map := @id_map F _ _, comp_map := @comp_map F _ _ } /- Lifting predicates and relations -/ section open functor theorem liftp_iff {α : Type u} (p : α → Prop) (x : F α) : liftp p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i, p (f i) := begin split, { rintros ⟨y, hy⟩, cases h : repr y with a f, use [a, λ i, (f i).val], split, { rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity }, intro i, apply (f i).property }, rintros ⟨a, f, h₀, h₁⟩, dsimp at *, use abs (⟨a, λ i, ⟨f i, h₁ i⟩⟩), rw [←abs_map, h₀], reflexivity end theorem liftp_iff' {α : Type u} (p : α → Prop) (x : F α) : liftp p x ↔ ∃ u : q.P.apply α, abs u = x ∧ ∀ i, p (u.snd i) := begin split, { rintros ⟨y, hy⟩, cases h : repr y with a f, use ⟨a, λ i, (f i).val⟩, dsimp, split, { rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity }, intro i, apply (f i).property }, rintros ⟨⟨a, f⟩, h₀, h₁⟩, dsimp at *, use abs (⟨a, λ i, ⟨f i, h₁ i⟩⟩), rw [←abs_map, ←h₀], reflexivity end theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : F α) : liftr r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : repr u with a f, use [a, λ i, (f i).val.fst, λ i, (f i).val.snd], split, { rw [←xeq, ←abs_repr u, h, ←abs_map], refl }, split, { rw [←yeq, ←abs_repr u, h, ←abs_map], refl }, intro i, exact (f i).property }, rintros ⟨a, f₀, f₁, xeq, yeq, h⟩, use abs ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩, dsimp, split, { rw [xeq, ←abs_map], refl }, rw [yeq, ←abs_map], refl end end /- Think of trees in the `W` type corresponding to `P` as representatives of elements of the least fixed point of `F`, and assign a canonical representative to each equivalence class of trees. -/ /-- does recursion on `q.P.W` using `g : F α → α` rather than `g : P α → α` -/ def recF {α : Type*} (g : F α → α) : q.P.W → α | ⟨a, f⟩ := g (abs ⟨a, λ x, recF (f x)⟩) theorem recF_eq {α : Type*} (g : F α → α) (x : q.P.W) : recF g x = g (abs (recF g <$> q.P.W_dest x)) := by cases x; reflexivity theorem recF_eq' {α : Type*} (g : F α → α) (a : q.P.A) (f : q.P.B a → q.P.W) : recF g ⟨a, f⟩ = g (abs (recF g <$> ⟨a, f⟩)) := rfl /-- two trees are equivalent if their F-abstractions are -/ inductive Wequiv : q.P.W → q.P.W → Prop | ind (a : q.P.A) (f f' : q.P.B a → q.P.W) : (∀ x, Wequiv (f x) (f' x)) → Wequiv ⟨a, f⟩ ⟨a, f'⟩ | abs (a : q.P.A) (f : q.P.B a → q.P.W) (a' : q.P.A) (f' : q.P.B a' → q.P.W) : abs ⟨a, f⟩ = abs ⟨a', f'⟩ → Wequiv ⟨a, f⟩ ⟨a', f'⟩ | trans (u v w : q.P.W) : Wequiv u v → Wequiv v w → Wequiv u w /-- recF is insensitive to the representation -/ theorem recF_eq_of_Wequiv {α : Type u} (u : F α → α) (x y : q.P.W) : Wequiv x y → recF u x = recF u y := begin cases x with a f, cases y with b g, intro h, induction h, case qpf.Wequiv.ind : a f f' h ih { simp only [recF_eq', pfunctor.map_eq, function.comp, ih] }, case qpf.Wequiv.abs : a f a' f' h ih { simp only [recF_eq', abs_map, h] }, case qpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact eq.trans ih₁ ih₂ } end theorem Wequiv.abs' (x y : q.P.W) (h : abs (q.P.W_dest x) = abs (q.P.W_dest y)) : Wequiv x y := by { cases x, cases y, apply Wequiv.abs, apply h } theorem Wequiv.refl (x : q.P.W) : Wequiv x x := by cases x with a f; exact Wequiv.abs a f a f rfl theorem Wequiv.symm (x y : q.P.W) : Wequiv x y → Wequiv y x := begin cases x with a f, cases y with b g, intro h, induction h, case qpf.Wequiv.ind : a f f' h ih { exact Wequiv.ind _ _ _ ih }, case qpf.Wequiv.abs : a f a' f' h ih { exact Wequiv.abs _ _ _ _ h.symm }, case qpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact qpf.Wequiv.trans _ _ _ ih₂ ih₁} end /-- maps every element of the W type to a canonical representative -/ def Wrepr : q.P.W → q.P.W := recF (q.P.W_mk ∘ repr) theorem Wrepr_equiv (x : q.P.W) : Wequiv (Wrepr x) x := begin induction x with a f ih, apply Wequiv.trans, { change Wequiv (Wrepr ⟨a, f⟩) (q.P.W_mk (Wrepr <$> ⟨a, f⟩)), apply Wequiv.abs', have : Wrepr ⟨a, f⟩ = q.P.W_mk (repr (abs (Wrepr <$> ⟨a, f⟩))) := rfl, rw [this, pfunctor.W_dest_W_mk, abs_repr], reflexivity }, apply Wequiv.ind, exact ih end /- Define the fixed point as the quotient of trees under the equivalence relation. -/ def W_setoid : setoid q.P.W := ⟨Wequiv, @Wequiv.refl _ _ _, @Wequiv.symm _ _ _, @Wequiv.trans _ _ _⟩ local attribute [instance] W_setoid def fix (F : Type u → Type u) [functor F] [q : qpf F]:= quotient (W_setoid : setoid q.P.W) def fix.rec {α : Type*} (g : F α → α) : fix F → α := quot.lift (recF g) (recF_eq_of_Wequiv g) def fix_to_W : fix F → q.P.W := quotient.lift Wrepr (recF_eq_of_Wequiv (λ x, q.P.W_mk (repr x))) def fix.mk (x : F (fix F)) : fix F := quot.mk _ (q.P.W_mk (fix_to_W <$> repr x)) def fix.dest : fix F → F (fix F) := fix.rec (functor.map fix.mk) theorem fix.rec_eq {α : Type*} (g : F α → α) (x : F (fix F)) : fix.rec g (fix.mk x) = g (fix.rec g <$> x) := have recF g ∘ fix_to_W = fix.rec g, by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv, apply Wrepr_equiv }, begin conv { to_lhs, rw [fix.rec, fix.mk], dsimp }, cases h : repr x with a f, rw [pfunctor.map_eq, recF_eq, ←pfunctor.map_eq, pfunctor.W_dest_W_mk, ←pfunctor.comp_map, abs_map, ←h, abs_repr, this] end theorem fix.ind_aux (a : q.P.A) (f : q.P.B a → q.P.W) : fix.mk (abs ⟨a, λ x, ⟦f x⟧⟩) = ⟦⟨a, f⟩⟧ := have fix.mk (abs ⟨a, λ x, ⟦f x⟧⟩) = ⟦Wrepr ⟨a, f⟩⟧, begin apply quot.sound, apply Wequiv.abs', rw [pfunctor.W_dest_W_mk, abs_map, abs_repr, ←abs_map, pfunctor.map_eq], conv { to_rhs, simp only [Wrepr, recF_eq, pfunctor.W_dest_W_mk, abs_repr] }, reflexivity end, by { rw this, apply quot.sound, apply Wrepr_equiv } theorem fix.ind_rec {α : Type u} (g₁ g₂ : fix F → α) (h : ∀ x : F (fix F), g₁ <$> x = g₂ <$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) : ∀ x, g₁ x = g₂ x := begin apply quot.ind, intro x, induction x with a f ih, change g₁ ⟦⟨a, f⟩⟧ = g₂ ⟦⟨a, f⟩⟧, rw [←fix.ind_aux a f], apply h, rw [←abs_map, ←abs_map, pfunctor.map_eq, pfunctor.map_eq], dsimp [function.comp], congr, ext x, apply ih end theorem fix.rec_unique {α : Type u} (g : F α → α) (h : fix F → α) (hyp : ∀ x, h (fix.mk x) = g (h <$> x)) : fix.rec g = h := begin ext x, apply fix.ind_rec, intros x hyp', rw [hyp, ←hyp', fix.rec_eq] end theorem fix.mk_dest (x : fix F) : fix.mk (fix.dest x) = x := begin change (fix.mk ∘ fix.dest) x = id x, apply fix.ind_rec, intro x, dsimp, rw [fix.dest, fix.rec_eq, id_map, comp_map], intro h, rw h end theorem fix.dest_mk (x : F (fix F)) : fix.dest (fix.mk x) = x := begin unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map], conv { to_rhs, rw ←(id_map x) }, congr, ext x, apply fix.mk_dest end theorem fix.ind (p : fix F → Prop) (h : ∀ x : F (fix F), liftp p x → p (fix.mk x)) : ∀ x, p x := begin apply quot.ind, intro x, induction x with a f ih, change p ⟦⟨a, f⟩⟧, rw [←fix.ind_aux a f], apply h, rw liftp_iff, refine ⟨_, _, rfl, _⟩, apply ih end end qpf /- Construct the final coalebra to a qpf. -/ namespace qpf variables {F : Type u → Type u} [functor F] [q : qpf F] include q open functor (liftp liftr) /-- does recursion on `q.P.M` using `g : α → F α` rather than `g : α → P α` -/ def corecF {α : Type*} (g : α → F α) : α → q.P.M := pfunctor.M_corec (λ x, repr (g x)) theorem corecF_eq {α : Type*} (g : α → F α) (x : α) : pfunctor.M_dest (corecF g x) = corecF g <$> repr (g x) := by rw [corecF, pfunctor.M_dest_corec] /- Equivalence -/ /- A pre-congruence on q.P.M *viewed as an F-coalgebra*. Not necessarily symmetric. -/ def is_precongr (r : q.P.M → q.P.M → Prop) : Prop := ∀ ⦃x y⦄, r x y → abs (quot.mk r <$> pfunctor.M_dest x) = abs (quot.mk r <$> pfunctor.M_dest y) /- The maximal congruence on q.P.M -/ def Mcongr : q.P.M → q.P.M → Prop := λ x y, ∃ r, is_precongr r ∧ r x y def cofix (F : Type u → Type u) [functor F] [q : qpf F]:= quot (@Mcongr F _ q) def cofix.corec {α : Type*} (g : α → F α) : α → cofix F := λ x, quot.mk _ (corecF g x) def cofix.dest : cofix F → F (cofix F) := quot.lift (λ x, quot.mk Mcongr <$> (abs (pfunctor.M_dest x))) begin rintros x y ⟨r, pr, rxy⟩, dsimp, have : ∀ x y, r x y → Mcongr x y, { intros x y h, exact ⟨r, pr, h⟩ }, rw [←quot.factor_mk_eq _ _ this], dsimp, conv { to_lhs, rw [comp_map, ←abs_map, pr rxy, abs_map, ←comp_map] } end theorem cofix.dest_corec {α : Type u} (g : α → F α) (x : α) : cofix.dest (cofix.corec g x) = cofix.corec g <$> g x := begin conv { to_lhs, rw [cofix.dest, cofix.corec] }, dsimp, rw [corecF_eq, abs_map, abs_repr, ←comp_map], reflexivity end private theorem cofix.bisim_aux (r : cofix F → cofix F → Prop) (h' : ∀ x, r x x) (h : ∀ x y, r x y → quot.mk r <$> cofix.dest x = quot.mk r <$> cofix.dest y) : ∀ x y, r x y → x = y := begin intro x, apply quot.induction_on x, clear x, intros x y, apply quot.induction_on y, clear y, intros y rxy, apply quot.sound, let r' := λ x y, r (quot.mk _ x) (quot.mk _ y), have : is_precongr r', { intros a b r'ab, have h₀: quot.mk r <$> quot.mk Mcongr <$> abs (pfunctor.M_dest a) = quot.mk r <$> quot.mk Mcongr <$> abs (pfunctor.M_dest b) := h _ _ r'ab, have h₁ : ∀ u v : q.P.M, Mcongr u v → quot.mk r' u = quot.mk r' v, { intros u v cuv, apply quot.sound, dsimp [r'], rw quot.sound cuv, apply h' }, let f : quot r → quot r' := quot.lift (quot.lift (quot.mk r') h₁) begin intro c, apply quot.induction_on c, clear c, intros c d, apply quot.induction_on d, clear d, intros d rcd, apply quot.sound, apply rcd end, have : f ∘ quot.mk r ∘ quot.mk Mcongr = quot.mk r' := rfl, rw [←this, pfunctor.comp_map _ _ f, pfunctor.comp_map _ _ (quot.mk r), abs_map, abs_map, abs_map, h₀], rw [pfunctor.comp_map _ _ f, pfunctor.comp_map _ _ (quot.mk r), abs_map, abs_map, abs_map] }, refine ⟨r', this, rxy⟩ end theorem cofix.bisim_rel (r : cofix F → cofix F → Prop) (h : ∀ x y, r x y → quot.mk r <$> cofix.dest x = quot.mk r <$> cofix.dest y) : ∀ x y, r x y → x = y := let r' x y := x = y ∨ r x y in begin intros x y rxy, apply cofix.bisim_aux r', { intro x, left, reflexivity }, { intros x y r'xy, cases r'xy, { rw r'xy }, have : ∀ x y, r x y → r' x y := λ x y h, or.inr h, rw ←quot.factor_mk_eq _ _ this, dsimp, rw [@comp_map _ _ q _ _ _ (quot.mk r), @comp_map _ _ q _ _ _ (quot.mk r)], rw h _ _ r'xy }, right, exact rxy end theorem cofix.bisim (r : cofix F → cofix F → Prop) (h : ∀ x y, r x y → liftr r (cofix.dest x) (cofix.dest y)) : ∀ x y, r x y → x = y := begin apply cofix.bisim_rel, intros x y rxy, rcases (liftr_iff r _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩, rw [dxeq, dyeq, ←abs_map, ←abs_map, pfunctor.map_eq, pfunctor.map_eq], congr' 2, ext i, apply quot.sound, apply h' end theorem cofix.bisim' {α : Type*} (Q : α → Prop) (u v : α → cofix F) (h : ∀ x, Q x → ∃ a f f', cofix.dest (u x) = abs ⟨a, f⟩ ∧ cofix.dest (v x) = abs ⟨a, f'⟩ ∧ ∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') : ∀ x, Q x → u x = v x := λ x Qx, let R := λ w z : cofix F, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in cofix.bisim R (λ x y ⟨x', Qx', xeq, yeq⟩, begin rcases h x' Qx' with ⟨a, f, f', ux'eq, vx'eq, h'⟩, rw liftr_iff, refine ⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩, end) _ _ ⟨x, Qx, rfl, rfl⟩ end qpf /- Composition of qpfs. -/ namespace qpf variables {F₂ : Type u → Type u} [functor F₂] [q₂ : qpf F₂] variables {F₁ : Type u → Type u} [functor F₁] [q₁ : qpf F₁] include q₂ q₁ def comp : qpf (functor.comp F₂ F₁) := { P := pfunctor.comp (q₂.P) (q₁.P), abs := λ α, begin dsimp [functor.comp], intro p, exact abs ⟨p.1.1, λ x, abs ⟨p.1.2 x, λ y, p.2 ⟨x, y⟩⟩⟩ end, repr := λ α, begin dsimp [functor.comp], intro y, refine ⟨⟨(repr y).1, λ u, (repr ((repr y).2 u)).1⟩, _⟩, dsimp [pfunctor.comp], intro x, exact (repr ((repr y).2 x.1)).snd x.2 end, abs_repr := λ α, begin abstract { dsimp [functor.comp], intro x, conv { to_rhs, rw ←abs_repr x}, cases h : repr x with a f, dsimp, congr, ext x, cases h' : repr (f x) with b g, dsimp, rw [←h', abs_repr] } end, abs_map := λ α β f, begin abstract { dsimp [functor.comp, pfunctor.comp], intro p, cases p with a g, dsimp, cases a with b h, dsimp, symmetry, transitivity, symmetry, apply abs_map, congr, rw pfunctor.map_eq, dsimp [function.comp], simp [abs_map], split, reflexivity, ext x, rw ←abs_map, reflexivity } end } end qpf /- Quotients. We show that if `F` is a qpf and `G` is a suitable quotient of `F`, then `G` is a qpf. -/ namespace qpf variables {F : Type u → Type u} [functor F] [q : qpf F] variables {G : Type u → Type u} [functor G] variable {FG_abs : Π {α}, F α → G α} variable {FG_repr : Π {α}, G α → F α} def quotient_qpf (FG_abs_repr : Π {α} (x : G α), FG_abs (FG_repr x) = x) (FG_abs_map : ∀ {α β} (f : α → β) (x : F α), FG_abs (f <$> x) = f <$> FG_abs x) : qpf G := { P := q.P, abs := λ {α} p, FG_abs (abs p), repr := λ {α} x, repr (FG_repr x), abs_repr := λ {α} x, by rw [abs_repr, FG_abs_repr], abs_map := λ {α β} f x, by { rw [abs_map, FG_abs_map] } } end qpf /- Support. -/ namespace qpf variables {F : Type u → Type u} [functor F] [q : qpf F] include q open functor (liftp liftr supp) open set theorem mem_supp {α : Type u} (x : F α) (u : α) : u ∈ supp x ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ := begin rw [supp], dsimp, split, { intros h a f haf, have : liftp (λ u, u ∈ f '' univ) x, { rw liftp_iff, refine ⟨a, f, haf.symm, λ i, mem_image_of_mem _ (mem_univ _)⟩ }, exact h this }, intros h p, rw liftp_iff, rintros ⟨a, f, xeq, h'⟩, rcases h a f xeq.symm with ⟨i, _, hi⟩, rw ←hi, apply h' end theorem supp_eq {α : Type u} (x : F α) : supp x = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ } := by ext; apply mem_supp theorem has_good_supp_iff {α : Type u} (x : F α) : (∀ p, liftp p x ↔ ∀ u ∈ supp x, p u) ↔ ∃ a f, abs ⟨a, f⟩ = x ∧ ∀ a' f', abs ⟨a', f'⟩ = x → f '' univ ⊆ f' '' univ := begin split, { intro h, have : liftp (supp x) x, by rw h; intro u; exact id, rw liftp_iff at this, rcases this with ⟨a, f, xeq, h'⟩, refine ⟨a, f, xeq.symm, _⟩, intros a' f' h'', rintros u ⟨i, _, hfi⟩, have : u ∈ supp x, by rw ←hfi; apply h', exact (mem_supp x u).mp this _ _ h'' }, rintros ⟨a, f, xeq, h⟩ p, rw liftp_iff, split, { rintros ⟨a', f', xeq', h'⟩ u usuppx, rcases (mem_supp x u).mp usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩, rw ←f'ieq, apply h' }, intro h', refine ⟨a, f, xeq.symm, _⟩, intro i, apply h', rw mem_supp, intros a' f' xeq', apply h a' f' xeq', apply mem_image_of_mem _ (mem_univ _) end variable (q) def is_uniform : Prop := ∀ ⦃α : Type u⦄ (a a' : q.P.A) (f : q.P.B a → α) (f' : q.P.B a' → α), abs ⟨a, f⟩ = abs ⟨a', f'⟩ → f '' univ = f' '' univ variable [q] theorem supp_eq_of_is_uniform (h : q.is_uniform) {α : Type u} (a : q.P.A) (f : q.P.B a → α) : supp (abs ⟨a, f⟩) = f '' univ := begin ext u, rw [mem_supp], split, { intro h', apply h' _ _ rfl }, intros h' a' f' e, rw [←h _ _ _ _ e.symm], apply h' end theorem liftp_iff_of_is_uniform (h : q.is_uniform) {α : Type u} (x : F α) (p : α → Prop) : liftp p x ↔ ∀ u ∈ supp x, p u := begin rw [liftp_iff, ←abs_repr x], cases repr x with a f, split, { rintros ⟨a', f', abseq, hf⟩ u, rw [supp_eq_of_is_uniform h, h _ _ _ _ abseq], rintros ⟨i, _, hi⟩, rw ←hi, apply hf }, intro h', refine ⟨a, f, rfl, λ i, h' _ _⟩, rw supp_eq_of_is_uniform h, exact ⟨i, mem_univ i, rfl⟩ end theorem supp_map (h : q.is_uniform) {α β : Type u} (g : α → β) (x : F α) : supp (g <$> x) = g '' supp x := begin rw ←abs_repr x, cases repr x with a f, rw [←abs_map, pfunctor.map_eq], rw [supp_eq_of_is_uniform h, supp_eq_of_is_uniform h, image_comp] end end qpf
5e18605b18c5469dd8a399b2a45239a74afded1b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_topology/nerve.lean
09c8373d1a4ba7901e2d6f1b24ee03002956aa74
[ "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,446
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.simplicial_set /-! # The nerve of a category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides the definition of the nerve of a category `C`, which is a simplicial set `nerve C` (see [goerss-jardine-2009], Example I.1.4). ## References * [Paul G. Goerss, John F. Jardine, *Simplical Homotopy Theory*][goerss-jardine-2009] -/ open category_theory.category universes v u namespace category_theory /-- The nerve of a category -/ @[simps] def nerve (C : Type u) [category.{v} C] : sSet.{max u v} := { obj := λ Δ, (simplex_category.to_Cat.obj Δ.unop) ⥤ C, map := λ Δ₁ Δ₂ f x, simplex_category.to_Cat.map f.unop ⋙ x, map_id' := λ Δ, begin rw [unop_id, functor.map_id], ext x, apply functor.id_comp, end, } instance {C : Type*} [category C] {Δ : simplex_categoryᵒᵖ} : category ((nerve C).obj Δ) := (infer_instance : category ((simplex_category.to_Cat.obj Δ.unop) ⥤ C)) /-- The nerve of a category, as a functor `Cat ⥤ sSet` -/ @[simps] def nerve_functor : Cat ⥤ sSet := { obj := λ C, nerve C, map := λ C C' F, { app := λ Δ x, x ⋙ F, }, map_id' := λ C, begin ext Δ x, apply functor.comp_id, end, } end category_theory
ca4d461c053bbc9d96c7f014c42ee9287fa18b67
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/sylow_auto.lean
24a0408d4cdaf86d0501c4a87a07c1278b1cdd45
[]
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,612
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.group_action.default import Mathlib.group_theory.quotient_group import Mathlib.group_theory.order_of_element import Mathlib.data.zmod.basic import Mathlib.data.fintype.card import Mathlib.data.list.rotate import Mathlib.PostPort universes u v u_1 namespace Mathlib namespace mul_action theorem mem_fixed_points_iff_card_orbit_eq_one {G : Type u} {α : Type v} [group G] [mul_action G α] {a : α} [fintype ↥(orbit G a)] : a ∈ fixed_points G α ↔ fintype.card ↥(orbit G a) = 1 := sorry theorem card_modeq_card_fixed_points {G : Type u} {α : Type v} [group G] [mul_action G α] [fintype α] [fintype G] [fintype ↥(fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact (nat.prime p)] (h : fintype.card G = p ^ n) : nat.modeq p (fintype.card α) (fintype.card ↥(fixed_points G α)) := sorry end mul_action theorem quotient_group.card_preimage_mk {G : Type u} [group G] [fintype G] (s : subgroup G) (t : set (quotient_group.quotient s)) : fintype.card ↥(quotient_group.mk ⁻¹' t) = fintype.card ↥s * fintype.card ↥t := sorry namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one {G : Type u} [group G] (n : ℕ) (v : vector G n) : vector G (n + 1) := list.prod (vector.to_list v)⁻¹::ᵥv theorem mk_vector_prod_eq_one_injective {G : Type u} [group G] (n : ℕ) : function.injective (mk_vector_prod_eq_one n) := sorry /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type u_1) [group G] (n : ℕ) : set (vector G n) := set_of fun (v : vector G n) => list.prod (vector.to_list v) = 1 theorem mem_vectors_prod_eq_one {G : Type u} [group G] {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ list.prod (vector.to_list v) = 1 := iff.rfl theorem mem_vectors_prod_eq_one_iff {G : Type u} [group G] {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (mk_vector_prod_eq_one n) := sorry /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type u_1) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : ↥(vectors_prod_eq_one G n)) : ↥(vectors_prod_eq_one G n) := { val := { val := list.rotate (vector.to_list (subtype.val v)) (zmod.val m), property := sorry }, property := sorry } protected instance rotate_vectors_prod_eq_one.mul_action {G : Type u} [group G] (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) ↥(vectors_prod_eq_one G n) := mul_action.mk sorry sorry theorem one_mem_vectors_prod_eq_one {G : Type u} [group G] (n : ℕ) : vector.repeat 1 n ∈ vectors_prod_eq_one G n := sorry theorem one_mem_fixed_points_rotate {G : Type u} [group G] (n : ℕ) [fact (0 < n)] : { val := vector.repeat 1 n, property := one_mem_vectors_prod_eq_one n } ∈ mul_action.fixed_points (multiplicative (zmod n)) ↥(vectors_prod_eq_one G n) := sorry /-- Cauchy's theorem -/ theorem exists_prime_order_of_dvd_card {G : Type u} [group G] [fintype G] (p : ℕ) [hp : fact (nat.prime p)] (hdvd : p ∣ fintype.card G) : ∃ (x : G), order_of x = p := sorry theorem mem_fixed_points_mul_left_cosets_iff_mem_normalizer {G : Type u} [group G] {H : subgroup G} [fintype ↥↑H] {x : G} : ↑x ∈ mul_action.fixed_points (↥H) (quotient_group.quotient H) ↔ x ∈ subgroup.normalizer H := sorry def fixed_points_mul_left_cosets_equiv_quotient {G : Type u} [group G] (H : subgroup G) [fintype ↥↑H] : ↥(mul_action.fixed_points (↥H) (quotient_group.quotient H)) ≃ quotient_group.quotient (subgroup.comap (subgroup.subtype (subgroup.normalizer H)) H) := equiv.subtype_quotient_equiv_quotient_subtype (↑(subgroup.normalizer H)) (mul_action.fixed_points (↥H) (quotient (id (setoid.mk (fun (x y : G) => x⁻¹ * y ∈ H) (quotient_group.left_rel._proof_1 H))))) sorry sorry theorem exists_subgroup_card_pow_prime {G : Type u} [group G] [fintype G] (p : ℕ) {n : ℕ} [hp : fact (nat.prime p)] (hdvd : p ^ n ∣ fintype.card G) : ∃ (H : subgroup G), fintype.card ↥H = p ^ n := sorry end Mathlib