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
404b229063aebe7666acc907f5f9f2a5421036a8
3b15c7b0b62d8ada1399c112ad88a529e6bfa115
/src/Init/Data/Nat/Basic.lean
e49a40a613a2dee4bf6ba5807da930c61e646e20
[ "Apache-2.0" ]
permissive
stephenbrady/lean4
74bf5cae8a433e9c815708ce96c9e54a5caf2115
b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9
refs/heads/master
1,692,621,473,161
1,634,308,743,000
1,634,310,749,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,574
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import Init.SimpLemmas universe u namespace Nat @[specialize] def foldAux {α : Type u} (f : Nat → α → α) (s : Nat) : Nat → α → α | 0, a => a | succ n, a => foldAux f s n (f (s - (succ n)) a) @[inline] def fold {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := foldAux f n n init @[inline] def foldRev {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f n a) loop n init @[specialize] def anyAux (f : Nat → Bool) (s : Nat) : Nat → Bool | 0 => false | succ n => f (s - (succ n)) || anyAux f s n /- `any f n = true` iff there is `i in [0, n-1]` s.t. `f i = true` -/ @[inline] def any (f : Nat → Bool) (n : Nat) : Bool := anyAux f n n @[inline] def all (f : Nat → Bool) (n : Nat) : Bool := !any (fun i => !f i) n @[inline] def repeat {α : Type u} (f : α → α) (n : Nat) (a : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f a) loop n a /- Nat.add theorems -/ @[simp] theorem zero_eq : Nat.zero = 0 := rfl @[simp] theorem add_eq : Nat.add x y = x + y := rfl @[simp] theorem lt_eq : Nat.lt x y = (x < y) := rfl @[simp] protected theorem zero_add : ∀ (n : Nat), 0 + n = n | 0 => rfl | n+1 => congrArg succ (Nat.zero_add n) theorem succ_add : ∀ (n m : Nat), (succ n) + m = succ (n + m) | n, 0 => rfl | n, m+1 => congrArg succ (succ_add n m) theorem add_succ (n m : Nat) : n + succ m = succ (n + m) := rfl theorem add_one (n : Nat) : n + 1 = succ n := rfl theorem succ_eq_add_one (n : Nat) : succ n = n + 1 := rfl protected theorem add_comm : ∀ (n m : Nat), n + m = m + n | n, 0 => Eq.symm (Nat.zero_add n) | n, m+1 => by have : succ (n + m) = succ (m + n) := by apply congrArg; apply Nat.add_comm rw [succ_add m n] apply this protected theorem add_assoc : ∀ (n m k : Nat), (n + m) + k = n + (m + k) | n, m, 0 => rfl | n, m, succ k => congrArg succ (Nat.add_assoc n m k) protected theorem add_left_comm (n m k : Nat) : n + (m + k) = m + (n + k) := by rw [← Nat.add_assoc, Nat.add_comm n m, Nat.add_assoc] protected theorem add_right_comm (n m k : Nat) : (n + m) + k = (n + k) + m := by rw [Nat.add_assoc, Nat.add_comm m k, ← Nat.add_assoc] protected theorem add_left_cancel {n m k : Nat} : n + m = n + k → m = k := by induction n with | zero => simp; intros; assumption | succ n ih => simp [succ_add]; intro h; apply ih h protected theorem add_right_cancel {n m k : Nat} (h : n + m = k + m) : n = k := by rw [Nat.add_comm n m, Nat.add_comm k m] at h apply Nat.add_left_cancel h /- Nat.mul theorems -/ @[simp] protected theorem mul_zero (n : Nat) : n * 0 = 0 := rfl theorem mul_succ (n m : Nat) : n * succ m = n * m + n := rfl @[simp] protected theorem zero_mul : ∀ (n : Nat), 0 * n = 0 | 0 => rfl | succ n => mul_succ 0 n ▸ (Nat.zero_mul n).symm ▸ rfl theorem succ_mul (n m : Nat) : (succ n) * m = (n * m) + m := by induction m with | zero => rfl | succ m ih => rw [mul_succ, add_succ, ih, mul_succ, add_succ, Nat.add_right_comm] protected theorem mul_comm : ∀ (n m : Nat), n * m = m * n | n, 0 => (Nat.zero_mul n).symm ▸ (Nat.mul_zero n).symm ▸ rfl | n, succ m => (mul_succ n m).symm ▸ (succ_mul m n).symm ▸ (Nat.mul_comm n m).symm ▸ rfl @[simp] protected theorem mul_one : ∀ (n : Nat), n * 1 = n := Nat.zero_add @[simp] protected theorem one_mul (n : Nat) : 1 * n = n := Nat.mul_comm n 1 ▸ Nat.mul_one n protected theorem left_distrib (n m k : Nat) : n * (m + k) = n * m + n * k := by induction n generalizing m k with | zero => repeat rw [Nat.zero_mul] | succ n ih => simp [succ_mul, ih]; rw [Nat.add_assoc, Nat.add_assoc (n*m)]; apply congrArg; apply Nat.add_left_comm protected theorem right_distrib (n m k : Nat) : (n + m) * k = n * k + m * k := have h₁ : (n + m) * k = k * (n + m) := Nat.mul_comm .. have h₂ : k * (n + m) = k * n + k * m := Nat.left_distrib .. have h₃ : k * n + k * m = n * k + k * m := Nat.mul_comm n k ▸ rfl have h₄ : n * k + k * m = n * k + m * k := Nat.mul_comm m k ▸ rfl ((h₁.trans h₂).trans h₃).trans h₄ protected theorem mul_add (n m k : Nat) : n * (m + k) = n * m + n * k := Nat.left_distrib n m k protected theorem add_mul (n m k : Nat) : (n + m) * k = n * k + m * k := Nat.right_distrib n m k protected theorem mul_assoc : ∀ (n m k : Nat), (n * m) * k = n * (m * k) | n, m, 0 => rfl | n, m, succ k => have h₁ : n * m * succ k = n * m * (k + 1) := rfl have h₂ : n * m * (k + 1) = (n * m * k) + n * m * 1 := Nat.left_distrib .. have h₃ : (n * m * k) + n * m * 1 = (n * m * k) + n * m := by rw [Nat.mul_one (n*m)] have h₄ : (n * m * k) + n * m = (n * (m * k)) + n * m := by rw [Nat.mul_assoc n m k] have h₅ : (n * (m * k)) + n * m = n * (m * k + m) := (Nat.left_distrib n (m*k) m).symm have h₆ : n * (m * k + m) = n * (m * succ k) := Nat.mul_succ m k ▸ rfl ((((h₁.trans h₂).trans h₃).trans h₄).trans h₅).trans h₆ protected theorem mul_left_comm (n m k : Nat) : n * (m * k) = m * (n * k) := by rw [← Nat.mul_assoc, Nat.mul_comm n m, Nat.mul_assoc] /- Inequalities -/ theorem succ_lt_succ {n m : Nat} : n < m → succ n < succ m := succ_le_succ theorem lt_succ_of_le {n m : Nat} : n ≤ m → n < succ m := succ_le_succ @[simp] protected theorem sub_zero (n : Nat) : n - 0 = n := rfl theorem succ_sub_succ_eq_sub (n m : Nat) : succ n - succ m = n - m := by induction m with | zero => exact rfl | succ m ih => apply congrArg pred ih theorem pred_le : ∀ (n : Nat), pred n ≤ n | zero => Nat.le.refl | succ n => le_succ _ theorem pred_lt : ∀ {n : Nat}, n ≠ 0 → pred n < n | zero, h => absurd rfl h | succ n, h => lt_succ_of_le (Nat.le_refl _) theorem sub_le (n m : Nat) : n - m ≤ n := by induction m with | zero => exact Nat.le_refl (n - 0) | succ m ih => apply Nat.le_trans (pred_le (n - m)) ih theorem sub_lt : ∀ {n m : Nat}, 0 < n → 0 < m → n - m < n | 0, m, h1, h2 => absurd h1 (Nat.lt_irrefl 0) | n+1, 0, h1, h2 => absurd h2 (Nat.lt_irrefl 0) | n+1, m+1, h1, h2 => Eq.symm (succ_sub_succ_eq_sub n m) ▸ show n - m < succ n from lt_succ_of_le (sub_le n m) theorem sub_succ (n m : Nat) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : Nat) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : Nat), n - n = 0 | 0 => by rw [Nat.sub_zero] | (succ n) => by rw [succ_sub_succ, Nat.sub_self n] protected theorem lt_of_lt_of_le {n m k : Nat} : n < m → m ≤ k → n < k := Nat.le_trans protected theorem lt_of_lt_of_eq {n m k : Nat} : n < m → m = k → n < k := fun h₁ h₂ => h₂ ▸ h₁ instance : Trans (. < . : Nat → Nat → Prop) (. < . : Nat → Nat → Prop) (. < . : Nat → Nat → Prop) where trans := Nat.lt_trans instance : Trans (. ≤ . : Nat → Nat → Prop) (. ≤ . : Nat → Nat → Prop) (. ≤ . : Nat → Nat → Prop) where trans := Nat.le_trans instance : Trans (. < . : Nat → Nat → Prop) (. ≤ . : Nat → Nat → Prop) (. < . : Nat → Nat → Prop) where trans := Nat.lt_of_lt_of_le instance : Trans (. ≤ . : Nat → Nat → Prop) (. < . : Nat → Nat → Prop) (. < . : Nat → Nat → Prop) where trans := Nat.lt_of_le_of_lt protected theorem le_of_eq {n m : Nat} (p : n = m) : n ≤ m := p ▸ Nat.le_refl n theorem le_of_succ_le {n m : Nat} (h : succ n ≤ m) : n ≤ m := Nat.le_trans (le_succ n) h protected theorem le_of_lt {n m : Nat} (h : n < m) : n ≤ m := le_of_succ_le h def lt.step {n m : Nat} : n < m → n < succ m := le_step theorem eq_zero_or_pos : ∀ (n : Nat), n = 0 ∨ n > 0 | 0 => Or.inl rfl | n+1 => Or.inr (succ_pos _) def lt.base (n : Nat) : n < succ n := Nat.le_refl (succ n) theorem lt_succ_self (n : Nat) : n < succ n := lt.base n protected theorem le_total (m n : Nat) : m ≤ n ∨ n ≤ m := match Nat.lt_or_ge m n with | Or.inl h => Or.inl (Nat.le_of_lt h) | Or.inr h => Or.inr h protected theorem lt_of_le_and_ne {m n : Nat} (h₁ : m ≤ n) (h₂ : m ≠ n) : m < n := match Nat.eq_or_lt_of_le h₁ with | Or.inl h => absurd h h₂ | Or.inr h => h theorem eq_zero_of_le_zero {n : Nat} (h : n ≤ 0) : n = 0 := Nat.le_antisymm h (zero_le _) theorem lt_of_succ_lt {n m : Nat} : succ n < m → n < m := le_of_succ_le theorem lt_of_succ_lt_succ {n m : Nat} : succ n < succ m → n < m := le_of_succ_le_succ theorem lt_of_succ_le {n m : Nat} (h : succ n ≤ m) : n < m := h theorem succ_le_of_lt {n m : Nat} (h : n < m) : succ n ≤ m := h theorem lt_or_eq_or_le_succ {m n : Nat} (h : m ≤ succ n) : m ≤ n ∨ m = succ n := Decidable.byCases (fun (h' : m = succ n) => Or.inr h') (fun (h' : m ≠ succ n) => have : m < succ n := Nat.lt_of_le_and_ne h h' have : succ m ≤ succ n := succ_le_of_lt this Or.inl (le_of_succ_le_succ this)) theorem le_add_right : ∀ (n k : Nat), n ≤ n + k | n, 0 => Nat.le_refl n | n, k+1 => le_succ_of_le (le_add_right n k) theorem le_add_left (n m : Nat): n ≤ m + n := Nat.add_comm n m ▸ le_add_right n m theorem le.dest : ∀ {n m : Nat}, n ≤ m → Exists (fun k => n + k = m) | zero, zero, h => ⟨0, rfl⟩ | zero, succ n, h => ⟨succ n, Nat.add_comm 0 (succ n) ▸ rfl⟩ | succ n, zero, h => absurd h (not_succ_le_zero _) | succ n, succ m, h => have : n ≤ m := Nat.le_of_succ_le_succ h have : Exists (fun k => n + k = m) := dest this match this with | ⟨k, h⟩ => ⟨k, show succ n + k = succ m from ((succ_add n k).symm ▸ h ▸ rfl)⟩ theorem le.intro {n m k : Nat} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k protected theorem not_le_of_gt {n m : Nat} (h : n > m) : ¬ n ≤ m := fun h₁ => match Nat.lt_or_ge n m with | Or.inl h₂ => absurd (Nat.lt_trans h h₂) (Nat.lt_irrefl _) | Or.inr h₂ => have Heq : n = m := Nat.le_antisymm h₁ h₂ absurd (@Eq.subst _ _ _ _ Heq h) (Nat.lt_irrefl m) theorem gt_of_not_le {n m : Nat} (h : ¬ n ≤ m) : n > m := match Nat.lt_or_ge m n with | Or.inl h₁ => h₁ | Or.inr h₁ => absurd h₁ h protected theorem add_le_add_left {n m : Nat} (h : n ≤ m) (k : Nat) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ => have h₁ : k + n + w = k + (n + w) := Nat.add_assoc .. have h₂ : k + (n + w) = k + m := congrArg _ hw le.intro <| h₁.trans h₂ protected theorem add_le_add_right {n m : Nat} (h : n ≤ m) (k : Nat) : n + k ≤ m + k := by rw [Nat.add_comm n k, Nat.add_comm m k] apply Nat.add_le_add_left assumption protected theorem add_lt_add_left {n m : Nat} (h : n < m) (k : Nat) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ Nat.add_le_add_left (succ_le_of_lt h) k) protected theorem add_lt_add_right {n m : Nat} (h : n < m) (k : Nat) : n + k < m + k := Nat.add_comm k m ▸ Nat.add_comm k n ▸ Nat.add_lt_add_left h k protected theorem zero_lt_one : 0 < (1:Nat) := zero_lt_succ 0 theorem add_le_add {a b c d : Nat} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := Nat.le_trans (Nat.add_le_add_right h₁ c) (Nat.add_le_add_left h₂ b) theorem add_lt_add {a b c d : Nat} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := Nat.lt_trans (Nat.add_lt_add_right h₁ c) (Nat.add_lt_add_left h₂ b) /- Basic theorems for comparing numerals -/ theorem ctor_eq_zero : Nat.zero = 0 := rfl protected theorem one_ne_zero : 1 ≠ (0 : Nat) := fun h => Nat.noConfusion h protected theorem zero_ne_one : 0 ≠ (1 : Nat) := fun h => Nat.noConfusion h theorem succ_ne_zero (n : Nat) : succ n ≠ 0 := fun h => Nat.noConfusion h /- mul + order -/ theorem mul_le_mul_left {n m : Nat} (k : Nat) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ => have : k * n + k * l = k * m := Nat.left_distrib k n l ▸ hl.symm ▸ rfl le.intro this theorem mul_le_mul_right {n m : Nat} (k : Nat) (h : n ≤ m) : n * k ≤ m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ mul_le_mul_left k h protected theorem mul_le_mul {n₁ m₁ n₂ m₂ : Nat} (h₁ : n₁ ≤ n₂) (h₂ : m₁ ≤ m₂) : n₁ * m₁ ≤ n₂ * m₂ := Nat.le_trans (mul_le_mul_right _ h₁) (mul_le_mul_left _ h₂) protected theorem mul_lt_mul_of_pos_left {n m k : Nat} (h : n < m) (hk : k > 0) : k * n < k * m := Nat.lt_of_lt_of_le (Nat.add_lt_add_left hk _) (Nat.mul_succ k n ▸ Nat.mul_le_mul_left k (succ_le_of_lt h)) protected theorem mul_lt_mul_of_pos_right {n m k : Nat} (h : n < m) (hk : k > 0) : n * k < m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ Nat.mul_lt_mul_of_pos_left h hk protected theorem mul_pos {n m : Nat} (ha : n > 0) (hb : m > 0) : n * m > 0 := have h : 0 * m < n * m := Nat.mul_lt_mul_of_pos_right ha hb Nat.zero_mul m ▸ h /- power -/ theorem pow_succ (n m : Nat) : n^(succ m) = n^m * n := rfl theorem pow_zero (n : Nat) : n^0 = 1 := rfl theorem pow_le_pow_of_le_left {n m : Nat} (h : n ≤ m) : ∀ (i : Nat), n^i ≤ m^i | 0 => Nat.le_refl _ | succ i => Nat.mul_le_mul (pow_le_pow_of_le_left h i) h theorem pow_le_pow_of_le_right {n : Nat} (hx : n > 0) {i : Nat} : ∀ {j}, i ≤ j → n^i ≤ n^j | 0, h => have : i = 0 := eq_zero_of_le_zero h this.symm ▸ Nat.le_refl _ | succ j, h => match lt_or_eq_or_le_succ h with | Or.inl h => show n^i ≤ n^j * n from have : n^i * 1 ≤ n^j * n := Nat.mul_le_mul (pow_le_pow_of_le_right hx h) hx Nat.mul_one (n^i) ▸ this | Or.inr h => h.symm ▸ Nat.le_refl _ theorem pos_pow_of_pos {n : Nat} (m : Nat) (h : 0 < n) : 0 < n^m := pow_le_pow_of_le_right h (Nat.zero_le _) /- min/max -/ protected def min (n m : Nat) : Nat := if n ≤ m then n else m protected def max (n m : Nat) : Nat := if n ≤ m then m else n end Nat namespace Prod @[inline] def foldI {α : Type u} (f : Nat → α → α) (i : Nat × Nat) (a : α) : α := Nat.foldAux f i.2 (i.2 - i.1) a @[inline] def anyI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux f i.2 (i.2 - i.1) @[inline] def allI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux (fun a => !f a) i.2 (i.2 - i.1) end Prod
934e1e3cf4308f17ef8eb51186a882f93401f9a4
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Server/Rpc/RequestHandling.lean
75614e7e3c38b7cd5e8333e3d949a5a075ffc248
[ "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
5,740
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Lsp.Extra import Lean.Server.Requests import Lean.Server.Rpc.Basic namespace Lean.Server private structure RpcProcedure where wrapper : (sessionId : UInt64) → Json → RequestM (RequestTask Json) deriving Inhabited /- We store the builtin RPC handlers in a Ref and users' handlers in an extension. This ensures that users don't need to import core Lean modules to make builtin handlers work, but also that they *can* easily create custom handlers and use them in the same file. -/ builtin_initialize builtinRpcProcedures : IO.Ref (PHashMap Name RpcProcedure) ← IO.mkRef {} builtin_initialize userRpcProcedures : MapDeclarationExtension Name ← mkMapDeclarationExtension private unsafe def evalRpcProcedureUnsafe (env : Environment) (opts : Options) (procName : Name) : Except String RpcProcedure := env.evalConstCheck RpcProcedure opts ``RpcProcedure procName @[implemented_by evalRpcProcedureUnsafe] opaque evalRpcProcedure (env : Environment) (opts : Options) (procName : Name) : Except String RpcProcedure open RequestM in def handleRpcCall (p : Lsp.RpcCallParams) : RequestM (RequestTask Json) := do -- The imports are finished at this point, because the handleRequest function -- waits for the header. (Therefore the built-in RPC procedures won't change -- if we wait for further snapshots.) if let some proc := (← builtinRpcProcedures.get).find? p.method then proc.wrapper p.sessionId p.params else let doc ← readDoc let text := doc.meta.text let callPos := text.lspPosToUtf8Pos p.position let throwNotFound := throwThe RequestError { code := .methodNotFound message := s!"No RPC method '{p.method}' found"} bindWaitFindSnap doc (notFoundX := throwNotFound) (fun s => s.endPos >= callPos || (userRpcProcedures.find? s.env p.method).isSome) fun snap => do if let some procName := userRpcProcedures.find? snap.env p.method then let options := snap.cmdState.scopes.head!.opts match evalRpcProcedure snap.env options procName with | .ok x => x.wrapper p.sessionId p.params | .error e => throwThe RequestError { code := .internalError message := s!"Failed to evaluate RPC constant '{procName}': {e}" } else throwNotFound builtin_initialize registerLspRequestHandler "$/lean/rpc/call" Lsp.RpcCallParams Json handleRpcCall def wrapRpcProcedure (method : Name) paramType respType [RpcEncodable paramType] [RpcEncodable respType] (handler : paramType → RequestM (RequestTask respType)) : RpcProcedure := ⟨fun seshId j => do let rc ← read let some seshRef := rc.rpcSessions.find? seshId | throwThe RequestError { code := JsonRpc.ErrorCode.rpcNeedsReconnect message := s!"Outdated RPC session" } let t ← RequestM.asTask do match rpcDecode j (← seshRef.get).objects with | Except.ok v => return v | Except.error e => throwThe RequestError { code := JsonRpc.ErrorCode.invalidParams message := s!"Cannot decode params in RPC call '{method}({j.compress})'\n{e}" } let t ← RequestM.bindTask t fun | Except.error e => throw e | Except.ok ps => handler ps RequestM.mapTask t fun | Except.error e => throw e | Except.ok ret => seshRef.modifyGet fun st => rpcEncode ret st.objects |>.map id ({st with objects := ·})⟩ def registerBuiltinRpcProcedure (method : Name) paramType respType [RpcEncodable paramType] [RpcEncodable respType] (handler : paramType → RequestM (RequestTask respType)) : IO Unit := do let errMsg := s!"Failed to register builtin RPC call handler for '{method}'" unless (← IO.initializing) do throw <| IO.userError s!"{errMsg}: only possible during initialization" if (←builtinRpcProcedures.get).contains method then throw <| IO.userError s!"{errMsg}: already registered" let proc := wrapRpcProcedure method paramType respType handler builtinRpcProcedures.modify fun ps => ps.insert method proc open Lean Elab Command Term Meta in def registerRpcProcedure (method : Name) : CoreM Unit := do let env ← getEnv let errMsg := "Failed to register RPC call handler for '{method}'" if (←builtinRpcProcedures.get).contains method then throwError s!"{errMsg}: already registered (builtin)" if userRpcProcedures.contains env method then throwError s!"{errMsg}: already registered" let wrappedName := method ++ `_rpc_wrapped let procT := mkConst ``RpcProcedure let proc ← MetaM.run' <| TermElabM.run' <| withoutErrToSorry do let stx ← ``(wrapRpcProcedure $(quote method) _ _ $(mkIdent method)) let c ← Lean.Elab.Term.elabTerm stx procT instantiateMVars c addAndCompile <| Declaration.defnDecl { name := wrappedName type := procT value := proc safety := DefinitionSafety.safe levelParams := [] hints := ReducibilityHints.opaque } setEnv <| userRpcProcedures.insert (← getEnv) method wrappedName builtin_initialize registerBuiltinAttribute { name := `server_rpc_method descr := "Marks a function as a Lean server RPC method. Shorthand for `registerRpcProcedure`. The function must have type `α → RequestM (RequestTask β)` with `[RpcEncodable α]` and `[RpcEncodable β]`." applicationTime := AttributeApplicationTime.afterCompilation add := fun decl _ _ => registerRpcProcedure decl } end Lean.Server
8441b1b5f9e9f913507f87e695e522bae20817e5
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Meta/Exception.lean
ee16a3496ede498a1ea00ced0f803e38531e7792
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,933
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Environment import Init.Lean.MetavarContext import Init.Lean.Message import Init.Lean.Util.PPGoal namespace Lean namespace Meta abbrev ExceptionContext := MessageDataContext inductive Bug | overwritingExprMVar (mvarId : Name) inductive Exception | unknownConst (constName : Name) (ctx : ExceptionContext) | unknownFVar (fvarId : FVarId) (ctx : ExceptionContext) | unknownExprMVar (mvarId : MVarId) (ctx : ExceptionContext) | unknownLevelMVar (mvarId : MVarId) (ctx : ExceptionContext) | unexpectedBVar (bvarIdx : Nat) | functionExpected (f a : Expr) (ctx : ExceptionContext) | typeExpected (type : Expr) (ctx : ExceptionContext) | incorrectNumOfLevels (constName : Name) (constLvls : List Level) (ctx : ExceptionContext) | invalidProjection (structName : Name) (idx : Nat) (s : Expr) (ctx : ExceptionContext) | revertFailure (toRevert : Array Expr) (decl : LocalDecl) (ctx : ExceptionContext) | readOnlyMVar (mvarId : MVarId) (ctx : ExceptionContext) | isLevelDefEqStuck (u v : Level) (ctx : ExceptionContext) | isExprDefEqStuck (t s : Expr) (ctx : ExceptionContext) | letTypeMismatch (fvarId : FVarId) (ctx : ExceptionContext) | appTypeMismatch (f a : Expr) (ctx : ExceptionContext) | notInstance (e : Expr) (ctx : ExceptionContext) | appBuilder (op : Name) (msg : String) (args : Array Expr) (ctx : ExceptionContext) | synthInstance (inst : Expr) (ctx : ExceptionContext) | tactic (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ctx : ExceptionContext) | generalizeTelescope (es : Array Expr) (ctx : ExceptionContext) | kernel (ex : KernelException) (opts : Options) | bug (b : Bug) (ctx : ExceptionContext) | other (msg : String) namespace Exception instance : Inhabited Exception := ⟨other ""⟩ -- TODO: improve, use (to be implemented) pretty printer def toStr : Exception → String | unknownConst c _ => "unknown constant '" ++ toString c ++ "'" | unknownFVar fvarId _ => "unknown free variable '" ++ toString fvarId ++ "'" | unknownExprMVar mvarId _ => "unknown metavariable '" ++ toString mvarId ++ "'" | unknownLevelMVar mvarId _ => "unknown universe level metavariable '" ++ toString mvarId ++ "'" | unexpectedBVar bvarIdx => "unexpected loose bound variable #" ++ toString bvarIdx | functionExpected fType args _ => "function expected" | typeExpected _ _ => "type expected" | incorrectNumOfLevels c lvls _ => "incorrect number of universe levels for '" ++ toString c ++ "' " ++ toString lvls | invalidProjection _ _ _ _ => "invalid projection" | revertFailure _ _ _ => "revert failure" | readOnlyMVar _ _ => "try to assign read only metavariable" | isLevelDefEqStuck _ _ _ => "isDefEq is stuck" | isExprDefEqStuck _ _ _ => "isDefEq is stuck" | letTypeMismatch _ _ => "type mismatch at let-expression" | appTypeMismatch _ _ _ => "application type mismatch" | notInstance _ _ => "type class instance expected" | appBuilder _ _ _ _ => "application builder failure" | synthInstance _ _ => "type class instance synthesis failed" | tactic tacName _ _ _ => "tactic '" ++ toString tacName ++ "' failed" | generalizeTelescope _ _ => "generalize telescope" | kernel _ _ => "kernel exception" | bug _ _ => "bug" | other s => s instance : HasToString Exception := ⟨toStr⟩ def mkCtx (ctx : ExceptionContext) (m : MessageData) : MessageData := MessageData.withContext ctx m /-- Generate trace message that is suitable for tracing crawlers -/ def toTraceMessageData : Exception → MessageData | unknownConst c ctx => mkCtx ctx $ `unknownConst ++ " " ++ c | unknownFVar fvarId ctx => mkCtx ctx $ `unknownFVar ++ " " ++ fvarId | unknownExprMVar mvarId ctx => mkCtx ctx $ `unknownExprMVar ++ " " ++ mkMVar mvarId | unknownLevelMVar mvarId ctx => mkCtx ctx $ `unknownLevelMVar ++ " " ++ mkLevelMVar mvarId | unexpectedBVar bvarIdx => `unexpectedBVar ++ " " ++ mkBVar bvarIdx | functionExpected f a ctx => mkCtx ctx $ `functionExpected ++ " " ++ mkApp f a | typeExpected t ctx => mkCtx ctx $ `typeExpected ++ " " ++ t | incorrectNumOfLevels c lvls ctx => mkCtx ctx $ `incorrectNumOfLevels ++ " " ++ mkConst c lvls | invalidProjection s i e ctx => mkCtx ctx $ `invalidProjection ++ " " ++ mkProj s i e | revertFailure xs decl ctx => mkCtx ctx $ `revertFailure -- TODO improve | readOnlyMVar mvarId ctx => mkCtx ctx $ `readOnlyMVar ++ " " ++ mkMVar mvarId | isLevelDefEqStuck u v ctx => mkCtx ctx $ `isLevelDefEqStuck ++ " " ++ u ++ " =?= " ++ v | isExprDefEqStuck t s ctx => mkCtx ctx $ `isExprDefEqStuck ++ " " ++ t ++ " =?= " ++ s | letTypeMismatch fvarId ctx => mkCtx ctx $ `letTypeMismatch ++ " " ++ mkFVar fvarId | appTypeMismatch f a ctx => mkCtx ctx $ `appTypeMismatch ++ " " ++ mkApp f a | notInstance i ctx => mkCtx ctx $ `notInstance ++ " " ++ i | appBuilder op msg args ctx => mkCtx ctx $ `appBuilder ++ " " ++ op ++ " " ++ args ++ " " ++ msg | synthInstance inst ctx => mkCtx ctx $ `synthInstance ++ " " ++ inst | tactic tacName mvarId msg ctx => mkCtx ctx $ `tacticFailure ++ " " ++ tacName ++ " " ++ msg | generalizeTelescope es ctx => mkCtx ctx $ `generalizeTelescope ++ " " ++ es | kernel ex opts => ex.toMessageData opts | bug _ _ => "internal bug" -- TODO improve | other s => s end Exception end Meta end Lean
510e9763d40a7f0b14d09f12d5db309a45f8705b
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world04/level08.lean
f5bdab3067dbc510a5d983f5f1cb0ea6de274b85
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
208
lean
lemma add_squared (a b : mynat) : (a + b) ^ (2 : mynat) = a ^ (2 : mynat) + b ^ (2 : mynat) + 2 * a * b := begin rw two_eq_succ_one, rw one_eq_succ_zero, repeat {rw pow_succ}, repeat {rw pow_zero}, ring, end
411e7f01b713c91c9a1938723a8c2b6246a334ca
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/module/linear_pmap.lean
b36ab7fbcd01d397e907ca7e5e758ffc2878a79b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,589
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import linear_algebra.linear_pmap import topology.algebra.module.basic /-! # Partially defined linear operators over topological vector spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define basic notions of partially defined linear operators, which we call unbounded operators for short. In this file we prove all elementary properties of unbounded operators that do not assume that the underlying spaces are normed. ## Main definitions * `linear_pmap.is_closed`: An unbounded operator is closed iff its graph is closed. * `linear_pmap.is_closable`: An unbounded operator is closable iff the closure of its graph is a graph. * `linear_pmap.closure`: For a closable unbounded operator `f : linear_pmap R E F` the closure is the smallest closed extension of `f`. If `f` is not closable, then `f.closure` is defined as `f`. * `linear_pmap.has_core`: a submodule contained in the domain is a core if restricting to the core does not lose information about the unbounded operator. ## Main statements * `linear_pmap.closable_iff_exists_closed_extension`: an unbounded operator is closable iff it has a closed extension. * `linear_pmap.closable.exists_unique`: there exists a unique closure * `linear_pmap.closure_has_core`: the domain of `f` is a core of its closure ## References * [J. Weidmann, *Linear Operators in Hilbert Spaces*][weidmann_linear] ## Tags Unbounded operators, closed operators -/ open_locale topology variables {R E F : Type*} variables [comm_ring R] [add_comm_group E] [add_comm_group F] variables [module R E] [module R F] variables [topological_space E] [topological_space F] namespace linear_pmap /-! ### Closed and closable operators -/ /-- An unbounded operator is closed iff its graph is closed. -/ def is_closed (f : E →ₗ.[R] F) : Prop := is_closed (f.graph : set (E × F)) variables [has_continuous_add E] [has_continuous_add F] variables [topological_space R] [has_continuous_smul R E] [has_continuous_smul R F] /-- An unbounded operator is closable iff the closure of its graph is a graph. -/ def is_closable (f : E →ₗ.[R] F) : Prop := ∃ (f' : linear_pmap R E F), f.graph.topological_closure = f'.graph /-- A closed operator is trivially closable. -/ lemma is_closed.is_closable {f : E →ₗ.[R] F} (hf : f.is_closed) : f.is_closable := ⟨f, hf.submodule_topological_closure_eq⟩ /-- If `g` has a closable extension `f`, then `g` itself is closable. -/ lemma is_closable.le_is_closable {f g : E →ₗ.[R] F} (hf : f.is_closable) (hfg : g ≤ f) : g.is_closable := begin cases hf with f' hf, have : g.graph.topological_closure ≤ f'.graph := by { rw ←hf, exact submodule.topological_closure_mono (le_graph_of_le hfg) }, refine ⟨g.graph.topological_closure.to_linear_pmap _, _⟩, { intros x hx hx', cases x, exact f'.graph_fst_eq_zero_snd (this hx) hx' }, rw [submodule.to_linear_pmap_graph_eq], end /-- The closure is unique. -/ lemma is_closable.exists_unique {f : E →ₗ.[R] F} (hf : f.is_closable) : ∃! (f' : E →ₗ.[R] F), f.graph.topological_closure = f'.graph := begin refine exists_unique_of_exists_of_unique hf (λ _ _ hy₁ hy₂, eq_of_eq_graph _), rw [←hy₁, ←hy₂], end open_locale classical /-- If `f` is closable, then `f.closure` is the closure. Otherwise it is defined as `f.closure = f`. -/ noncomputable def closure (f : E →ₗ.[R] F) : E →ₗ.[R] F := if hf : f.is_closable then hf.some else f lemma closure_def {f : E →ₗ.[R] F} (hf : f.is_closable) : f.closure = hf.some := by simp [closure, hf] lemma closure_def' {f : E →ₗ.[R] F} (hf : ¬f.is_closable) : f.closure = f := by simp [closure, hf] /-- The closure (as a submodule) of the graph is equal to the graph of the closure (as a `linear_pmap`). -/ lemma is_closable.graph_closure_eq_closure_graph {f : E →ₗ.[R] F} (hf : f.is_closable) : f.graph.topological_closure = f.closure.graph := begin rw closure_def hf, exact hf.some_spec, end /-- A `linear_pmap` is contained in its closure. -/ lemma le_closure (f : E →ₗ.[R] F) : f ≤ f.closure := begin by_cases hf : f.is_closable, { refine le_of_le_graph _, rw ←hf.graph_closure_eq_closure_graph, exact (graph f).le_topological_closure }, rw closure_def' hf, end lemma is_closable.closure_mono {f g : E →ₗ.[R] F} (hg : g.is_closable) (h : f ≤ g) : f.closure ≤ g.closure := begin refine le_of_le_graph _, rw ←(hg.le_is_closable h).graph_closure_eq_closure_graph, rw ←hg.graph_closure_eq_closure_graph, exact submodule.topological_closure_mono (le_graph_of_le h), end /-- If `f` is closable, then the closure is closed. -/ lemma is_closable.closure_is_closed {f : E →ₗ.[R] F} (hf : f.is_closable) : f.closure.is_closed := begin rw [is_closed, ←hf.graph_closure_eq_closure_graph], exact f.graph.is_closed_topological_closure, end /-- If `f` is closable, then the closure is closable. -/ lemma is_closable.closure_is_closable {f : E →ₗ.[R] F} (hf : f.is_closable) : f.closure.is_closable := hf.closure_is_closed.is_closable lemma is_closable_iff_exists_closed_extension {f : E →ₗ.[R] F} : f.is_closable ↔ ∃ (g : E →ₗ.[R] F) (hg : g.is_closed), f ≤ g := ⟨λ h, ⟨f.closure, h.closure_is_closed, f.le_closure⟩, λ ⟨_, hg, h⟩, hg.is_closable.le_is_closable h⟩ /-! ### The core of a linear operator -/ /-- A submodule `S` is a core of `f` if the closure of the restriction of `f` to `S` is again `f`.-/ structure has_core (f : E →ₗ.[R] F) (S : submodule R E) : Prop := (le_domain : S ≤ f.domain) (closure_eq : (f.dom_restrict S).closure = f) lemma has_core_def {f : E →ₗ.[R] F} {S : submodule R E} (h : f.has_core S) : (f.dom_restrict S).closure = f := h.2 /-- For every unbounded operator `f` the submodule `f.domain` is a core of its closure. Note that we don't require that `f` is closable, due to the definition of the closure. -/ lemma closure_has_core (f : E →ₗ.[R] F) : f.closure.has_core f.domain := begin refine ⟨f.le_closure.1, _⟩, congr, ext, { simp only [dom_restrict_domain, submodule.mem_inf, and_iff_left_iff_imp], intro hx, exact f.le_closure.1 hx }, intros x y hxy, let z : f.closure.domain := ⟨y.1, f.le_closure.1 y.2⟩, have hyz : (y : E) = z := by simp, rw f.le_closure.2 hyz, exact dom_restrict_apply (hxy.trans hyz), end end linear_pmap
107b0343d5bd32977639766c1f66341326542a39
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Facets.lean
ef86b5c24ea42faaf1ddd6a256a593cd7fadc3fe
[ "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
3,967
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Build.Job import Lake.Build.Data /-! # Simple Builtin Facet Declarations This module contains the definitions of most of the builtin facets. The others are defined `Build.Info`. The facets there require configuration definitions (e.g., `Module`), and some of the facets here are used in said definitions. -/ namespace Lake export System (SearchPath FilePath) /-- A dynamic/shared library for linking. -/ structure Dynlib where /-- Library file path. -/ path : FilePath /-- Library name without platform-specific prefix/suffix (for `-l`). -/ name : String /-- Optional library directory (for `-L`). -/ def Dynlib.dir? (self : Dynlib) : Option FilePath := self.path.parent /-! ## Module Facets -/ /-- A module facet name along with proof of its data type. -/ structure ModuleFacet (α) where /-- The name of the module facet. -/ name : Name /-- Proof that module's facet build result is of type α. -/ data_eq : ModuleData name = α deriving Repr instance (facet : ModuleFacet α) : FamilyDef ModuleData facet.name α := ⟨facet.data_eq⟩ instance [FamilyOut ModuleData facet α] : CoeDep Name facet (ModuleFacet α) := ⟨facet, FamilyOut.family_key_eq_type⟩ /-- The facet which builds all of a module's dependencies (i.e., transitive local imports and `--load-dynlib` shared libraries). Returns the list of shared libraries to load along with their search path. -/ abbrev Module.depsFacet := `deps module_data deps : BuildJob (SearchPath × Array FilePath) /-- The core compilation / elaboration of the Lean file via `lean`, which produce the Lean binaries of the module (i.e., `olean`, `ilean`, `c`). Its trace just includes its dependencies. -/ abbrev Module.leanBinFacet := `bin module_data bin : BuildJob Unit /-- The `leanBinFacet` combined with the module's trace (i.e., the trace of its `olean` and `ilean`). It is the facet used for building a Lean import of a module. -/ abbrev Module.importBinFacet := `importBin module_data importBin : BuildJob Unit /-- The `olean` file produced by `lean` -/ abbrev Module.oleanFacet := `olean module_data olean : BuildJob FilePath /-- The `ilean` file produced by `lean` -/ abbrev Module.ileanFacet := `ilean module_data ilean : BuildJob FilePath /-- The C file built from the Lean file via `lean` -/ abbrev Module.cFacet := `c module_data c : BuildJob FilePath /-- The object file built from `lean.c` -/ abbrev Module.oFacet := `o module_data o : BuildJob FilePath /-! ## Package Facets -/ /-- A package's cloud build release. -/ abbrev Package.releaseFacet := `release package_data release : BuildJob Unit /-- A package's `extraDepTargets` mixed with its transitive dependencies'. -/ abbrev Package.extraDepFacet := `extraDep package_data extraDep : BuildJob Unit /-! ## Target Facets -/ /-- A Lean library's Lean libraries. -/ abbrev LeanLib.leanFacet := `lean library_data lean : BuildJob Unit /-- A Lean library's static binary. -/ abbrev LeanLib.staticFacet := `static library_data static : BuildJob FilePath /-- A Lean library's shared binary. -/ abbrev LeanLib.sharedFacet := `shared library_data shared : BuildJob FilePath /-- A Lean library's `extraDepTargets` mixed with its package's. -/ abbrev LeanLib.extraDepFacet := `extraDep library_data extraDep : BuildJob Unit /-- A Lean binary executable. -/ abbrev LeanExe.exeFacet := `leanExe target_data leanExe : BuildJob FilePath /-- A external library's static binary. -/ abbrev ExternLib.staticFacet := `externLib.static target_data externLib.static : BuildJob FilePath /-- A external library's shared binary. -/ abbrev ExternLib.sharedFacet := `externLib.shared target_data externLib.shared : BuildJob FilePath /-- A external library's dynlib. -/ abbrev ExternLib.dynlibFacet := `externLib.dynlib target_data externLib.dynlib : BuildJob Dynlib
c3efdddd891e6dac8c14c7a109c1d77732622e5e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/eval.lean
e939aa6b18ffdc8f5a2190a52155dcae10cedd36
[ "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
30,820
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.degree.definitions import algebra.geom_sum /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : polynomial R} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_at_zero : p.eval₂ f 0 = f (coeff p 0) := by simp only [eval₂_eq_sum, zero_pow_eq, mul_ite, mul_zero, mul_one, sum, not_not, mem_support_iff, sum_ite_eq', ite_eq_left_iff, ring_hom.map_zero, implies_true_iff, eq_self_iff_true] {contextual := tt} @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := by simp [eval₂_eq_sum] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X : X.eval₂ f x = x := by simp [eval₂_eq_sum] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw X_pow_eq_monomial, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := by { apply sum_add_index; simp [add_mul] } @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s * eval₂ g x p := begin have A : p.nat_degree < p.nat_degree.succ := nat.lt_succ_self _, have B : (s • p).nat_degree < p.nat_degree.succ := (nat_degree_smul_le _ _).trans_lt A, rw [eval₂_eq_sum, eval₂_eq_sum, sum_over_range' _ _ _ A, sum_over_range' _ _ _ B]; simp [mul_sum, mul_assoc], end @[simp] lemma eval₂_C_X : eval₂ C X p = p := polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq]) (λ n x, by rw [eval₂_monomial, monomial_eq_smul_X, C_mul']) /-- `eval₂_add_monoid_hom (f : R →+* S) (x : S)` is the `add_monoid_hom` from `polynomial R` to `S` obtained by evaluating the pushforward of `p` along `f` at `x`. -/ @[simps] def eval₂_add_monoid_hom : polynomial R →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n := begin induction n with n ih, { simp only [eval₂_zero, nat.cast_zero] }, { rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] } end variables [semiring T] lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := begin let T : polynomial R →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ p q, eval₂_add _ _ }, have A : ∀ y, eval₂ f x y = T y := λ y, rfl, simp only [A], rw [sum, T.map_sum, sum] end lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := begin classical, induction s using finset.induction with p hp s hs, simp, rw [sum_insert, eval₂_add, hs, sum_insert]; assumption, end lemma eval₂_to_finsupp_eq_lift_nc {f : R →+* S} {x : S} {p : add_monoid_algebra R ℕ} : eval₂ f x (⟨p⟩ : polynomial R) = lift_nc ↑f (powers_hom S x) p := by { simp only [eval₂_eq_sum, sum, sum_to_finsupp, support, coeff], refl } lemma eval₂_mul_noncomm (hf : ∀ k, commute (f $ q.coeff k) x) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := begin rcases p, rcases q, simp only [coeff] at hf, simp only [mul_to_finsupp, eval₂_to_finsupp_eq_lift_nc], exact lift_nc_mul _ _ p q (λ k n hn, (hf k).pow_right n) end @[simp] lemma eval₂_mul_X : eval₂ f x (p * X) = eval₂ f x p * x := begin refine trans (eval₂_mul_noncomm _ _ $ λ k, _) (by rw eval₂_X), rcases em (k = 1) with (rfl|hk), { simp }, { simp [coeff_X_of_ne_one hk] } end @[simp] lemma eval₂_X_mul : eval₂ f x (X * p) = eval₂ f x p * x := by rw [X_mul, eval₂_mul_X] lemma eval₂_mul_C' (h : commute (f a) x) : eval₂ f x (p * C a) = eval₂ f x p * f a := begin rw [eval₂_mul_noncomm, eval₂_C], intro k, by_cases hk : k = 0, { simp only [hk, h, coeff_C_zero, coeff_C_ne_zero] }, { simp only [coeff_C_ne_zero hk, ring_hom.map_zero, commute.zero_left] } end lemma eval₂_list_prod_noncomm (ps : list (polynomial R)) (hf : ∀ (p ∈ ps) k, commute (f $ coeff p k) x) : eval₂ f x ps.prod = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps using list.reverse_rec_on with ps p ihp, { simp }, { simp only [list.forall_mem_append, list.forall_mem_singleton] at hf, simp [eval₂_mul_noncomm _ _ hf.2, ihp hf.1] } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (x : S) (hf : ∀ a, commute (f a) x) : polynomial R →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ p q, eval₂_mul_noncomm f x (λ k, hf $ coeff q k), map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ variables [comm_semiring S] variables (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := eval₂_mul_noncomm _ _ $ λ k, commute.all _ _ lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x : S) : polynomial R →+* S := { map_one' := eval₂_one _ _, map_mul' := λ _ _, eval₂_mul _ _, ..eval₂_add_monoid_hom f x } @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) lemma eval₂_eq_sum_range' (f : R →+* S) {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i := begin rw [eval₂_eq_sum, p.sum_over_range' _ _ hn], intro i, rw [f.map_zero, zero_mul] end lemma eval₂_dvd : p ∣ q → eval₂ f x p ∣ eval₂ f x q := (eval₂_ring_hom f x).map_dvd lemma eval₂_eq_zero_of_dvd_of_eval₂_eq_zero (h : p ∣ q) (h0 : eval₂ f x p = 0) : eval₂ f x q = 0 := zero_dvd_iff.mp (h0 ▸ eval₂_dvd f x h) end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = p.sum (λ e a, a * x ^ e) := rfl lemma eval_eq_finset_sum (p : polynomial R) (x : R) : p.eval x = ∑ i in range (p.nat_degree + 1), p.coeff i * x ^ i := by { rw [eval_eq_sum, sum_over_range], simp } lemma eval_eq_finset_sum' (P : polynomial R) : (λ x, eval x P) = (λ x, ∑ i in range (P.nat_degree + 1), P.coeff i * x ^ i) := begin ext, exact P.eval_eq_finset_sum x end @[simp] lemma eval₂_at_apply {S : Type*} [semiring S] (f : R →+* S) (r : R) : p.eval₂ f (f r) = f (p.eval r) := begin rw [eval₂_eq_sum, eval_eq_sum, sum, sum, f.map_sum], simp only [f.map_mul, f.map_pow], end @[simp] lemma eval₂_at_one {S : Type*} [semiring S] (f : R →+* S) : p.eval₂ f 1 = f (p.eval 1) := begin convert eval₂_at_apply f 1, simp, end @[simp] lemma eval₂_at_nat_cast {S : Type*} [semiring S] (f : R →+* S) (n : ℕ) : p.eval₂ f n = f (p.eval n) := begin convert eval₂_at_apply f n, simp, end @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} : (s • p).eval x = s * p.eval x := eval₂_smul (ring_hom.id _) _ _ @[simp] lemma eval_C_mul : (C a * p).eval x = a * p.eval x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [mul_add, eval_add, ph, qh], }, { intros n b, simp only [mul_assoc, C_mul_monomial, eval_monomial], } end /-- `polynomial.eval` as linear map -/ @[simps] def leval {R : Type*} [semiring R] (r : R) : polynomial R →ₗ[R] R := { to_fun := λ f, f.eval r, map_add' := λ f g, eval_add, map_smul' := λ c f, eval_smul f r } @[simp] lemma eval_nat_cast_mul {n : ℕ} : ((n : polynomial R) * p).eval x = n * p.eval x := by rw [←C_eq_nat_cast, eval_C_mul] @[simp] lemma eval_mul_X : (p * X).eval x = p.eval x * x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [add_mul, eval_add, ph, qh], }, { intros n a, simp only [←monomial_one_one_eq_X, monomial_mul_monomial, eval_monomial, mul_one, pow_succ', mul_assoc], } end @[simp] lemma eval_mul_X_pow {k : ℕ} : (p * X^k).eval x = p.eval x * x^k := begin induction k with k ih, { simp, }, { simp [pow_succ', ←mul_assoc, ih], } end lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma is_root.eq_zero (h : is_root p x) : eval x p = 0 := h lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp lemma is_root.dvd {R : Type*} [comm_semiring R] {p q : polynomial R} {x : R} (h : p.is_root x) (hpq : p ∣ q) : q.is_root x := by rwa [is_root, eval, eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ hpq] lemma not_is_root_C (r a : R) (hr : r ≠ 0) : ¬ is_root (C r) a := by simpa using hr end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin simp only [comp, eval₂, ← monomial_eq_C_mul_X], exact sum_monomial_eq _, end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := by simp [comp, (C : R →+* _).map_sum] @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma nat_cast_comp {n : ℕ} : (n : polynomial R).comp p = n := by rw [←C_eq_nat_cast, C_comp] @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma monomial_comp (n : ℕ) : (monomial n a).comp p = C a * p^n := eval₂_monomial _ _ @[simp] lemma mul_X_comp : (p * X).comp r = p.comp r * r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, add_mul, add_comp] }, { intros n b, simp only [pow_succ', mul_assoc, monomial_mul_X, monomial_comp] } end @[simp] lemma X_pow_comp {k : ℕ} : (X^k).comp p = p^k := begin induction k with k ih, { simp, }, { simp [pow_succ', mul_X_comp, ih], }, end @[simp] lemma mul_X_pow_comp {k : ℕ} : (p * X^k).comp r = p.comp r * r^k := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, mul_X_comp], }, end @[simp] lemma C_mul_comp : (C a * p).comp r = C a * p.comp r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, mul_add], }, { intros n b, simp [mul_assoc], } end @[simp] lemma nat_cast_mul_comp {n : ℕ} : ((n : polynomial R) * p).comp r = n * p.comp r := by rw [←C_eq_nat_cast, C_mul_comp, C_eq_nat_cast] @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : polynomial R) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ lemma prod_comp {R : Type*} [comm_semiring R] (s : multiset (polynomial R)) (p : polynomial R) : s.prod.comp p = (s.map (λ q : polynomial R, q.comp p)).prod := (s.prod_hom (monoid_hom.mk (λ q : polynomial R, q.comp p) one_comp (λ q r, mul_comp q r p))).symm @[simp] lemma pow_comp {R : Type*} [comm_semiring R] (p q : polynomial R) (n : ℕ) : (p^n).comp q = (p.comp q)^n := ((monoid_hom.mk (λ r : polynomial R, r.comp q)) one_comp (λ r s, mul_comp r s q)).map_pow p n @[simp] lemma bit0_comp : comp (bit0 p : polynomial R) q = bit0 (p.comp q) := by simp only [bit0, add_comp] @[simp] lemma bit1_comp : comp (bit1 p : polynomial R) q = bit1 (p.comp q) := by simp only [bit1, add_comp, bit0_comp, one_comp] lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : polynomial R) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C.comp f) X @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, monomial_eq_C_mul_X], refl, end @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := by { rw [map, eval₂_mul_noncomm], exact λ k, (commute_X _).symm } @[simp] lemma map_smul (r : R) : (r • p).map f = f r • p.map f := by rw [map, eval₂_smul, ring_hom.comp_apply, C_mul'] /-- `polynomial.map` as a `ring_hom`. -/ -- `map` is a ring-hom unconditionally, and theoretically the definition could be replaced, -- but this turns out not to be easy because `p.map f` does not resolve to `polynomial.map` -- if `map` is a `ring_hom` instead of a plain function; the elaborator does not try to coerce -- to a function before trying field (dot) notation (this may be technically infeasible); -- the relevant code is (both lines): https://github.com/leanprover-community/ -- lean/blob/487ac5d7e9b34800502e1ddf3c7c806c01cf9d51/src/frontends/lean/elaborator.cpp#L1876-L1913 def map_ring_hom (f : R →+* S) : polynomial R →+* polynomial S := { to_fun := polynomial.map f, map_add' := λ _ _, map_add f, map_zero' := map_zero f, map_mul' := λ _ _, map_mul f, map_one' := map_one f } @[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl -- This is protected to not clash with the global `map_nat_cast`. @[simp] protected theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n := map_nat_cast (map_ring_hom f) n @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum, sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, sum, ring_hom.map_sum], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, f.map_mul], split_ifs; simp [f.map_zero], end /-- If `R` and `S` are isomorphic, then so are their polynomial rings. -/ @[simps] def map_equiv (e : R ≃+* S) : polynomial R ≃+* polynomial S := ring_equiv.of_hom_inv (map_ring_hom e) (map_ring_hom e.symm) (by ext; simp) (by ext; simp) lemma map_map [semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f) : function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] lemma map_surjective (hf : function.surjective f) : function.surjective (map f) := λ p, polynomial.induction_on' p (λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [map_add f, hp', hq']⟩) (λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩) lemma degree_map_le (p : polynomial R) : degree (p.map f) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl], end lemma nat_degree_map_le (p : polynomial R) : nat_degree (p.map f) ≤ nat_degree p := nat_degree_le_nat_degree (degree_map_le f p) variables {f} lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp only [mul_one, hp.leading_coeff, f.map_one] ... = f x * (p.map f).coeff p.nat_degree : congr_arg _ (coeff_map _ _).symm ... = 0 : by simp only [hfp, mul_zero, coeff_zero], λ h, ext (λ n, by simp only [h, coeff_map, coeff_zero]) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) lemma degree_map_eq_of_leading_coeff_ne_zero (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 leading_coeff_ne_zero.mp (λ hp0, hf (trans (congr_arg _ hp0) f.map_zero)), 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 (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 (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 variables (f) @[simp] lemma map_ring_hom_id : map_ring_hom (ring_hom.id R) = ring_hom.id (polynomial R) := ring_hom.ext $ λ x, map_id @[simp] lemma map_ring_hom_comp [semiring T] (f : S →+* T) (g : R →+* S) : (map_ring_hom f).comp (map_ring_hom g) = map_ring_hom (f.comp g) := ring_hom.ext $ polynomial.map_map g f lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (map_ring_hom f).to_monoid_hom @[simp] protected lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := (map_ring_hom f).map_pow _ _ lemma mem_map_srange {p : polynomial S} : p ∈ (map_ring_hom f).srange ↔ ∀ n, p.coeff n ∈ f.srange := begin split, { rintro ⟨p, rfl⟩ n, rw [coe_map_ring_hom, coeff_map], exact set.mem_range_self _ }, { intro h, rw p.as_sum_range_C_mul_X_pow, refine (map_ring_hom f).srange.sum_mem _, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [coe_map_ring_hom, map_mul, map_C, hc, polynomial.map_pow, map_X] } end lemma mem_map_range {R S : Type*} [ring R] [ring S] (f : R →+* S) {p : polynomial S} : p ∈ (map_ring_hom f).range ↔ ∀ n, p.coeff n ∈ f.range := mem_map_srange f lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := begin have A : nat_degree (p.map f) < p.nat_degree.succ := (nat_degree_map_le _ _).trans_lt (nat.lt_succ_self _), conv_lhs { rw [eval₂_eq_sum], }, rw [sum_over_range' _ _ _ A], { simp only [coeff_map, eval₂_eq_sum, sum_over_range, forall_const, zero_mul, ring_hom.map_zero, function.comp_app, ring_hom.coe_comp] }, { simp only [forall_const, zero_mul, ring_hom.map_zero] } end lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map f (ring_hom.id _) x lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := (map_ring_hom f).map_sum _ _ lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp only [map_C, forall_const, C_comp, eq_self_iff_true]) (by simp only [map_add, add_comp, forall_const, implies_true_iff, eq_self_iff_true] {contextual := tt}) (by simp only [pow_succ', ←mul_assoc, comp, forall_const, eval₂_mul_X, implies_true_iff, eq_self_iff_true, map_X, map_mul] {contextual := tt}) @[simp] lemma eval_zero_map (f : R →+* S) (p : polynomial R) : (p.map f).eval 0 = f (p.eval 0) := by simp [←coeff_zero_eq_eval_zero] @[simp] lemma eval_one_map (f : R →+* S) (p : polynomial R) : (p.map f).eval 1 = f (p.eval 1) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [one_pow, mul_one, eval_monomial, map_monomial] } end @[simp] lemma eval_nat_cast_map (f : R →+* S) (p : polynomial R) (n : ℕ) : (p.map f).eval n = f (p.eval n) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [map_nat_cast f, eval_monomial, map_monomial, f.map_pow, f.map_mul] } end @[simp] lemma eval_int_cast_map {R S : Type*} [ring R] [ring S] (f : R →+* S) (p : polynomial R) (i : ℤ) : (p.map f).eval i = f (p.eval i) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [f.map_int_cast, eval_monomial, map_monomial, f.map_pow, f.map_mul] } end end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ variables [semiring S] [semiring T] (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := by rw [←eval₂_map, eval₂_at_apply, eval_map] end hom_eval₂ end semiring section comm_semiring section eval variables [comm_semiring R] {p q : polynomial R} {x : R} lemma eval₂_comp [comm_semiring S] (f : R →+* S) {x : S} : eval₂ f x (p.comp q) = eval₂ f (eval₂ f x q) p := by rw [comp, p.as_sum_range]; simp [eval₂_finset_sum, eval₂_pow] @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ /-- `eval r`, regarded as a ring homomorphism from `polynomial R` to `R`. -/ def eval_ring_hom : R → polynomial R →+* R := eval₂_ring_hom (ring_hom.id _) @[simp] lemma coe_eval_ring_hom (r : R) : ((eval_ring_hom r) : polynomial R → R) = eval r := rfl @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ @[simp] lemma eval_comp : (p.comp q).eval x = p.eval (q.eval x) := begin apply polynomial.induction_on' p, { intros r s hr hs, simp [add_comp, hr, hs], }, { intros n a, simp, } end /-- `comp p`, regarded as a ring homomorphism from `polynomial R` to itself. -/ def comp_ring_hom : polynomial R → polynomial R →+* polynomial R := eval₂_ring_hom C lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] /-- Polynomial evaluation commutes with `list.prod` -/ lemma eval_list_prod (l : list (polynomial R)) (x : R) : eval x l.prod = (l.map (eval x)).prod := (eval_ring_hom x).map_list_prod l /-- Polynomial evaluation commutes with `multiset.prod` -/ lemma eval_multiset_prod (s : multiset (polynomial R)) (x : R) : eval x s.prod = (s.map (eval x)).prod := (eval_ring_hom x).map_multiset_prod s /-- Polynomial evaluation commutes with `finset.prod` -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := (eval_ring_hom x).map_prod _ _ lemma is_root_prod {R} [comm_ring R] [is_domain R] {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) : is_root (∏ j in s, p j) x ↔ ∃ i ∈ s, is_root (p i) x := by simp only [is_root, eval_prod, finset.prod_eq_zero_iff] lemma eval_dvd : p ∣ q → eval x p ∣ eval x q := eval₂_dvd _ _ lemma eval_eq_zero_of_dvd_of_eval_eq_zero : p ∣ q → eval x p = 0 → eval x q = 0 := eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ @[simp] lemma eval_geom_sum {R} [comm_semiring R] {n : ℕ} {x : R} : eval x (geom_sum X n) = geom_sum x n := by simp [geom_sum_def, eval_finset_sum] end eval section map variables [comm_semiring R] [comm_semiring S] (f : R →+* S) lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (map_ring_hom f).to_monoid_hom lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := (map_ring_hom f).map_prod _ _ lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support := begin intros x, simp only [mem_support_iff], contrapose!, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f, end lemma is_root.map {f : R →+* S} {x : R} {p : polynomial R} (h : is_root p x) : is_root (p.map f) (f x) := by rw [is_root, eval_map, eval₂_hom, h.eq_zero, f.map_zero] lemma is_root.of_map {R} [comm_ring R] {f : R →+* S} {x : R} {p : polynomial R} (h : is_root (p.map f) (f x)) (hf : function.injective f) : is_root p x := by rwa [is_root, ←f.injective_iff'.mp hf, ←eval₂_hom, ←eval_map] lemma is_root_map_iff {R : Type*} [comm_ring R] {f : R →+* S} {x : R} {p : polynomial R} (hf : function.injective f) : is_root (p.map f) (f x) ↔ is_root p x := ⟨λ h, h.of_map hf, λ h, h.map⟩ end map end comm_semiring section ring variables [ring R] {p q r : polynomial R} lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b @[simp] lemma map_sub {S} [ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := (map_ring_hom f).map_sub p q @[simp] lemma map_neg {S} [ring S] (f : R →+* S) : (-p).map f = -(p.map f) := (map_ring_hom f).map_neg p @[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := (map_ring_hom f).map_int_cast n @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ @[simp] lemma cast_int_comp (i : ℤ) : comp (i : polynomial R) p = i := by cases i; simp end ring end polynomial
1c2fa572059df7082a17000c42303ae0128597c9
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter2/2-6+7.lean
1cf682f8b8797f35064c490e1eba827f911bf150
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
618
lean
def compose (α β γ : Type) (g : β → γ) (f : α → β) (z : α) : γ := g $ f z section a variables (α β γ : Type) def doTwice (f : α → α) (x : α) : α := f $ f x end a section bar variables (α β γ : nat) end bar namespace abracadabra constant bob : nat def bob2 := 2 def bob2x (x : nat) : nat := bob2 * x #reduce bob2x #print bob2x end abracadabra #reduce abracadabra.bob2x #print abracadabra.bob2x open abracadabra #reduce bob2x #print bob2x #check list.nil open list #check nil #check cons #check append
dd552f38c09df26e845af26de641ca38c3087ed5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/finset/powerset.lean
e31cc8ba38cc06bb0fdf8c6aeea3cc81cae31647
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
10,187
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.finset.lattice /-! # The powerset of a finset -/ namespace finset open multiset variables {α : Type*} /-! ### powerset -/ section powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] lemma powerset_empty : finset.powerset (∅ : finset α) = {∅} := rfl @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) lemma not_mem_of_mem_powerset_of_not_mem {s t : finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by { apply mt _ h, apply mem_powerset.1 ht } lemma powerset_insert [decidable_eq α] (s : finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := begin ext t, simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff], by_cases h : a ∈ t, { split, { exact λH, or.inr ⟨_, H, insert_erase h⟩ }, { intros H, cases H, { exact subset.trans (erase_subset a t) H }, { rcases H with ⟨u, hu⟩, rw ← hu.2, exact subset.trans (erase_insert_subset a u) hu.1 } } }, { have : ¬ ∃ (u : finset α), u ⊆ s ∧ insert a u = t, by simp [ne.symm (ne_insert_of_not_mem _ _ h)], simp [finset.erase_eq_of_not_mem h, this] } end /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for any subset. -/ instance decidable_exists_of_decidable_subsets {s : finset α} {p : Π t ⊆ s, Prop} [Π t (h : t ⊆ s), decidable (p t h)] : decidable (∃ t (h : t ⊆ s), p t h) := decidable_of_iff (∃ t (hs : t ∈ s.powerset), p t (mem_powerset.1 hs)) ⟨(λ ⟨t, _, hp⟩, ⟨t, _, hp⟩), (λ ⟨t, hs, hp⟩, ⟨t, mem_powerset.2 hs, hp⟩)⟩ /-- For predicate `p` decidable on subsets, it is decidable whether `p` holds for every subset. -/ instance decidable_forall_of_decidable_subsets {s : finset α} {p : Π t ⊆ s, Prop} [Π t (h : t ⊆ s), decidable (p t h)] : decidable (∀ t (h : t ⊆ s), p t h) := decidable_of_iff (∀ t (h : t ∈ s.powerset), p t (mem_powerset.1 h)) ⟨(λ h t hs, h t (mem_powerset.2 hs)), (λ h _ _, h _ _)⟩ /-- A version of `finset.decidable_exists_of_decidable_subsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidable_exists_of_decidable_subsets' {s : finset α} {p : finset α → Prop} (hu : Π t (h : t ⊆ s), decidable (p t)) : decidable (∃ t (h : t ⊆ s), p t) := @finset.decidable_exists_of_decidable_subsets _ _ _ hu /-- A version of `finset.decidable_forall_of_decidable_subsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidable_forall_of_decidable_subsets' {s : finset α} {p : finset α → Prop} (hu : Π t (h : t ⊆ s), decidable (p t)) : decidable (∀ t (h : t ⊆ s), p t) := @finset.decidable_forall_of_decidable_subsets _ _ _ hu end powerset section ssubsets variables [decidable_eq α] /-- For `s` a finset, `s.ssubsets` is the finset comprising strict subsets of `s`. -/ def ssubsets (s : finset α) : finset (finset α) := erase (powerset s) s @[simp] lemma mem_ssubsets {s t : finset α} : t ∈ s.ssubsets ↔ t ⊂ s := by rw [ssubsets, mem_erase, mem_powerset, ssubset_iff_subset_ne, and.comm] lemma empty_mem_ssubsets {s : finset α} (h : s.nonempty) : ∅ ∈ s.ssubsets := by { rw [mem_ssubsets, ssubset_iff_subset_ne], exact ⟨empty_subset s, h.ne_empty.symm⟩, } /-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for any ssubset. -/ instance decidable_exists_of_decidable_ssubsets {s : finset α} {p : Π t ⊂ s, Prop} [Π t (h : t ⊂ s), decidable (p t h)] : decidable (∃ t h, p t h) := decidable_of_iff (∃ t (hs : t ∈ s.ssubsets), p t (mem_ssubsets.1 hs)) ⟨(λ ⟨t, _, hp⟩, ⟨t, _, hp⟩), (λ ⟨t, hs, hp⟩, ⟨t, mem_ssubsets.2 hs, hp⟩)⟩ /-- For predicate `p` decidable on ssubsets, it is decidable whether `p` holds for every ssubset. -/ instance decidable_forall_of_decidable_ssubsets {s : finset α} {p : Π t ⊂ s, Prop} [Π t (h : t ⊂ s), decidable (p t h)] : decidable (∀ t h, p t h) := decidable_of_iff (∀ t (h : t ∈ s.ssubsets), p t (mem_ssubsets.1 h)) ⟨(λ h t hs, h t (mem_ssubsets.2 hs)), (λ h _ _, h _ _)⟩ /-- A version of `finset.decidable_exists_of_decidable_ssubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidable_exists_of_decidable_ssubsets' {s : finset α} {p : finset α → Prop} (hu : Π t (h : t ⊂ s), decidable (p t)) : decidable (∃ t (h : t ⊂ s), p t) := @finset.decidable_exists_of_decidable_ssubsets _ _ _ _ hu /-- A version of `finset.decidable_forall_of_decidable_ssubsets` with a non-dependent `p`. Typeclass inference cannot find `hu` here, so this is not an instance. -/ def decidable_forall_of_decidable_ssubsets' {s : finset α} {p : finset α → Prop} (hu : Π t (h : t ⊂ s), decidable (p t)) : decidable (∀ t (h : t ⊂ s), p t) := @finset.decidable_forall_of_decidable_ssubsets _ _ _ _ hu end ssubsets section powerset_len /-- Given an integer `n` and a finset `s`, then `powerset_len n s` is the finset of subsets of `s` of cardinality `n`. -/ def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) @[simp] lemma powerset_len_zero (s : finset α) : finset.powerset_len 0 s = {∅} := begin ext, rw [mem_powerset_len, mem_singleton, card_eq_zero], refine ⟨λ h, h.2, λ h, by { rw h, exact ⟨empty_subset s, rfl⟩ }⟩, end @[simp] theorem powerset_len_empty (n : ℕ) {s : finset α} (h : s.card < n) : powerset_len n s = ∅ := finset.card_eq_zero.mp (by rw [card_powerset_len, nat.choose_eq_zero_of_lt h]) theorem powerset_len_eq_filter {n} {s : finset α} : powerset_len n s = (powerset s).filter (λ x, x.card = n) := by { ext, simp [mem_powerset_len] } lemma powerset_len_succ_insert [decidable_eq α] {x : α} {s : finset α} (h : x ∉ s) (n : ℕ) : powerset_len n.succ (insert x s) = powerset_len n.succ s ∪ (powerset_len n s).image (insert x) := begin rw [powerset_len_eq_filter, powerset_insert, filter_union, ←powerset_len_eq_filter], congr, rw [powerset_len_eq_filter, image_filter], congr' 1, ext t, simp only [mem_powerset, mem_filter, function.comp_app, and.congr_right_iff], intro ht, have : x ∉ t := λ H, h (ht H), simp [card_insert_of_not_mem this, nat.succ_inj'] end lemma powerset_len_nonempty {n : ℕ} {s : finset α} (h : n < s.card) : (powerset_len n s).nonempty := begin classical, induction s using finset.induction_on with x s hx IH generalizing n, { simpa using h }, { cases n, { simp }, { rw [card_insert_of_not_mem hx, nat.succ_lt_succ_iff] at h, rw powerset_len_succ_insert hx, refine nonempty.mono _ ((IH h).image (insert x)), convert (subset_union_right _ _) } } end @[simp] lemma powerset_len_self (s : finset α) : powerset_len s.card s = {s} := begin ext, rw [mem_powerset_len, mem_singleton], split, { exact λ ⟨hs, hc⟩, eq_of_subset_of_card_le hs hc.ge }, { rintro rfl, simp } end lemma powerset_card_bUnion [decidable_eq (finset α)] (s : finset α) : finset.powerset s = (range (s.card + 1)).bUnion (λ i, powerset_len i s) := begin refine ext (λ a, ⟨λ ha, _, λ ha, _ ⟩), { rw mem_bUnion, exact ⟨a.card, mem_range.mpr (nat.lt_succ_of_le (card_le_of_subset (mem_powerset.mp ha))), mem_powerset_len.mpr ⟨mem_powerset.mp ha, rfl⟩⟩ }, { rcases mem_bUnion.mp ha with ⟨i, hi, ha⟩, exact mem_powerset.mpr (mem_powerset_len.mp ha).1, } end lemma powerset_len_sup [decidable_eq α] (u : finset α) (n : ℕ) (hn : n < u.card) : (powerset_len n.succ u).sup id = u := begin apply le_antisymm, { simp_rw [sup_le_iff, mem_powerset_len], rintros x ⟨h, -⟩, exact h }, { rw [sup_eq_bUnion, le_iff_subset, subset_iff], cases (nat.succ_le_of_lt hn).eq_or_lt with h' h', { simp [h'] }, { intros x hx, simp only [mem_bUnion, exists_prop, id.def], obtain ⟨t, ht⟩ : ∃ t, t ∈ powerset_len n (u.erase x) := powerset_len_nonempty _, { refine ⟨insert x t, _, mem_insert_self _ _⟩, rw [←insert_erase hx, powerset_len_succ_insert (not_mem_erase _ _)], exact mem_union_right _ (mem_image_of_mem _ ht) }, { rwa [card_erase_of_mem hx, nat.lt_pred_iff] } } } end end powerset_len end finset
b5268664178bc4efbdf763afdfe9235cb1c07e64
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/pi.lean
8ee93c4bcb42c2c6cac69b142617b305d9b52cb5
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,018
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Alex Kontorovich -/ import order.filter.bases /-! # (Co)product of a family of filters In this file we define two filters on `Π i, α i` and prove some basic properties of these filters. * `filter.pi (f : Π i, filter (α i))` to be the maximal filter on `Π i, α i` such that `∀ i, filter.tendsto (function.eval i) (filter.pi f) (f i)`. It is defined as `Π i, filter.comap (function.eval i) (f i)`. This is a generalization of `filter.prod` to indexed products. * `filter.Coprod (f : Π i, filter (α i))`: a generalization of `filter.coprod`; it is the supremum of `comap (eval i) (f i)`. -/ open set function open_locale classical filter namespace filter variables {ι : Type*} {α : ι → Type*} {f f₁ f₂ : Π i, filter (α i)} {s : Π i, set (α i)} section pi /-- The product of an indexed family of filters. -/ def pi (f : Π i, filter (α i)) : filter (Π i, α i) := ⨅ i, comap (eval i) (f i) lemma tendsto_eval_pi (f : Π i, filter (α i)) (i : ι) : tendsto (eval i) (pi f) (f i) := tendsto_infi' i tendsto_comap lemma tendsto_pi {β : Type*} {m : β → Π i, α i} {l : filter β} : tendsto m l (pi f) ↔ ∀ i, tendsto (λ x, m x i) l (f i) := by simp only [pi, tendsto_infi, tendsto_comap_iff] lemma le_pi {g : filter (Π i, α i)} : g ≤ pi f ↔ ∀ i, tendsto (eval i) g (f i) := tendsto_pi @[mono] lemma pi_mono (h : ∀ i, f₁ i ≤ f₂ i) : pi f₁ ≤ pi f₂ := infi_mono $ λ i, comap_mono $ h i lemma mem_pi_of_mem (i : ι) {s : set (α i)} (hs : s ∈ f i) : eval i ⁻¹' s ∈ pi f := mem_infi_of_mem i $ preimage_mem_comap hs lemma pi_mem_pi {I : set ι} (hI : finite I) (h : ∀ i ∈ I, s i ∈ f i) : I.pi s ∈ pi f := begin rw [pi_def, bInter_eq_Inter], refine mem_infi_of_Inter hI (λ i, _) subset.rfl, exact preimage_mem_comap (h i i.2) end lemma mem_pi {s : set (Π i, α i)} : s ∈ pi f ↔ ∃ (I : set ι), finite I ∧ ∃ t : Π i, set (α i), (∀ i, t i ∈ f i) ∧ I.pi t ⊆ s := begin split, { simp only [pi, mem_infi', mem_comap, pi_def], rintro ⟨I, If, V, hVf, hVI, rfl, -⟩, choose t htf htV using hVf, exact ⟨I, If, t, htf, Inter₂_mono (λ i _, htV i)⟩ }, { rintro ⟨I, If, t, htf, hts⟩, exact mem_of_superset (pi_mem_pi If $ λ i _, htf i) hts } end lemma mem_pi' {s : set (Π i, α i)} : s ∈ pi f ↔ ∃ (I : finset ι), ∃ t : Π i, set (α i), (∀ i, t i ∈ f i) ∧ set.pi ↑I t ⊆ s := mem_pi.trans exists_finite_iff_finset lemma mem_of_pi_mem_pi [∀ i, ne_bot (f i)] {I : set ι} (h : I.pi s ∈ pi f) {i : ι} (hi : i ∈ I) : s i ∈ f i := begin rcases mem_pi.1 h with ⟨I', I'f, t, htf, hts⟩, refine mem_of_superset (htf i) (λ x hx, _), have : ∀ i, (t i).nonempty, from λ i, nonempty_of_mem (htf i), choose g hg, have : update g i x ∈ I'.pi t, { intros j hj, rcases eq_or_ne j i with (rfl|hne); simp * }, simpa using hts this i hi end @[simp] lemma pi_mem_pi_iff [∀ i, ne_bot (f i)] {I : set ι} (hI : finite I) : I.pi s ∈ pi f ↔ ∀ i ∈ I, s i ∈ f i := ⟨λ h i hi, mem_of_pi_mem_pi h hi, pi_mem_pi hI⟩ lemma has_basis_pi {ι' : ι → Type} {s : Π i, ι' i → set (α i)} {p : Π i, ι' i → Prop} (h : ∀ i, (f i).has_basis (p i) (s i)) : (pi f).has_basis (λ If : set ι × Π i, ι' i, finite If.1 ∧ ∀ i ∈ If.1, p i (If.2 i)) (λ If : set ι × Π i, ι' i, If.1.pi (λ i, s i $ If.2 i)) := begin have : (pi f).has_basis _ _ := has_basis_infi (λ i, (h i).comap (eval i : (Π j, α j) → α i)), convert this, ext, simp end @[simp] lemma pi_inf_principal_univ_pi_eq_bot : pi f ⊓ 𝓟 (set.pi univ s) = ⊥ ↔ ∃ i, f i ⊓ 𝓟 (s i) = ⊥ := begin split, { simp only [inf_principal_eq_bot, mem_pi], contrapose!, rintros (hsf : ∀ i, ∃ᶠ x in f i, x ∈ s i) I If t htf hts, have : ∀ i, (s i ∩ t i).nonempty, from λ i, ((hsf i).and_eventually (htf i)).exists, choose x hxs hxt, exact hts (λ i hi, hxt i) (mem_univ_pi.2 hxs) }, { simp only [inf_principal_eq_bot], rintro ⟨i, hi⟩, filter_upwards [mem_pi_of_mem i hi] with x using mt (λ h, h i trivial), }, end @[simp] lemma pi_inf_principal_pi_eq_bot [Π i, ne_bot (f i)] {I : set ι} : pi f ⊓ 𝓟 (set.pi I s) = ⊥ ↔ ∃ i ∈ I, f i ⊓ 𝓟 (s i) = ⊥ := begin rw [← univ_pi_piecewise I, pi_inf_principal_univ_pi_eq_bot], refine exists_congr (λ i, _), by_cases hi : i ∈ I; simp [hi, (‹Π i, ne_bot (f i)› i).ne] end @[simp] lemma pi_inf_principal_univ_pi_ne_bot : ne_bot (pi f ⊓ 𝓟 (set.pi univ s)) ↔ ∀ i, ne_bot (f i ⊓ 𝓟 (s i)) := by simp [ne_bot_iff] @[simp] lemma pi_inf_principal_pi_ne_bot [Π i, ne_bot (f i)] {I : set ι} : ne_bot (pi f ⊓ 𝓟 (I.pi s)) ↔ ∀ i ∈ I, ne_bot (f i ⊓ 𝓟 (s i)) := by simp [ne_bot_iff] instance pi_inf_principal_pi.ne_bot [h : ∀ i, ne_bot (f i ⊓ 𝓟 (s i))] {I : set ι} : ne_bot (pi f ⊓ 𝓟 (I.pi s)) := (pi_inf_principal_univ_pi_ne_bot.2 ‹_›).mono $ inf_le_inf_left _ $ principal_mono.2 $ λ x hx i hi, hx i trivial @[simp] lemma pi_eq_bot : pi f = ⊥ ↔ ∃ i, f i = ⊥ := by simpa using @pi_inf_principal_univ_pi_eq_bot ι α f (λ _, univ) @[simp] lemma pi_ne_bot : ne_bot (pi f) ↔ ∀ i, ne_bot (f i) := by simp [ne_bot_iff] instance [∀ i, ne_bot (f i)] : ne_bot (pi f) := pi_ne_bot.2 ‹_› end pi /-! ### `n`-ary coproducts of filters -/ section Coprod /-- Coproduct of filters. -/ protected def Coprod (f : Π i, filter (α i)) : filter (Π i, α i) := ⨆ i : ι, comap (eval i) (f i) lemma mem_Coprod_iff {s : set (Π i, α i)} : (s ∈ filter.Coprod f) ↔ (∀ i : ι, (∃ t₁ ∈ f i, eval i ⁻¹' t₁ ⊆ s)) := by simp [filter.Coprod] lemma compl_mem_Coprod {s : set (Π i, α i)} : sᶜ ∈ filter.Coprod f ↔ ∀ i, (eval i '' s)ᶜ ∈ f i := by simp only [filter.Coprod, mem_supr, compl_mem_comap] lemma Coprod_ne_bot_iff' : ne_bot (filter.Coprod f) ↔ (∀ i, nonempty (α i)) ∧ ∃ d, ne_bot (f d) := by simp only [filter.Coprod, supr_ne_bot, ← exists_and_distrib_left, ← comap_eval_ne_bot_iff'] @[simp] lemma Coprod_ne_bot_iff [∀ i, nonempty (α i)] : ne_bot (filter.Coprod f) ↔ ∃ d, ne_bot (f d) := by simp [Coprod_ne_bot_iff', *] lemma Coprod_eq_bot_iff' : filter.Coprod f = ⊥ ↔ (∃ i, is_empty (α i)) ∨ f = ⊥ := by simpa [not_and_distrib, funext_iff] using not_congr Coprod_ne_bot_iff' @[simp] lemma Coprod_eq_bot_iff [∀ i, nonempty (α i)] : filter.Coprod f = ⊥ ↔ f = ⊥ := by simpa [funext_iff] using not_congr Coprod_ne_bot_iff @[simp] lemma Coprod_bot' : filter.Coprod (⊥ : Π i, filter (α i)) = ⊥ := Coprod_eq_bot_iff'.2 (or.inr rfl) @[simp] lemma Coprod_bot : filter.Coprod (λ _, ⊥ : Π i, filter (α i)) = ⊥ := Coprod_bot' lemma ne_bot.Coprod [∀ i, nonempty (α i)] {i : ι} (h : ne_bot (f i)) : ne_bot (filter.Coprod f) := Coprod_ne_bot_iff.2 ⟨i, h⟩ @[instance] lemma Coprod_ne_bot [∀ i, nonempty (α i)] [nonempty ι] (f : Π i, filter (α i)) [H : ∀ i, ne_bot (f i)] : ne_bot (filter.Coprod f) := (H (classical.arbitrary ι)).Coprod @[mono] lemma Coprod_mono (hf : ∀ i, f₁ i ≤ f₂ i) : filter.Coprod f₁ ≤ filter.Coprod f₂ := supr_mono $ λ i, comap_mono (hf i) variables {β : ι → Type*} {m : Π i, α i → β i} lemma map_pi_map_Coprod_le : map (λ (k : Π i, α i), λ i, m i (k i)) (filter.Coprod f) ≤ filter.Coprod (λ i, map (m i) (f i)) := begin simp only [le_def, mem_map, mem_Coprod_iff], intros s h i, obtain ⟨t, H, hH⟩ := h i, exact ⟨{x : α i | m i x ∈ t}, H, λ x hx, hH hx⟩ end lemma tendsto.pi_map_Coprod {g : Π i, filter (β i)} (h : ∀ i, tendsto (m i) (f i) (g i)) : tendsto (λ (k : Π i, α i), λ i, m i (k i)) (filter.Coprod f) (filter.Coprod g) := map_pi_map_Coprod_le.trans (Coprod_mono h) end Coprod end filter
912f02b25ec763fc12c41d35e44219fd364255b6
290f65d8de0088e3098f612884d54e5b714d7862
/src/affine_algebraic_set/basic.lean
d4a3025ae24ea3195c1a80a85ca5163029baf7e1
[ "Apache-2.0" ]
permissive
auhlmann/M4P33
ec775fd53610427b35f59ef84d469c30511de24e
dc2586aa3a8e0d916fc0795df592a996c89c85bb
refs/heads/master
1,607,862,664,432
1,579,796,968,000
1,579,796,968,000
234,415,945
0
0
Apache-2.0
1,579,210,321,000
1,579,210,320,000
null
UTF-8
Lean
false
false
4,312
lean
/- Copyright (c) 2020 Kevin Buzzard Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, and whoever else wants to join in. -/ import data.mv_polynomial -- We want to be able to talk about V ⊆ W if V and W are affine algebraic sets -- We will need import order.lattice at some point. /-! # Affine algebraic sets This file defines affine algebraic subsets of affine n-space and proves basic properties about them. ## Important definitions * `affine_algebraic_set k n` -- the type of affine algebraic subsets of kⁿ. ## Notation None as yet -- do we need 𝔸ⁿ for affine n-space? ## Implementation notes None yet. ## References Martin Orr's lecture notes https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/ ## Tags algebraic geometry, algebraic variety -/ -- let k be a commutative ring variables {k : Type*} [comm_ring k] -- and let n be a natural number variable {n : ℕ} -- In Lean, the multivariable polynomial ring k[X₁, X₂, ..., Xₙ] is -- denoted `mv_polynomial (fin n) k`. We could use better notation. -- The set kⁿ is denoted `fin n → k` (which means maps from {0,1,2,...,(n-1)} to k). -- We now make some definitions which we'll need in the course. namespace mv_polynomial -- means "multivariable polynomial" /-- The set of zeros in kⁿ of a function f ∈ k[X₁, X₂, ..., Xₙ] -/ def zeros (f : mv_polynomial (fin n) k) : set (fin n → k) := {x | f.eval x = 0} -- I just want to write f(x) = 0 really /-- x is in the zeros of f iff f(x) = 0 -/ @[simp] lemma mem_zeros (f : mv_polynomial (fin n) k) (x : fin n → k) : x ∈ f.zeros ↔ f.eval x = 0 := iff.rfl -- note that the next result needs that k is a field. /-- The zeros of f * g are the union of the zeros of f and of g -/ lemma zeros_mul {k : Type*} [discrete_field k] (f g : mv_polynomial (fin n) k) : zeros (f * g) = zeros f ∪ zeros g := begin -- two sets are equal if they have the same elements ext, -- and now it's not hard to prove using `mem_zeros` and other -- equalities known to Lean's simplifier. simp, -- TODO -- should I give the full proof here? end end mv_polynomial open mv_polynomial /-- An affine algebraic subset of kⁿ is the common zeros of a set of polynomials -/ structure affine_algebraic_set (k : Type*) [comm_ring k] (n : ℕ) := -- a subset of the set of maps {0,1,2,...,n-1} → k (called "carrier") (carrier : set (fin n → k)) -- ...such that there's a set of polynomials such that the carrier is equal to the -- intersection of the zeros of the polynomials in the set. (is_algebraic' : ∃ S : set (mv_polynomial (fin n) k), carrier = ⋂ f ∈ S, zeros f) -- ...such that namespace affine_algebraic_set -- this is invisible notation so mathematicians don't need to understand the definition instance : has_coe_to_fun (affine_algebraic_set k n) := { F := λ _, _, coe := carrier } -- use `is_algebraic'` not `is_alegbraic` because the notation's right -- no "carrier". def is_algebraic (V : affine_algebraic_set k n) : ∃ S : set (mv_polynomial (fin n) k), (V : set _) = ⋂ f ∈ S, zeros f := affine_algebraic_set.is_algebraic' V -- Now some basic facts about affine algebraic subsets. /-- Two affine algebraic subsets with the same carrier are equal! -/ lemma ext {V W : affine_algebraic_set k n} : (V : set _) = W → V = W := begin intro h, cases V, cases W, simpa, -- TODO -- why no debugging output? end -- Do I want this instance? -- /-- We can talk about elements of affine algebraic subsets of kⁿ -/ -- instance : has_mem (fin n → k) (affine_algebraic_set k n) := -- ⟨λ x V, x ∈ V.carrier⟩ -- Computer scientists insist on using ≤ for any order relation such as ⊆ . -- It is some sort of problem with notation I think. instance : has_le (affine_algebraic_set k n) := ⟨λ V W, (V : set (fin n → k)) ⊆ W⟩ instance : partial_order (affine_algebraic_set k n) := { le := (≤), le_refl := λ _ _, id, le_trans := λ _ _ _, set.subset.trans, le_antisymm := λ U V hUV hVU, ext (set.subset.antisymm hUV hVU) } /-- Mathematicians want to talk about affine algebraic subsets of kⁿ being subsets of one another -/ instance : has_subset (affine_algebraic_set k n) := ⟨affine_algebraic_set.has_le.le⟩ end affine_algebraic_set
68383bd0933c1872faa0d814cc0e52f7f96b0322
4fa161becb8ce7378a709f5992a594764699e268
/src/ring_theory/euclidean_domain.lean
4bdd0076b21e7d17bc73333cae2d5bd60b6908c5
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
2,105
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import ring_theory.coprime import ring_theory.ideals noncomputable theory open_locale classical open euclidean_domain set ideal theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin apply le_antisymm, { refine span_le.2 (λ x, _), simp only [set.mem_singleton_iff, submodule.mem_coe, mem_span_pair], rintro rfl, exact ⟨gcd_a x y, gcd_b x y, by simp [gcd_eq_gcd_ab, mul_comm]⟩ }, { assume z , simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair, @eq_comm _ _ z] {contextual := tt}, assume a b h, exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _) (dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) } end theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := ⟨λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b * gcd_a x y, b * gcd_b x y, by rw [← hb, gcd_eq_gcd_ab, mul_comm x, mul_comm y, mul_add, mul_assoc, mul_assoc]⟩, λ ⟨a, b, h⟩, is_unit_iff_dvd_one.2 $ h ▸ dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left x y) _) (dvd_mul_of_dvd_right (gcd_dvd_right x y) _)⟩ theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, euclidean_domain.gcd_eq_zero_iff] end theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), unfreezeI, apply is_coprime_of_dvd, { rintro ⟨rfl, rfl⟩, simpa using h }, { rintro z nu nz ⟨w, rfl⟩ dy, refine h' (dvd.trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end
360aed9e70e8b33c2cf9c899bf1b3fddbc9b32b9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/field/basic.lean
8318abff932d40a30fd04ef86d76a51bf32658dc
[ "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
31,309
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import order.bounds.order_iso import algebra.field.basic import algebra.order.field.defs import algebra.group_power.order /-! # Lemmas about linear ordered (semi)fields -/ open function order_dual variables {ι α β : Type*} section linear_ordered_semifield variables [linear_ordered_semifield α] {a b c d e : α} {m n : ℤ} /-- `equiv.mul_left₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_left₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_left ha, ..equiv.mul_left₀ a ha.ne' } /-- `equiv.mul_right₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_right₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right ha, ..equiv.mul_right₀ a ha.ne' } /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from ⟨λ h, inv_inv a ▸ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] alias inv_pos ↔ _ inv_pos_of_pos @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] alias inv_nonneg ↔ _ inv_nonneg_of_nonneg @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a ▸ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a ▸ inv_lt_zero lemma one_div_nonneg : 0 ≤ 1 / a ↔ 0 ≤ a := inv_eq_one_div a ▸ inv_nonneg lemma one_div_nonpos : 1 / a ≤ 0 ↔ a ≤ 0 := inv_eq_one_div a ▸ inv_nonpos lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := by { rw div_eq_mul_inv, exact mul_pos ha (inv_pos.2 hb) } lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := by { rw div_eq_mul_inv, exact mul_nonneg ha (inv_nonneg.2 hb) } lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 := by { rw div_eq_mul_inv, exact mul_nonpos_of_nonpos_of_nonneg ha (inv_nonneg.2 hb) } lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 := by { rw div_eq_mul_inv, exact mul_nonpos_of_nonneg_of_nonpos ha (inv_nonpos.2 hb) } lemma zpow_nonneg (ha : 0 ≤ a) : ∀ n : ℤ, 0 ≤ a ^ n | (n : ℕ) := by { rw zpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma zpow_pos_of_pos (ha : 0 < a) : ∀ n : ℤ, 0 < a ^ n | (n : ℕ) := by { rw zpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm ▸ mul_le_mul_of_nonneg_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≤ c * b : mul_le_mul_of_nonneg_right h hb.le, λ h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma div_self_le_one (a : α) : a / a ≤ 1 := if h : a = 0 then by simp [h] else by simp [h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≤ b) (hc : 0 ≤ c) (h : a ≤ c * b) : a / b ≤ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≤ b) (hb : 0 ≤ b) : a / b ≤ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ ≤ b ↔ b⁻¹ ≤ a`. See also `inv_le_of_inv_le` for a one-sided implication with one fewer assumption. -/ lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv] lemma inv_le_of_inv_le (ha : 0 < a) (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := (inv_le ha ((inv_pos.2 ha).trans_le h)).1 h lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv] /-- See `inv_lt_inv_of_lt` for the implication from right-to-left with one fewer assumption. -/ lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt_inv_of_lt (hb : 0 < b) (h : b < a) : a⁻¹ < b⁻¹ := (inv_lt_inv (hb.trans h) hb).2 h /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ < b ↔ b⁻¹ < a`. See also `inv_lt_of_inv_lt` for a one-sided implication with one fewer assumption. -/ lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma inv_lt_of_inv_lt (ha : 0 < a) (h : a⁻¹ < b) : b⁻¹ < a := (inv_lt ha ((inv_pos.2 ha).trans h)).1 h lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt (zero_lt_one.trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv zero_lt_one h₁, inv_one] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rwa [inv_le (zero_lt_one.trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (h₂ : a ≤ 1) : 1 ≤ a⁻¹ := by rwa [le_inv zero_lt_one h₁, inv_one] lemma inv_lt_one_iff_of_pos (h₀ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv a ▸ one_lt_inv (inv_pos.2 h₀) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≤ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv a ▸ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≤ 1 ↔ a ≤ 0 ∨ 1 ≤ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≤ a⁻¹ ↔ 0 < a ∧ a ≤ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv a ▸ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ @[mono] lemma div_le_div_of_le (hc : 0 ≤ c) (h : a ≤ b) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end -- Not a `mono` lemma b/c `div_le_div` is strictly more general lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := div_le_div_of_le hc hab lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := by simp only [div_eq_mul_inv, mul_lt_mul_left ha, inv_lt_inv hb hc] lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] @[mono] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hc : 0 < c) (hb : 0 < b) (h : b < a) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma div_le_self (ha : 0 ≤ a) (hb : 1 ≤ b) : a / b ≤ a := by simpa only [div_one] using div_le_div_of_le_left ha zero_lt_one hb lemma div_lt_self (ha : 0 < a) (hb : 1 < b) : a / b < a := by simpa only [div_one] using div_lt_div_of_lt_left ha zero_lt_one hb lemma le_div_self (ha : 0 ≤ a) (hb₀ : 0 < b) (hb₁ : b ≤ 1) : a ≤ a / b := by simpa only [div_one] using div_le_div_of_le_left ha hb₀ hb₁ lemma one_le_div (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div zero_lt_one h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := by rwa [le_one_div zero_lt_one h1, one_div_one] /-! ### Results about halving. The equalities also hold in semifields of characteristic `0`. -/ /- TODO: Unify `add_halves` and `add_halves'` into a single lemma about `division_semiring` + `char_zero` -/ lemma add_halves (a : α) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] -- TODO: Generalize to `division_semiring` lemma add_self_div_two (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (zero_lt_two' α)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma half_le_self (ha_nonneg : 0 ≤ a) : a / 2 ≤ a := begin by_cases h0 : a = 0, { simp [h0], }, { rw ← ne.def at h0, exact (half_lt_self (lt_of_le_of_ne ha_nonneg h0.symm)).le, }, end lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma two_inv_lt_one : (2⁻¹ : α) < 1 := (one_div _).symm.trans_lt one_half_lt_one lemma left_lt_add_div_two : a < (a + b) / 2 ↔ a < b := by simp [lt_div_iff, mul_two] lemma add_div_two_lt_right : (a + b) / 2 < b ↔ a < b := by simp [div_lt_iff, mul_two] /-! ### Miscellaneous lemmas -/ lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≤ d) (hc : 0 < c) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≤ c / d) (he : 0 ≤ e) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_pos_mul_lt {a : α} (h : 0 < a) (b : α) : ∃ c : α, 0 < c ∧ b * c < a := begin have : 0 < a / max (b + 1) 1, from div_pos h (lt_max_iff.2 (or.inr zero_lt_one)), refine ⟨a / max (b + 1) 1, this, _⟩, rw [← lt_div_iff this, div_div_cancel' h.ne'], exact lt_max_iff.2 (or.inl $ lt_add_one _) end lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := begin haveI := @linear_order.decidable_le α _, simpa only [div_eq_mul_inv] using (monotone_mul_right_of_nonneg (inv_nonneg.2 hc)).comp hf end lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f) {c : α} (hc : 0 < c) : strict_mono (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := λ a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_left h _), calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = a₂ : add_self_div_two a₂⟩ } lemma min_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (λ x y, div_le_div_of_le hc) lemma max_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (λ x y, div_le_div_of_le hc) lemma one_div_strict_anti_on : strict_anti_on (λ x : α, 1 / x) (set.Ioi 0) := λ x x1 y y1 xy, (one_div_lt_one_div (set.mem_Ioi.mp y1) (set.mem_Ioi.mp x1)).mpr xy lemma one_div_pow_le_one_div_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : 1 / a ^ n ≤ 1 / a ^ m := by refine (one_div_le_one_div _ _).mpr (pow_le_pow a1 mn); exact pow_pos (zero_lt_one.trans_le a1) _ lemma one_div_pow_lt_one_div_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : 1 / a ^ n < 1 / a ^ m := by refine (one_div_lt_one_div _ _).mpr (pow_lt_pow a1 mn); exact pow_pos (trans zero_lt_one a1) _ lemma one_div_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_le_one_div_pow_of_le a1 lemma one_div_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_lt_one_div_pow_of_lt a1 lemma inv_strict_anti_on : strict_anti_on (λ x : α, x⁻¹) (set.Ioi 0) := λ x hx y hy xy, (inv_lt_inv hy hx).2 xy lemma inv_pow_le_inv_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : (a ^ n)⁻¹ ≤ (a ^ m)⁻¹ := by convert one_div_pow_le_one_div_pow_of_le a1 mn; simp lemma inv_pow_lt_inv_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : (a ^ n)⁻¹ < (a ^ m)⁻¹ := by convert one_div_pow_lt_one_div_pow_of_lt a1 mn; simp lemma inv_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, (a ^ n)⁻¹) := λ m n, inv_pow_le_inv_pow_of_le a1 lemma inv_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, (a ^ n)⁻¹) := λ m n, inv_pow_lt_inv_pow_of_lt a1 /-! ### Results about `is_lub` and `is_glb` -/ lemma is_glb.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_glb_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_glb_singleton }, end lemma is_glb.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha end linear_ordered_semifield section variables [linear_ordered_field α] {a b c d : α} {n : ℤ} /-! ### Lemmas about pos, nonneg, nonpos, neg -/ lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≤ a / b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by simp [division_def, mul_nonpos_iff] lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := div_pos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := div_neg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := div_neg_iff.2 $ or.inl ⟨ha, hb⟩ /-! ### Relating one division with another term -/ lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≤ a ↔ c * a ≤ b := by rw [mul_comm, div_le_iff_of_neg hc] lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul] lemma le_div_iff_of_neg' (hc : c < 0) : a ≤ b / c ↔ b ≤ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) /-! ### Relating two divisions -/ lemma div_le_div_of_nonpos_of_le (hc : c ≤ 0) (h : b ≤ a) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_div_right_of_neg hc /-! ### Relating one division and involving `1` -/ lemma one_le_div_of_neg (hb : b < 0) : 1 ≤ a / b ↔ a ≤ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≤ 1 ↔ b ≤ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≤ a / b ↔ 0 < b ∧ b ≤ a ∨ b < 0 ∧ a ≤ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≤ 1 ↔ 0 < b ∧ a ≤ b ∨ b = 0 ∨ b < 0 ∧ b ≤ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving -/ lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (zero_lt_two' α)] end /-- An inequality involving `2`. -/ lemma sub_one_div_inv_le_two (a2 : 2 ≤ a) : (1 - 1 / a)⁻¹ ≤ 2 := begin -- Take inverses on both sides to obtain `2⁻¹ ≤ 1 - 1 / a` refine (inv_le_inv_of_le (inv_pos.2 $ zero_lt_two' α) _).trans_eq (inv_inv (2 : α)), -- move `1 / a` to the left and `1 - 1 / 2 = 1 / 2` to the right to obtain `1 / a ≤ ⅟ 2` refine (le_sub_iff_add_le.2 (_ : _ + 2⁻¹ = _ ).le).trans ((sub_le_sub_iff_left 1).2 _), { -- show 2⁻¹ + 2⁻¹ = 1 exact (two_mul _).symm.trans (mul_inv_cancel two_ne_zero) }, { -- take inverses on both sides and use the assumption `2 ≤ a`. exact (one_div a).le.trans (inv_le_inv_of_le zero_lt_two a2) } end /-! ### Results about `is_lub` and `is_glb` -/ -- TODO: Generalize to `linear_ordered_semifield` lemma is_lub.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_lub_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_lub_singleton }, end -- TODO: Generalize to `linear_ordered_semifield` lemma is_lub.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha /-! ### Miscellaneous lemmmas -/ lemma mul_sub_mul_div_mul_neg_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] lemma mul_sub_mul_div_mul_nonpos_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) ≤ 0 ↔ a / c ≤ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma exists_add_lt_and_pos_of_lt (h : b < a) : ∃ c, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma le_of_forall_sub_le (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin contrapose! h, simpa only [and_comm ((0 : α) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ λ h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right_of_nonpos (hc : c ≤ 0) (a b : α) : min (a / c) (b / c) = (max a b) / c := eq.symm $ antitone.map_max $ λ x y, div_le_div_of_nonpos_of_le hc lemma max_div_div_right_of_nonpos (hc : c ≤ 0) (a b : α) : max (a / c) (b / c) = (min a b) / c := eq.symm $ antitone.map_min $ λ x y, div_le_div_of_nonpos_of_le hc lemma abs_inv (a : α) : |a⁻¹| = (|a|)⁻¹ := map_inv₀ (abs_hom : α →*₀ α) a lemma abs_div (a b : α) : |a / b| = |a| / |b| := map_div₀ (abs_hom : α →*₀ α) a b lemma abs_one_div (a : α) : |1 / a| = 1 / |a| := by rw [abs_div, abs_one] lemma pow_minus_two_nonneg : 0 ≤ a^(-2 : ℤ) := begin simp only [inv_nonneg, zpow_neg], change 0 ≤ a ^ ((2 : ℕ) : ℤ), rw zpow_coe_nat, apply sq_nonneg, end end
70d87571d3ddceda25f94804aacddc90fb4089d3
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Class.lean
a7e5d0aa7c4c545bc54edbce57f870dbf7043c71
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
6,133
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Attributes namespace Lean inductive ClassEntry | «class» (name : Name) (hasOutParam : Bool) | «instance» (name : Name) (ofClass : Name) -- TODO: remove after we remove old type class resolution namespace ClassEntry @[inline] def getName : ClassEntry → Name | «class» n _ => n | «instance» n _ => n def lt (a b : ClassEntry) : Bool := Name.quickLt a.getName b.getName end ClassEntry structure ClassState := (classToInstances : SMap Name (List Name) := SMap.empty) -- TODO: delete (hasOutParam : SMap Name Bool := SMap.empty) -- We should keep only this one (instances : SMap Name Unit := SMap.empty) -- TODO: delete namespace ClassState instance : Inhabited ClassState := ⟨{}⟩ def addEntry (s : ClassState) (entry : ClassEntry) : ClassState := match entry with | ClassEntry.«class» clsName hasOutParam => { hasOutParam := s.hasOutParam.insert clsName hasOutParam, .. s } | ClassEntry.«instance» instName clsName => { instances := s.instances.insert instName (), classToInstances := match s.classToInstances.find? clsName with | some insts => s.classToInstances.insert clsName (instName :: insts) | none => s.classToInstances.insert clsName [instName], .. s } def switch : ClassState → ClassState | ⟨m₁, m₂, m₃⟩ => ⟨m₁.switch, m₂.switch, m₃.switch⟩ end ClassState /- TODO: add support for scoped instances -/ def mkClassExtension : IO (SimplePersistentEnvExtension ClassEntry ClassState) := registerSimplePersistentEnvExtension { name := `classExt, addEntryFn := ClassState.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries ClassState.addEntry {} es).switch } @[init mkClassExtension] constant classExtension : SimplePersistentEnvExtension ClassEntry ClassState := arbitrary _ @[export lean_is_class] def isClass (env : Environment) (n : Name) : Bool := (classExtension.getState env).hasOutParam.contains n @[export lean_is_instance] def isInstance (env : Environment) (n : Name) : Bool := (classExtension.getState env).instances.contains n @[export lean_get_class_instances] def getClassInstances (env : Environment) (n : Name) : List Name := match (classExtension.getState env).classToInstances.find? n with | some insts => insts | none => [] @[export lean_has_out_params] def hasOutParams (env : Environment) (n : Name) : Bool := match (classExtension.getState env).hasOutParam.find? n with | some b => b | none => false @[export lean_is_out_param] def isOutParam (e : Expr) : Bool := e.isAppOfArity `outParam 1 /-- Auxiliary function for checking whether a class has `outParam`, and whether they are being correctly used. A regular (i.e., non `outParam`) must not depend on an `outParam`. Reason for this restriction: When performing type class resolution, we replace arguments that are `outParam`s with fresh metavariables. If regular parameters could depend on `outParam`s, then we would also have to replace them with fresh metavariables. Otherwise, the resulting expression could be type incorrect. This transformation would be counterintuitive to users since we would implicitly treat these regular parameters as `outParam`s. -/ private partial def checkOutParam : Nat → Array FVarId → Expr → Except String Bool | i, outParams, Expr.forallE _ d b _ => if isOutParam d then let fvarId := mkNameNum `_fvar outParams.size; let outParams := outParams.push fvarId; let fvar := mkFVar fvarId; let b := b.instantiate1 fvar; checkOutParam (i+1) outParams b else if d.hasAnyFVar (fun fvarId => outParams.contains fvarId) then Except.error $ "invalid class, parameter #" ++ toString i ++ " depends on `outParam`, but it is not an `outParam`" else checkOutParam (i+1) outParams b | i, outParams, e => pure (outParams.size > 0) def addClass (env : Environment) (clsName : Name) : Except String Environment := if isClass env clsName then Except.error ("class has already been declared '" ++ toString clsName ++ "'") else match env.find? clsName with | none => Except.error ("unknown declaration '" ++ toString clsName ++ "'") | some decl@(ConstantInfo.inductInfo _) => do b ← checkOutParam 1 #[] decl.type; Except.ok (classExtension.addEntry env (ClassEntry.«class» clsName b)) | some _ => Except.error ("invalid 'class', declaration '" ++ toString clsName ++ "' must be inductive datatype or structure") private def consumeNLambdas : Nat → Expr → Option Expr | 0, e => some e | i+1, Expr.lam _ _ b _ => consumeNLambdas i b | _, _ => none partial def getClassName (env : Environment) : Expr → Option Name | Expr.forallE _ _ b _ => getClassName b | e => do Expr.const c _ _ ← pure e.getAppFn | none; info ← env.find? c; match info.value? with | some val => do body ← consumeNLambdas e.getAppNumArgs val; getClassName body | none => if isClass env c then some c else none @[init] def registerClassAttr : IO Unit := registerBuiltinAttribute { name := `class, descr := "type class", add := fun env decl args persistent => do when args.hasArgs $ throw (IO.userError ("invalid attribute 'class', unexpected argument")); unless persistent $ throw (IO.userError ("invalid attribute 'class', must be persistent")); IO.ofExcept (addClass env decl) } -- TODO: delete @[export lean_add_instance_old] def addGlobalInstanceOld (env : Environment) (instName : Name) : Except String Environment := match env.find? instName with | none => Except.error ("unknown declaration '" ++ toString instName ++ "'") | some decl => match getClassName env decl.type with | none => Except.error ("invalid instance '" ++ toString instName ++ "', failed to retrieve class") | some clsName => Except.ok (classExtension.addEntry env (ClassEntry.«instance» instName clsName)) end Lean
ade3b326430cea6a9d24c6b8bb5b4b640ca3f4b1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/bounded_order.lean
629e1d1335d0d517bccc7ed41d3c5e2877ef8c03
[ "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
70,860
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 data.option.basic import logic.nontrivial import order.lattice import order.max import tactic.pi_instances /-! # ⊤ and ⊥, bounded lattices and variants This file defines top and bottom elements (greatest and least elements) of a type, the bounded variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides instances for `Prop` and `fun`. ## Main declarations * `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation. * `order_<top/bot> α`: Order with a top/bottom element. * `bounded_order α`: Order with a top and bottom element. * `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element. * `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a non distributive lattice, an element can have several complements. * `complemented_lattice α`: Typeclass stating that any element of a lattice has a complement. ## Common lattices * Distributive lattices with a bottom element. Notated by `[distrib_lattice α] [order_bot α]` It captures the properties of `disjoint` that are common to `generalized_boolean_algebra` and `distrib_lattice` when `order_bot`. * Bounded and distributive lattice. Notated by `[distrib_lattice α] [bounded_order α]`. Typical examples include `Prop` and `set α`. -/ open function order_dual set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} {γ δ : Type*} /-! ### Top, bottom element -/ /-- Typeclass for the `⊤` (`\top`) notation -/ @[notation_class] class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ @[notation_class] class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot @[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩ @[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩ attribute [pattern] has_bot.bot has_top.top /-- An order is an `order_top` if it has a greatest element. We state this using a data mixin, holding the value of `⊤` and the greatest element constraint. -/ @[ancestor has_top] class order_top (α : Type u) [has_le α] extends has_top α := (le_top : ∀ a : α, a ≤ ⊤) section order_top /-- An order is (noncomputably) either an `order_top` or a `no_order_top`. Use as `casesI bot_order_or_no_bot_order α`. -/ noncomputable def top_order_or_no_top_order (α : Type*) [has_le α] : psum (order_top α) (no_top_order α) := begin by_cases H : ∀ a : α, ∃ b, ¬ b ≤ a, { exact psum.inr ⟨H⟩ }, { push_neg at H, exact psum.inl ⟨_, classical.some_spec H⟩ } end section has_le variables [has_le α] [order_top α] {a : α} @[simp] lemma le_top : a ≤ ⊤ := order_top.le_top a @[simp] lemma is_top_top : is_top (⊤ : α) := λ _, le_top end has_le section preorder variables [preorder α] [order_top α] {a b : α} @[simp] lemma is_max_top : is_max (⊤ : α) := is_top_top.is_max @[simp] lemma not_top_lt : ¬ ⊤ < a := is_max_top.not_lt lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := (h.trans_le le_top).ne alias ne_top_of_lt ← has_lt.lt.ne_top end preorder variables [partial_order α] [order_top α] [preorder β] {f : α → β} {a b : α} @[simp] lemma is_max_iff_eq_top : is_max a ↔ a = ⊤ := ⟨λ h, h.eq_of_le le_top, λ h b _, h.symm ▸ le_top⟩ @[simp] lemma is_top_iff_eq_top : is_top a ↔ a = ⊤ := ⟨λ h, h.is_max.eq_of_le le_top, λ h b, h.symm ▸ le_top⟩ lemma not_is_max_iff_ne_top : ¬ is_max a ↔ a ≠ ⊤ := is_max_iff_eq_top.not lemma not_is_top_iff_ne_top : ¬ is_top a ↔ a ≠ ⊤ := is_top_iff_eq_top.not alias is_max_iff_eq_top ↔ is_max.eq_top _ alias is_top_iff_eq_top ↔ is_top.eq_top _ @[simp] lemma top_le_iff : ⊤ ≤ a ↔ a = ⊤ := le_top.le_iff_eq.trans eq_comm lemma top_unique (h : ⊤ ≤ a) : a = ⊤ := le_top.antisymm h lemma eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := top_le_iff.symm lemma eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_unique $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne @[simp] lemma not_lt_top_iff : ¬ a < ⊤ ↔ a = ⊤ := lt_top_iff_ne_top.not_left lemma eq_top_or_lt_top (a : α) : a = ⊤ ∨ a < ⊤ := le_top.eq_or_lt lemma ne.lt_top (h : a ≠ ⊤) : a < ⊤ := lt_top_iff_ne_top.mpr h lemma ne.lt_top' (h : ⊤ ≠ a) : a < ⊤ := h.symm.lt_top lemma ne_top_of_le_ne_top (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := (hab.trans_lt hb.lt_top).ne lemma strict_mono.apply_eq_top_iff (hf : strict_mono f) : f a = f ⊤ ↔ a = ⊤ := ⟨λ h, not_lt_top_iff.1 $ λ ha, (hf ha).ne h, congr_arg _⟩ lemma strict_anti.apply_eq_top_iff (hf : strict_anti f) : f a = f ⊤ ↔ a = ⊤ := ⟨λ h, not_lt_top_iff.1 $ λ ha, (hf ha).ne' h, congr_arg _⟩ variables [nontrivial α] lemma not_is_min_top : ¬ is_min (⊤ : α) := λ h, let ⟨a, ha⟩ := exists_ne (⊤ : α) in ha $ top_le_iff.1 $ h le_top end order_top lemma strict_mono.maximal_preimage_top [linear_order α] [preorder β] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.maximal_of_maximal_image (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {hA : partial_order α} (A : order_top α) {hB : partial_order α} (B : order_top α) (H : ∀ x y : α, (by haveI := hA; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} [partial_order α] {A B : order_top α} : A = B := begin have tt := order_top.ext_top A B (λ _ _, iff.rfl), casesI A with _ ha, casesI B with _ hb, congr, exact le_antisymm (hb _) (ha _) end /-- An order is an `order_bot` if it has a least element. We state this using a data mixin, holding the value of `⊥` and the least element constraint. -/ @[ancestor has_bot] class order_bot (α : Type u) [has_le α] extends has_bot α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot /-- An order is (noncomputably) either an `order_bot` or a `no_order_bot`. Use as `casesI bot_order_or_no_bot_order α`. -/ noncomputable def bot_order_or_no_bot_order (α : Type*) [has_le α] : psum (order_bot α) (no_bot_order α) := begin by_cases H : ∀ a : α, ∃ b, ¬ a ≤ b, { exact psum.inr ⟨H⟩ }, { push_neg at H, exact psum.inl ⟨_, classical.some_spec H⟩ } end section has_le variables [has_le α] [order_bot α] {a : α} @[simp] lemma bot_le : ⊥ ≤ a := order_bot.bot_le a @[simp] lemma is_bot_bot : is_bot (⊥ : α) := λ _, bot_le end has_le namespace order_dual variable (α) instance [has_bot α] : has_top αᵒᵈ := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot αᵒᵈ := ⟨(⊤ : α)⟩ instance [has_le α] [order_bot α] : order_top αᵒᵈ := { le_top := @bot_le α _ _, .. order_dual.has_top α } instance [has_le α] [order_top α] : order_bot αᵒᵈ := { bot_le := @le_top α _ _, .. order_dual.has_bot α } @[simp] lemma of_dual_bot [has_top α] : of_dual ⊥ = (⊤ : α) := rfl @[simp] lemma of_dual_top [has_bot α] : of_dual ⊤ = (⊥ : α) := rfl @[simp] lemma to_dual_bot [has_bot α] : to_dual (⊥ : α) = ⊤ := rfl @[simp] lemma to_dual_top [has_top α] : to_dual (⊤ : α) = ⊥ := rfl end order_dual section preorder variables [preorder α] [order_bot α] {a b : α} @[simp] lemma is_min_bot : is_min (⊥ : α) := is_bot_bot.is_min @[simp] lemma not_lt_bot : ¬ a < ⊥ := is_min_bot.not_lt lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := (bot_le.trans_lt h).ne' alias ne_bot_of_gt ← has_lt.lt.ne_bot end preorder variables [partial_order α] [order_bot α] [preorder β] {f : α → β} {a b : α} @[simp] lemma is_min_iff_eq_bot : is_min a ↔ a = ⊥ := ⟨λ h, h.eq_of_ge bot_le, λ h b _, h.symm ▸ bot_le⟩ @[simp] lemma is_bot_iff_eq_bot : is_bot a ↔ a = ⊥ := ⟨λ h, h.is_min.eq_of_ge bot_le, λ h b, h.symm ▸ bot_le⟩ lemma not_is_min_iff_ne_bot : ¬ is_min a ↔ a ≠ ⊥ := is_min_iff_eq_bot.not lemma not_is_bot_iff_ne_bot : ¬ is_bot a ↔ a ≠ ⊥ := is_bot_iff_eq_bot.not alias is_min_iff_eq_bot ↔ is_min.eq_bot _ alias is_bot_iff_eq_bot ↔ is_bot.eq_bot _ @[simp] lemma le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := bot_le.le_iff_eq lemma bot_unique (h : a ≤ ⊥) : a = ⊥ := h.antisymm bot_le lemma eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := le_bot_iff.symm lemma eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := bot_unique $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := bot_le.lt_iff_ne.trans ne_comm @[simp] lemma not_bot_lt_iff : ¬ ⊥ < a ↔ a = ⊥ := bot_lt_iff_ne_bot.not_left lemma eq_bot_or_bot_lt (a : α) : a = ⊥ ∨ ⊥ < a := bot_le.eq_or_gt lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ := (eq_bot_or_bot_lt a).resolve_right (h ⊥) lemma ne.bot_lt (h : a ≠ ⊥) : ⊥ < a := bot_lt_iff_ne_bot.mpr h lemma ne.bot_lt' (h : ⊥ ≠ a) : ⊥ < a := h.symm.bot_lt lemma ne_bot_of_le_ne_bot (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := (hb.bot_lt.trans_le hab).ne' lemma strict_mono.apply_eq_bot_iff (hf : strict_mono f) : f a = f ⊥ ↔ a = ⊥ := hf.dual.apply_eq_top_iff lemma strict_anti.apply_eq_bot_iff (hf : strict_anti f) : f a = f ⊥ ↔ a = ⊥ := hf.dual.apply_eq_top_iff variables [nontrivial α] lemma not_is_max_bot : ¬ is_max (⊥ : α) := @not_is_min_top αᵒᵈ _ _ _ end order_bot lemma strict_mono.minimal_preimage_bot [linear_order α] [partial_order β] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.minimal_of_minimal_image (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {hA : partial_order α} (A : order_bot α) {hB : partial_order α} (B : order_bot α) (H : ∀ x y : α, (by haveI := hA; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} [partial_order α] {A B : order_bot α} : A = B := begin have tt := order_bot.ext_bot A B (λ _ _, iff.rfl), casesI A with a ha, casesI B with b hb, congr, exact le_antisymm (ha _) (hb _) end section semilattice_sup_top variables [semilattice_sup α] [order_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top section semilattice_sup_bot variables [semilattice_sup α] [order_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot section semilattice_inf_top variables [semilattice_inf α] [order_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := @sup_eq_bot_iff αᵒᵈ _ _ _ _ end semilattice_inf_top section semilattice_inf_bot variables [semilattice_inf α] [order_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /-! ### Bounded order -/ /-- A bounded order describes an order `(≤)` with a top and bottom element, denoted `⊤` and `⊥` respectively. -/ @[ancestor order_top order_bot] class bounded_order (α : Type u) [has_le α] extends order_top α, order_bot α. instance (α : Type u) [has_le α] [bounded_order α] : bounded_order αᵒᵈ := { .. order_dual.order_top α, .. order_dual.order_bot α } theorem bounded_order.ext {α} [partial_order α] {A B : bounded_order α} : A = B := begin have ht : @bounded_order.to_order_top α _ A = @bounded_order.to_order_top α _ B := order_top.ext, have hb : @bounded_order.to_order_bot α _ A = @bounded_order.to_order_bot α _ B := order_bot.ext, casesI A, casesI B, injection ht with h, injection hb with h', convert rfl, { exact h.symm }, { exact h'.symm } end /-- Propositions form a distributive lattice. -/ instance Prop.distrib_lattice : distrib_lattice Prop := { sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := λ a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := λ a b c, or_and_distrib_left.2, ..Prop.partial_order } /-- Propositions form a bounded order. -/ instance Prop.bounded_order : bounded_order Prop := { top := true, le_top := λ a Ha, true.intro, bot := false, bot_le := @false.elim } instance Prop.le_is_total : is_total Prop (≤) := ⟨λ p q, by { change (p → q) ∨ (q → p), tauto! }⟩ noncomputable instance Prop.linear_order : linear_order Prop := by classical; exact lattice.to_linear_order Prop @[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl @[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl section logic /-! #### In this section we prove some properties about monotone and antitone operations on `Prop` -/ section preorder variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∧ q x) := λ a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∨ q x) := λ a b h, or.imp (m_p h) (m_q h) lemma monotone_le {x : α}: monotone ((≤) x) := λ y z h' h, h.trans h' lemma monotone_lt {x : α}: monotone ((<) x) := λ y z h' h, h.trans_le h' lemma antitone_le {x : α}: antitone (≤ x) := λ y z h' h, h'.trans h lemma antitone_lt {x : α}: antitone (< x) := λ y z h' h, h'.trans_lt h lemma monotone.forall {P : β → α → Prop} (hP : ∀ x, monotone (P x)) : monotone (λ y, ∀ x, P x y) := λ y y' hy h x, hP x hy $ h x lemma antitone.forall {P : β → α → Prop} (hP : ∀ x, antitone (P x)) : antitone (λ y, ∀ x, P x y) := λ y y' hy h x, hP x hy (h x) lemma monotone.ball {P : β → α → Prop} {s : set β} (hP : ∀ x ∈ s, monotone (P x)) : monotone (λ y, ∀ x ∈ s, P x y) := λ y y' hy h x hx, hP x hx hy (h x hx) lemma antitone.ball {P : β → α → Prop} {s : set β} (hP : ∀ x ∈ s, antitone (P x)) : antitone (λ y, ∀ x ∈ s, P x y) := λ y y' hy h x hx, hP x hx hy (h x hx) end preorder section semilattice_sup variables [semilattice_sup α] lemma exists_ge_and_iff_exists {P : α → Prop} {x₀ : α} (hP : monotone P) : (∃ x, x₀ ≤ x ∧ P x) ↔ ∃ x, P x := ⟨λ h, h.imp $ λ x h, h.2, λ ⟨x, hx⟩, ⟨x ⊔ x₀, le_sup_right, hP le_sup_left hx⟩⟩ end semilattice_sup section semilattice_inf variables [semilattice_inf α] lemma exists_le_and_iff_exists {P : α → Prop} {x₀ : α} (hP : antitone P) : (∃ x, x ≤ x₀ ∧ P x) ↔ ∃ x, P x := exists_ge_and_iff_exists hP.dual_left end semilattice_inf end logic /-! ### Function lattices -/ namespace pi variables {ι : Type*} {α' : ι → Type*} instance [Π i, has_bot (α' i)] : has_bot (Π i, α' i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply [Π i, has_bot (α' i)] (i : ι) : (⊥ : Π i, α' i) i = ⊥ := rfl lemma bot_def [Π i, has_bot (α' i)] : (⊥ : Π i, α' i) = λ i, ⊥ := rfl instance [Π i, has_top (α' i)] : has_top (Π i, α' i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply [Π i, has_top (α' i)] (i : ι) : (⊤ : Π i, α' i) i = ⊤ := rfl lemma top_def [Π i, has_top (α' i)] : (⊤ : Π i, α' i) = λ i, ⊤ := rfl instance [Π i, has_le (α' i)] [Π i, order_top (α' i)] : order_top (Π i, α' i) := { le_top := λ _ _, le_top, ..pi.has_top } instance [Π i, has_le (α' i)] [Π i, order_bot (α' i)] : order_bot (Π i, α' i) := { bot_le := λ _ _, bot_le, ..pi.has_bot } instance [Π i, has_le (α' i)] [Π i, bounded_order (α' i)] : bounded_order (Π i, α' i) := { ..pi.order_top, ..pi.order_bot } end pi section subsingleton variables [partial_order α] [bounded_order α] lemma eq_bot_of_bot_eq_top (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) lemma subsingleton_iff_bot_eq_top : (⊥ : α) = (⊤ : α) ↔ subsingleton α := ⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩ end subsingleton section lift /-- Pullback an `order_top`. -/ @[reducible] -- See note [reducible non-instances] def order_top.lift [has_le α] [has_top α] [has_le β] [order_top β] (f : α → β) (map_le : ∀ a b, f a ≤ f b → a ≤ b) (map_top : f ⊤ = ⊤) : order_top α := ⟨⊤, λ a, map_le _ _ $ by { rw map_top, exact le_top }⟩ /-- Pullback an `order_bot`. -/ @[reducible] -- See note [reducible non-instances] def order_bot.lift [has_le α] [has_bot α] [has_le β] [order_bot β] (f : α → β) (map_le : ∀ a b, f a ≤ f b → a ≤ b) (map_bot : f ⊥ = ⊥) : order_bot α := ⟨⊥, λ a, map_le _ _ $ by { rw map_bot, exact bot_le }⟩ /-- Pullback a `bounded_order`. -/ @[reducible] -- See note [reducible non-instances] def bounded_order.lift [has_le α] [has_top α] [has_bot α] [has_le β] [bounded_order β] (f : α → β) (map_le : ∀ a b, f a ≤ f b → a ≤ b) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) : bounded_order α := { ..order_top.lift f map_le map_top, ..order_bot.lift f map_le map_bot } end lift /-! ### `with_bot`, `with_top` -/ /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot variables {a b : α} meta instance [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance [has_repr α] : has_repr (with_bot α) := ⟨λ o, match o with | none := "⊥" | (some a) := "↑" ++ repr a end⟩ instance : has_coe_t α (with_bot α) := ⟨some⟩ instance : has_bot (with_bot α) := ⟨none⟩ meta instance {α : Type} [reflected _ α] [has_reflect α] : has_reflect (with_bot α) | ⊥ := `(⊥) | (a : α) := `(coe : α → with_bot α).subst `(a) instance : inhabited (with_bot α) := ⟨⊥⟩ lemma coe_injective : injective (coe : α → with_bot α) := option.some_injective _ @[norm_cast] lemma coe_inj : (a : with_bot α) = b ↔ a = b := option.some_inj lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl @[simp] lemma bot_ne_coe : ⊥ ≠ (a : with_bot α) . @[simp] lemma coe_ne_bot : (a : with_bot α) ≠ ⊥ . /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[simp] lemma rec_bot_coe_bot {C : with_bot α → Sort*} (d : C ⊥) (f : Π (a : α), C a) : @rec_bot_coe _ C d f ⊥ = d := rfl @[simp] lemma rec_bot_coe_coe {C : with_bot α → Sort*} (d : C ⊥) (f : Π (a : α), C a) (x : α) : @rec_bot_coe _ C d f ↑x = f x := rfl /-- Specialization of `option.get_or_else` to values in `with_bot α` that respects API boundaries. -/ def unbot' (d : α) (x : with_bot α) : α := rec_bot_coe d id x @[simp] lemma unbot'_bot {α} (d : α) : unbot' d ⊥ = d := rfl @[simp] lemma unbot'_coe {α} (d x : α) : unbot' d x = x := rfl @[norm_cast] lemma coe_eq_coe : (a : with_bot α) = b ↔ a = b := option.some_inj /-- Lift a map `f : α → β` to `with_bot α → with_bot β`. Implemented using `option.map`. -/ def map (f : α → β) : with_bot α → with_bot β := option.map f @[simp] lemma map_bot (f : α → β) : map f ⊥ = ⊥ := rfl @[simp] lemma map_coe (f : α → β) (a : α) : map f a = f a := rfl lemma map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂) (a : α) : map g₁ (map f₁ a) = map g₂ (map f₂ a) := option.map_comm h _ lemma ne_bot_iff_exists {x : with_bot α} : x ≠ ⊥ ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists /-- Deconstruct a `x : with_bot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/ def unbot : Π (x : with_bot α), x ≠ ⊥ → α | ⊥ h := absurd rfl h | (some x) h := x @[simp] lemma coe_unbot (x : with_bot α) (h : x ≠ ⊥) : (x.unbot h : with_bot α) = x := by { cases x, simpa using h, refl, } @[simp] lemma unbot_coe (x : α) (h : (x : with_bot α) ≠ ⊥ := coe_ne_bot) : (x : with_bot α).unbot h = x := rfl instance : can_lift (with_bot α) α := { coe := coe, cond := λ r, r ≠ ⊥, prf := λ x h, ⟨x.unbot h, coe_unbot _ _⟩ } section has_le variables [has_le α] @[priority 10] instance : has_le (with_bot α) := ⟨λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b⟩ @[simp] lemma some_le_some : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp, norm_cast] lemma coe_le_coe : (a : with_bot α) ≤ b ↔ a ≤ b := some_le_some @[simp] lemma none_le {a : with_bot α} : @has_le.le (with_bot α) _ none a := λ b h, option.no_confusion h instance : order_bot (with_bot α) := { bot_le := λ a, none_le, ..with_bot.has_bot } instance [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩ } instance [order_top α] : bounded_order (with_bot α) := { ..with_bot.order_top, ..with_bot.order_bot } lemma not_coe_le_bot (a : α) : ¬ (a : with_bot α) ≤ ⊥ := λ h, let ⟨b, hb, _⟩ := h _ rfl in option.not_mem_none _ hb lemma coe_le : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe lemma coe_le_iff : ∀ {x : with_bot α}, ↑a ≤ x ↔ ∃ b : α, x = b ∧ a ≤ b | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := iff_of_false (not_coe_le_bot _) $ by simp [none_eq_bot] lemma le_coe_iff : ∀ {x : with_bot α}, x ≤ b ↔ ∀ a, x = ↑a → a ≤ b | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_bot] protected lemma _root_.is_max.with_bot (h : is_max a) : is_max (a : with_bot α) | none _ := bot_le | (some b) hb := some_le_some.2 $ h $ some_le_some.1 hb end has_le section has_lt variables [has_lt α] @[priority 10] instance : has_lt (with_bot α) := ⟨λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b⟩ @[simp] lemma some_lt_some : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp, norm_cast] lemma coe_lt_coe : (a : with_bot α) < b ↔ a < b := some_lt_some @[simp] lemma none_lt_some (a : α) : @has_lt.lt (with_bot α) _ none (some a) := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe (a : α) : (⊥ : with_bot α) < a := none_lt_some a @[simp] lemma not_lt_none (a : with_bot α) : ¬ @has_lt.lt (with_bot α) _ a none := λ ⟨_, h, _⟩, option.not_mem_none _ h lemma lt_iff_exists_coe : ∀ {a b : with_bot α}, a < b ↔ ∃ p : α, b = p ∧ a < p | a (some b) := by simp [some_eq_coe, coe_eq_coe] | a none := iff_of_false (not_lt_none _) $ by simp [none_eq_bot] lemma lt_coe_iff : ∀ {x : with_bot α}, x < b ↔ ∀ a, x = ↑a → a < b | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_bot, bot_lt_coe] end has_lt instance [preorder α] : preorder (with_bot α) := { le := (≤), lt := (<), lt_iff_le_not_le := by { intros, cases a; cases b; simp [lt_iff_le_not_le]; simp [(<), (≤)] }, le_refl := λ o a ha, ⟨a, ha, le_rfl⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } lemma map_le_iff [preorder α] [preorder β] (f : α → β) (mono_iff : ∀ {a b}, f a ≤ f b ↔ a ≤ b) : ∀ (a b : with_bot α), a.map f ≤ b.map f ↔ a ≤ b | ⊥ _ := by simp only [map_bot, bot_le] | (a : α) ⊥ := by simp only [map_coe, map_bot, coe_ne_bot, not_coe_le_bot _] | (a : α) (b : α) := by simpa using mono_iff lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [has_le α] [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] lemma get_or_else_bot_lt_iff [partial_order α] [order_bot α] {a : with_bot α} {b : α} (ha : a ≠ ⊥) : a.get_or_else ⊥ < b ↔ a < b := begin obtain ⟨a, rfl⟩ := ne_bot_iff_exists.mp ha, simp only [lt_iff_le_and_ne, get_or_else_bot_le_iff, and.congr_right_iff], intro h, apply iff.not, simp only [with_bot.coe_eq_coe, option.get_or_else_coe, iff_self], end instance [semilattice_sup α] : semilattice_sup (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot, ..with_bot.partial_order } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl instance [semilattice_inf α] : semilattice_inf (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp [map] at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp [map] at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot, ..with_bot.partial_order } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl instance [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } instance decidable_le [has_le α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance is_total_le [has_le α] [is_total α (≤)] : is_total (with_bot α) (≤) := ⟨λ a b, match a, b with | none , _ := or.inl bot_le | _ , none := or.inr bot_le | some x, some y := (total_of (≤) x y).imp some_le_some.2 some_le_some.2 end⟩ instance [linear_order α] : linear_order (with_bot α) := lattice.to_linear_order _ @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := rfl @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := rfl lemma well_founded_lt [preorder α] (h : @well_founded α (<)) : @well_founded (with_bot α) (<) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance [has_lt α] [densely_ordered α] [no_min_order α] : densely_ordered (with_bot α) := ⟨ λ a b, match a, b with | a, none := λ h : a < ⊥, (not_lt_none _ h).elim | none, some b := λ h, let ⟨a, ha⟩ := exists_lt b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [preorder α] [densely_ordered α] [no_min_order α] {a b : with_bot α} : a < b ↔ ∃ x : α, a < ↑x ∧ ↑x < b := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.1 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ instance [has_le α] [no_top_order α] [nonempty α] : no_top_order (with_bot α) := ⟨begin apply rec_bot_coe, { exact ‹nonempty α›.elim (λ a, ⟨a, not_coe_le_bot a⟩) }, { intro a, obtain ⟨b, h⟩ := exists_not_le a, exact ⟨b, by rwa coe_le_coe⟩ } end⟩ instance [has_lt α] [no_max_order α] [nonempty α] : no_max_order (with_bot α) := ⟨begin apply with_bot.rec_bot_coe, { apply ‹nonempty α›.elim, exact λ a, ⟨a, with_bot.bot_lt_coe a⟩, }, { intro a, obtain ⟨b, ha⟩ := exists_gt a, exact ⟨b, with_bot.coe_lt_coe.mpr ha⟩, } end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top variables {a b : α} meta instance [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance [has_repr α] : has_repr (with_top α) := ⟨λ o, match o with | none := "⊤" | (some a) := "↑" ++ repr a end⟩ instance : has_coe_t α (with_top α) := ⟨some⟩ instance : has_top (with_top α) := ⟨none⟩ meta instance {α : Type} [reflected _ α] [has_reflect α] : has_reflect (with_top α) | ⊤ := `(⊤) | (a : α) := `(coe : α → with_top α).subst `(a) instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl @[simp] lemma top_ne_coe : ⊤ ≠ (a : with_top α) . @[simp] lemma coe_ne_top : (a : with_top α) ≠ ⊤ . /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[simp] lemma rec_top_coe_top {C : with_top α → Sort*} (d : C ⊤) (f : Π (a : α), C a) : @rec_top_coe _ C d f ⊤ = d := rfl @[simp] lemma rec_top_coe_coe {C : with_top α → Sort*} (d : C ⊤) (f : Π (a : α), C a) (x : α) : @rec_top_coe _ C d f ↑x = f x := rfl /-- `with_top.to_dual` is the equivalence sending `⊤` to `⊥` and any `a : α` to `to_dual a : αᵒᵈ`. See `with_top.to_dual_bot_equiv` for the related order-iso. -/ protected def to_dual : with_top α ≃ with_bot αᵒᵈ := equiv.refl _ /-- `with_top.of_dual` is the equivalence sending `⊤` to `⊥` and any `a : αᵒᵈ` to `of_dual a : α`. See `with_top.to_dual_bot_equiv` for the related order-iso. -/ protected def of_dual : with_top αᵒᵈ ≃ with_bot α := equiv.refl _ /-- `with_bot.to_dual` is the equivalence sending `⊥` to `⊤` and any `a : α` to `to_dual a : αᵒᵈ`. See `with_bot.to_dual_top_equiv` for the related order-iso. -/ protected def _root_.with_bot.to_dual : with_bot α ≃ with_top αᵒᵈ := equiv.refl _ /-- `with_bot.of_dual` is the equivalence sending `⊥` to `⊤` and any `a : αᵒᵈ` to `of_dual a : α`. See `with_bot.to_dual_top_equiv` for the related order-iso. -/ protected def _root_.with_bot.of_dual : with_bot αᵒᵈ ≃ with_top α := equiv.refl _ @[simp] lemma to_dual_symm_apply (a : with_bot αᵒᵈ) : with_top.to_dual.symm a = a.of_dual := rfl @[simp] lemma of_dual_symm_apply (a : with_bot α) : with_top.of_dual.symm a = a.to_dual := rfl @[simp] lemma to_dual_apply_top : with_top.to_dual (⊤ : with_top α) = ⊥ := rfl @[simp] lemma of_dual_apply_top : with_top.of_dual (⊤ : with_top α) = ⊥ := rfl @[simp] lemma to_dual_apply_coe (a : α) : with_top.to_dual (a : with_top α) = to_dual a := rfl @[simp] lemma of_dual_apply_coe (a : αᵒᵈ) : with_top.of_dual (a : with_top αᵒᵈ) = of_dual a := rfl /-- Specialization of `option.get_or_else` to values in `with_top α` that respects API boundaries. -/ def untop' (d : α) (x : with_top α) : α := rec_top_coe d id x @[simp] lemma untop'_top {α} (d : α) : untop' d ⊤ = d := rfl @[simp] lemma untop'_coe {α} (d x : α) : untop' d x = x := rfl @[norm_cast] lemma coe_eq_coe : (a : with_top α) = b ↔ a = b := option.some_inj /-- Lift a map `f : α → β` to `with_top α → with_top β`. Implemented using `option.map`. -/ def map (f : α → β) : with_top α → with_top β := option.map f @[simp] lemma map_top (f : α → β) : map f ⊤ = ⊤ := rfl @[simp] lemma map_coe (f : α → β) (a : α) : map f a = f a := rfl lemma map_comm {f₁ : α → β} {f₂ : α → γ} {g₁ : β → δ} {g₂ : γ → δ} (h : g₁ ∘ f₁ = g₂ ∘ f₂) (a : α) : map g₁ (map f₁ a) = map g₂ (map f₂ a) := option.map_comm h _ lemma map_to_dual (f : αᵒᵈ → βᵒᵈ) (a : with_bot α) : map f (with_bot.to_dual a) = a.map (to_dual ∘ f) := rfl lemma map_of_dual (f : α → β) (a : with_bot αᵒᵈ) : map f (with_bot.of_dual a) = a.map (of_dual ∘ f) := rfl lemma to_dual_map (f : α → β) (a : with_top α) : with_top.to_dual (map f a) = with_bot.map (to_dual ∘ f ∘ of_dual) a.to_dual := rfl lemma of_dual_map (f : αᵒᵈ → βᵒᵈ) (a : with_top αᵒᵈ) : with_top.of_dual (map f a) = with_bot.map (of_dual ∘ f ∘ to_dual) a.of_dual := rfl lemma ne_top_iff_exists {x : with_top α} : x ≠ ⊤ ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists /-- Deconstruct a `x : with_top α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/ def untop : Π (x : with_top α), x ≠ ⊤ → α := with_bot.unbot @[simp] lemma coe_untop (x : with_top α) (h : x ≠ ⊤) : (x.untop h : with_top α) = x := with_bot.coe_unbot x h @[simp] lemma untop_coe (x : α) (h : (x : with_top α) ≠ ⊤ := coe_ne_top) : (x : with_top α).untop h = x := rfl instance : can_lift (with_top α) α := { coe := coe, cond := λ r, r ≠ ⊤, prf := λ x h, ⟨x.untop h, coe_untop _ _⟩ } section has_le variables [has_le α] @[priority 10] instance : has_le (with_top α) := ⟨λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a⟩ lemma to_dual_le_iff {a : with_top α} {b : with_bot αᵒᵈ} : with_top.to_dual a ≤ b ↔ with_bot.of_dual b ≤ a := iff.rfl lemma le_to_dual_iff {a : with_bot αᵒᵈ} {b : with_top α} : a ≤ with_top.to_dual b ↔ b ≤ with_bot.of_dual a := iff.rfl @[simp] lemma to_dual_le_to_dual_iff {a b : with_top α} : with_top.to_dual a ≤ with_top.to_dual b ↔ b ≤ a := iff.rfl lemma of_dual_le_iff {a : with_top αᵒᵈ} {b : with_bot α} : with_top.of_dual a ≤ b ↔ with_bot.to_dual b ≤ a := iff.rfl lemma le_of_dual_iff {a : with_bot α} {b : with_top αᵒᵈ} : a ≤ with_top.of_dual b ↔ b ≤ with_bot.to_dual a := iff.rfl @[simp] lemma of_dual_le_of_dual_iff {a b : with_top αᵒᵈ} : with_top.of_dual a ≤ with_top.of_dual b ↔ b ≤ a := iff.rfl @[simp, norm_cast] lemma coe_le_coe : (a : with_top α) ≤ b ↔ a ≤ b := by simp only [←to_dual_le_to_dual_iff, to_dual_apply_coe, with_bot.coe_le_coe, to_dual_le_to_dual] @[simp] lemma some_le_some : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe @[simp] lemma le_none {a : with_top α} : @has_le.le (with_top α) _ a none := to_dual_le_to_dual_iff.mp with_bot.none_le instance : order_top (with_top α) := { le_top := λ a, le_none, .. with_top.has_top } instance [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩ } instance [order_bot α] : bounded_order (with_top α) := { ..with_top.order_top, ..with_top.order_bot } lemma not_top_le_coe (a : α) : ¬ (⊤ : with_top α) ≤ ↑a := with_bot.not_coe_le_bot (to_dual a) lemma le_coe : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe lemma le_coe_iff {x : with_top α} : x ≤ b ↔ ∃ a : α, x = a ∧ a ≤ b := by simpa [←to_dual_le_to_dual_iff, with_bot.coe_le_iff] lemma coe_le_iff {x : with_top α} : ↑a ≤ x ↔ ∀ b, x = ↑b → a ≤ b := begin simp only [←to_dual_le_to_dual_iff, to_dual_apply_coe, with_bot.le_coe_iff, order_dual.forall, to_dual_le_to_dual], exact forall₂_congr (λ _ _, iff.rfl) end protected lemma _root_.is_min.with_top (h : is_min a) : is_min (a : with_top α) := begin -- defeq to is_max_to_dual_iff.mp (is_max.with_bot _), but that breaks API boundary intros _ hb, rw ←to_dual_le_to_dual_iff at hb, simpa [to_dual_le_iff] using (is_max.with_bot h : is_max (to_dual a : with_bot αᵒᵈ)) hb end end has_le section has_lt variables [has_lt α] @[priority 10] instance : has_lt (with_top α) := ⟨λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a⟩ lemma to_dual_lt_iff {a : with_top α} {b : with_bot αᵒᵈ} : with_top.to_dual a < b ↔ with_bot.of_dual b < a := iff.rfl lemma lt_to_dual_iff {a : with_bot αᵒᵈ} {b : with_top α} : a < with_top.to_dual b ↔ b < with_bot.of_dual a := iff.rfl @[simp] lemma to_dual_lt_to_dual_iff {a b : with_top α} : with_top.to_dual a < with_top.to_dual b ↔ b < a := iff.rfl lemma of_dual_lt_iff {a : with_top αᵒᵈ} {b : with_bot α} : with_top.of_dual a < b ↔ with_bot.to_dual b < a := iff.rfl lemma lt_of_dual_iff {a : with_bot α} {b : with_top αᵒᵈ} : a < with_top.of_dual b ↔ b < with_bot.to_dual a := iff.rfl @[simp] lemma of_dual_lt_of_dual_iff {a b : with_top αᵒᵈ} : with_top.of_dual a < with_top.of_dual b ↔ b < a := iff.rfl end has_lt end with_top namespace with_bot @[simp] lemma to_dual_symm_apply (a : with_top αᵒᵈ) : with_bot.to_dual.symm a = a.of_dual := rfl @[simp] lemma of_dual_symm_apply (a : with_top α) : with_bot.of_dual.symm a = a.to_dual := rfl @[simp] lemma to_dual_apply_bot : with_bot.to_dual (⊥ : with_bot α) = ⊤ := rfl @[simp] lemma of_dual_apply_bot : with_bot.of_dual (⊥ : with_bot α) = ⊤ := rfl @[simp] lemma to_dual_apply_coe (a : α) : with_bot.to_dual (a : with_bot α) = to_dual a := rfl @[simp] lemma of_dual_apply_coe (a : αᵒᵈ) : with_bot.of_dual (a : with_bot αᵒᵈ) = of_dual a := rfl lemma map_to_dual (f : αᵒᵈ → βᵒᵈ) (a : with_top α) : with_bot.map f (with_top.to_dual a) = a.map (to_dual ∘ f) := rfl lemma map_of_dual (f : α → β) (a : with_top αᵒᵈ) : with_bot.map f (with_top.of_dual a) = a.map (of_dual ∘ f) := rfl lemma to_dual_map (f : α → β) (a : with_bot α) : with_bot.to_dual (with_bot.map f a) = map (to_dual ∘ f ∘ of_dual) a.to_dual := rfl lemma of_dual_map (f : αᵒᵈ → βᵒᵈ) (a : with_bot αᵒᵈ) : with_bot.of_dual (with_bot.map f a) = map (of_dual ∘ f ∘ to_dual) a.of_dual := rfl section has_le variables [has_le α] {a b : α} lemma to_dual_le_iff {a : with_bot α} {b : with_top αᵒᵈ} : with_bot.to_dual a ≤ b ↔ with_top.of_dual b ≤ a := iff.rfl lemma le_to_dual_iff {a : with_top αᵒᵈ} {b : with_bot α} : a ≤ with_bot.to_dual b ↔ b ≤ with_top.of_dual a := iff.rfl @[simp] lemma to_dual_le_to_dual_iff {a b : with_bot α} : with_bot.to_dual a ≤ with_bot.to_dual b ↔ b ≤ a := iff.rfl lemma of_dual_le_iff {a : with_bot αᵒᵈ} {b : with_top α} : with_bot.of_dual a ≤ b ↔ with_top.to_dual b ≤ a := iff.rfl lemma le_of_dual_iff {a : with_top α} {b : with_bot αᵒᵈ} : a ≤ with_bot.of_dual b ↔ b ≤ with_top.to_dual a := iff.rfl @[simp] lemma of_dual_le_of_dual_iff {a b : with_bot αᵒᵈ} : with_bot.of_dual a ≤ with_bot.of_dual b ↔ b ≤ a := iff.rfl end has_le section has_lt variables [has_lt α] {a b : α} lemma to_dual_lt_iff {a : with_bot α} {b : with_top αᵒᵈ} : with_bot.to_dual a < b ↔ with_top.of_dual b < a := iff.rfl lemma lt_to_dual_iff {a : with_top αᵒᵈ} {b : with_bot α} : a < with_bot.to_dual b ↔ b < with_top.of_dual a := iff.rfl @[simp] lemma to_dual_lt_to_dual_iff {a b : with_bot α} : with_bot.to_dual a < with_bot.to_dual b ↔ b < a := iff.rfl lemma of_dual_lt_iff {a : with_bot αᵒᵈ} {b : with_top α} : with_bot.of_dual a < b ↔ with_top.to_dual b < a := iff.rfl lemma lt_of_dual_iff {a : with_top α} {b : with_bot αᵒᵈ} : a < with_bot.of_dual b ↔ b < with_top.to_dual a := iff.rfl @[simp] lemma of_dual_lt_of_dual_iff {a b : with_bot αᵒᵈ} : with_bot.of_dual a < with_bot.of_dual b ↔ b < a := iff.rfl end has_lt end with_bot namespace with_top section has_lt variables [has_lt α] {a b : α} @[simp, norm_cast] lemma coe_lt_coe : (a : with_top α) < b ↔ a < b := by simp only [←to_dual_lt_to_dual_iff, to_dual_apply_coe, with_bot.coe_lt_coe, to_dual_lt_to_dual] @[simp] lemma some_lt_some : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := coe_lt_coe lemma coe_lt_top (a : α) : (a : with_top α) < ⊤ := by simpa [←to_dual_lt_to_dual_iff] using with_bot.bot_lt_coe _ @[simp] lemma some_lt_none (a : α) : @has_lt.lt (with_top α) _ (some a) none := coe_lt_top a @[simp] lemma not_none_lt (a : with_top α) : ¬ @has_lt.lt (with_top α) _ none a := begin rw [←to_dual_lt_to_dual_iff], exact with_bot.not_lt_none _ end lemma lt_iff_exists_coe {a b : with_top α} : a < b ↔ ∃ p : α, a = p ∧ ↑p < b := begin rw [←to_dual_lt_to_dual_iff, with_bot.lt_iff_exists_coe, order_dual.exists], exact exists_congr (λ _, and_congr_left' iff.rfl) end lemma coe_lt_iff {x : with_top α} : ↑a < x ↔ ∀ b, x = ↑b → a < b := begin simp only [←to_dual_lt_to_dual_iff, with_bot.lt_coe_iff, to_dual_apply_coe, order_dual.forall, to_dual_lt_to_dual], exact forall₂_congr (λ _ _, iff.rfl) end end has_lt instance [preorder α] : preorder (with_top α) := { le := (≤), lt := (<), lt_iff_le_not_le := by simp [←to_dual_lt_to_dual_iff, lt_iff_le_not_le], le_refl := λ _, to_dual_le_to_dual_iff.mp le_rfl, le_trans := λ _ _ _, by { simp_rw [←to_dual_le_to_dual_iff], exact function.swap le_trans } } instance [partial_order α] : partial_order (with_top α) := { le_antisymm := λ _ _, by { simp_rw [←to_dual_le_to_dual_iff], exact function.swap le_antisymm }, .. with_top.preorder } lemma map_le_iff [preorder α] [preorder β] (f : α → β) (a b : with_top α) (mono_iff : ∀ {a b}, f a ≤ f b ↔ a ≤ b) : a.map f ≤ b.map f ↔ a ≤ b := begin rw [←to_dual_le_to_dual_iff, to_dual_map, to_dual_map, with_bot.map_le_iff, to_dual_le_to_dual_iff], simp [mono_iff] end instance [semilattice_inf α] : semilattice_inf (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.partial_order } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance [semilattice_sup α] : semilattice_sup (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp [map] at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp [map] at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.partial_order } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } instance decidable_le [has_le α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ _ _, decidable_of_decidable_of_iff (with_bot.decidable_le _ _) (to_dual_le_to_dual_iff) instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ _ _, decidable_of_decidable_of_iff (with_bot.decidable_lt _ _) (to_dual_lt_to_dual_iff) instance is_total_le [has_le α] [is_total α (≤)] : is_total (with_top α) (≤) := ⟨λ _ _, by { simp_rw ←to_dual_le_to_dual_iff, exact total_of _ _ _ }⟩ instance [linear_order α] : linear_order (with_top α) := lattice.to_linear_order _ @[simp, norm_cast] lemma coe_min [linear_order α] (x y : α) : (↑(min x y) : with_top α) = min x y := rfl @[simp, norm_cast] lemma coe_max [linear_order α] (x y : α) : (↑(max x y) : with_top α) = max x y := rfl lemma well_founded_lt [preorder α] (h : @well_founded α (<)) : @well_founded (with_top α) (<) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ lemma well_founded_gt [preorder α] (h : @well_founded α (>)) : @well_founded (with_top α) (>) := ⟨λ a, begin -- ideally, use rel_hom_class.acc, but that is defined later have : acc (<) a.to_dual := well_founded.apply (with_bot.well_founded_lt h) _, revert this, generalize ha : a.to_dual = b, intro ac, induction ac with _ H IH generalizing a, subst ha, exact ⟨_, λ a' h, IH (a'.to_dual) (to_dual_lt_to_dual.mpr h) _ rfl⟩ end⟩ lemma _root_.with_bot.well_founded_gt [preorder α] (h : @well_founded α (>)) : @well_founded (with_bot α) (>) := ⟨λ a, begin -- ideally, use rel_hom_class.acc, but that is defined later have : acc (<) a.to_dual := well_founded.apply (with_top.well_founded_lt h) _, revert this, generalize ha : a.to_dual = b, intro ac, induction ac with _ H IH generalizing a, subst ha, exact ⟨_, λ a' h, IH (a'.to_dual) (to_dual_lt_to_dual.mpr h) _ rfl⟩ end⟩ instance trichotomous.lt [preorder α] [is_trichotomous α (<)] : is_trichotomous (with_top α) (<) := ⟨begin rintro (a | _) (b | _), iterate 3 { simp }, simpa [option.some_inj] using @trichotomous _ (<) _ a b end⟩ instance is_well_order.lt [preorder α] [h : is_well_order α (<)] : is_well_order (with_top α) (<) := { wf := well_founded_lt h.wf } instance trichotomous.gt [preorder α] [is_trichotomous α (>)] : is_trichotomous (with_top α) (>) := ⟨begin rintro (a | _) (b | _), iterate 3 { simp }, simpa [option.some_inj] using @trichotomous _ (>) _ a b end⟩ instance is_well_order.gt [preorder α] [h : is_well_order α (>)] : is_well_order (with_top α) (>) := { wf := well_founded_gt h.wf } instance _root_.with_bot.trichotomous.lt [preorder α] [h : is_trichotomous α (<)] : is_trichotomous (with_bot α) (<) := @with_top.trichotomous.gt αᵒᵈ _ h instance _root_.with_bot.is_well_order.lt [preorder α] [h : is_well_order α (<)] : is_well_order (with_bot α) (<) := @with_top.is_well_order.gt αᵒᵈ _ h instance _root_.with_bot.trichotomous.gt [preorder α] [h : is_trichotomous α (>)] : is_trichotomous (with_bot α) (>) := @with_top.trichotomous.lt αᵒᵈ _ h instance _root_.with_bot.is_well_order.gt [preorder α] [h : is_well_order α (>)] : is_well_order (with_bot α) (>) := @with_top.is_well_order.lt αᵒᵈ _ h instance [has_lt α] [densely_ordered α] [no_max_order α] : densely_ordered (with_top α) := order_dual.densely_ordered (with_bot αᵒᵈ) lemma lt_iff_exists_coe_btwn [preorder α] [densely_ordered α] [no_max_order α] {a b : with_top α} : a < b ↔ ∃ x : α, a < ↑x ∧ ↑x < b := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ instance [has_le α] [no_bot_order α] [nonempty α] : no_bot_order (with_top α) := order_dual.no_bot_order (with_bot αᵒᵈ) instance [has_lt α] [no_min_order α] [nonempty α] : no_min_order (with_top α) := order_dual.no_min_order (with_bot αᵒᵈ) end with_top section mono variables [preorder α] [preorder β] {f : α → β} protected lemma monotone.with_bot_map (hf : monotone f) : monotone (with_bot.map f) | ⊥ _ h := bot_le | (a : α) ⊥ h := (with_bot.not_coe_le_bot _ h).elim | (a : α) (b : α) h := with_bot.coe_le_coe.2 (hf (with_bot.coe_le_coe.1 h)) protected lemma monotone.with_top_map (hf : monotone f) : monotone (with_top.map f) := hf.dual.with_bot_map.dual protected lemma strict_mono.with_bot_map (hf : strict_mono f) : strict_mono (with_bot.map f) | ⊥ (a : α) h := with_bot.bot_lt_coe _ | (a : α) (b : α) h := with_bot.coe_lt_coe.mpr (hf $ with_bot.coe_lt_coe.mp h) protected lemma strict_mono.with_top_map (hf : strict_mono f) : strict_mono (with_top.map f) := hf.dual.with_bot_map.dual end mono /-! ### Subtype, order dual, product lattices -/ namespace subtype variables {p : α → Prop} /-- A subtype remains a `⊥`-order if the property holds at `⊥`. -/ @[reducible] -- See note [reducible non-instances] protected def order_bot [has_le α] [order_bot α] (hbot : p ⊥) : order_bot {x : α // p x} := { bot := ⟨⊥, hbot⟩, bot_le := λ _, bot_le } /-- A subtype remains a `⊤`-order if the property holds at `⊤`. -/ @[reducible] -- See note [reducible non-instances] protected def order_top [has_le α] [order_top α] (htop : p ⊤) : order_top {x : α // p x} := { top := ⟨⊤, htop⟩, le_top := λ _, le_top } /-- A subtype remains a bounded order if the property holds at `⊥` and `⊤`. -/ @[reducible] -- See note [reducible non-instances] protected def bounded_order [has_le α] [bounded_order α] (hbot : p ⊥) (htop : p ⊤) : bounded_order (subtype p) := { ..subtype.order_top htop, ..subtype.order_bot hbot } variables [partial_order α] @[simp] lemma mk_bot [order_bot α] [order_bot (subtype p)] (hbot : p ⊥) : mk ⊥ hbot = ⊥ := le_bot_iff.1 $ coe_le_coe.1 bot_le @[simp] lemma mk_top [order_top α] [order_top (subtype p)] (htop : p ⊤) : mk ⊤ htop = ⊤ := top_le_iff.1 $ coe_le_coe.1 le_top lemma coe_bot [order_bot α] [order_bot (subtype p)] (hbot : p ⊥) : ((⊥ : subtype p) : α) = ⊥ := congr_arg coe (mk_bot hbot).symm lemma coe_top [order_top α] [order_top (subtype p)] (htop : p ⊤) : ((⊤ : subtype p) : α) = ⊤ := congr_arg coe (mk_top htop).symm @[simp] lemma coe_eq_bot_iff [order_bot α] [order_bot (subtype p)] (hbot : p ⊥) {x : {x // p x}} : (x : α) = ⊥ ↔ x = ⊥ := by rw [←coe_bot hbot, ext_iff] @[simp] lemma coe_eq_top_iff [order_top α] [order_top (subtype p)] (htop : p ⊤) {x : {x // p x}} : (x : α) = ⊤ ↔ x = ⊤ := by rw [←coe_top htop, ext_iff] @[simp] lemma mk_eq_bot_iff [order_bot α] [order_bot (subtype p)] (hbot : p ⊥) {x : α} (hx : p x) : (⟨x, hx⟩ : subtype p) = ⊥ ↔ x = ⊥ := (coe_eq_bot_iff hbot).symm @[simp] lemma mk_eq_top_iff [order_top α] [order_top (subtype p)] (htop : p ⊤) {x : α} (hx : p x) : (⟨x, hx⟩ : subtype p) = ⊤ ↔ x = ⊤ := (coe_eq_top_iff htop).symm end subtype namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [has_le α] [has_le β] [order_top α] [order_top β] : order_top (α × β) := { le_top := λ a, ⟨le_top, le_top⟩, .. prod.has_top α β } instance [has_le α] [has_le β] [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := λ a, ⟨bot_le, bot_le⟩, .. prod.has_bot α β } instance [has_le α] [has_le β] [bounded_order α] [bounded_order β] : bounded_order (α × β) := { .. prod.order_top α β, .. prod.order_bot α β } end prod section linear_order variables [linear_order α] -- `simp` can prove these, so they shouldn't be simp-lemmas. lemma min_bot_left [order_bot α] (a : α) : min ⊥ a = ⊥ := bot_inf_eq lemma max_top_left [order_top α] (a : α) : max ⊤ a = ⊤ := top_sup_eq lemma min_top_left [order_top α] (a : α) : min ⊤ a = a := top_inf_eq lemma max_bot_left [order_bot α] (a : α) : max ⊥ a = a := bot_sup_eq lemma min_top_right [order_top α] (a : α) : min a ⊤ = a := inf_top_eq lemma max_bot_right [order_bot α] (a : α) : max a ⊥ = a := sup_bot_eq lemma min_bot_right [order_bot α] (a : α) : min a ⊥ = ⊥ := inf_bot_eq lemma max_top_right [order_top α] (a : α) : max a ⊤ = ⊤ := sup_top_eq @[simp] lemma min_eq_bot [order_bot α] {a b : α} : min a b = ⊥ ↔ a = ⊥ ∨ b = ⊥ := by simp only [←inf_eq_min, ←le_bot_iff, inf_le_iff] @[simp] lemma max_eq_top [order_top α] {a b : α} : max a b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := @min_eq_bot αᵒᵈ _ _ a b @[simp] lemma max_eq_bot [order_bot α] {a b : α} : max a b = ⊥ ↔ a = ⊥ ∧ b = ⊥ := sup_eq_bot_iff @[simp] lemma min_eq_top [order_top α] {a b : α} : min a b = ⊤ ↔ a = ⊤ ∧ b = ⊤ := inf_eq_top_iff end linear_order /-! ### Disjointness and complements -/ section disjoint section semilattice_inf_bot variables [semilattice_inf α] [order_bot α] {a b c d : α} /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ lemma disjoint_iff : disjoint a b ↔ a ⊓ b = ⊥ := le_bot_iff lemma disjoint.eq_bot : disjoint a b → a ⊓ b = ⊥ := bot_unique lemma disjoint.comm : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] lemma disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm lemma disjoint_assoc : disjoint (a ⊓ b) c ↔ disjoint a (b ⊓ c) := by rw [disjoint, disjoint, inf_assoc] lemma disjoint_left_comm : disjoint a (b ⊓ c) ↔ disjoint b (a ⊓ c) := by simp_rw [disjoint, inf_left_comm] lemma disjoint_right_comm : disjoint (a ⊓ b) c ↔ disjoint (a ⊓ c) b := by simp_rw [disjoint, inf_right_comm] @[simp] lemma disjoint_bot_left : disjoint ⊥ a := inf_le_left @[simp] lemma disjoint_bot_right : disjoint a ⊥ := inf_le_right lemma disjoint.mono (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans $ inf_le_inf h₁ h₂ lemma disjoint.mono_left (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h le_rfl lemma disjoint.mono_right : b ≤ c → disjoint a c → disjoint a b := disjoint.mono le_rfl variables (c) lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b := h.mono_left inf_le_left lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b := h.mono_left inf_le_right lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) := h.mono_right inf_le_left lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) := h.mono_right inf_le_right variables {c} @[simp] lemma disjoint_self : disjoint a a ↔ a = ⊥ := by simp [disjoint] /- TODO: Rename `disjoint.eq_bot` to `disjoint.inf_eq` and `disjoint.eq_bot_of_self` to `disjoint.eq_bot` -/ alias disjoint_self ↔ disjoint.eq_bot_of_self _ lemma disjoint.ne (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := λ h, ha $ disjoint_self.1 $ by rwa ←h at hab lemma disjoint.eq_bot_of_le (hab : disjoint a b) (h : a ≤ b) : a = ⊥ := eq_bot_iff.2 (by rwa ←inf_eq_left.2 h) lemma disjoint.eq_bot_of_ge (hab : disjoint a b) : b ≤ a → b = ⊥ := hab.symm.eq_bot_of_le lemma disjoint.of_disjoint_inf_of_le (h : disjoint (a ⊓ b) c) (hle : a ≤ c) : disjoint a b := disjoint_iff.2 $ h.eq_bot_of_le $ inf_le_of_left_le hle lemma disjoint.of_disjoint_inf_of_le' (h : disjoint (a ⊓ b) c) (hle : b ≤ c) : disjoint a b := disjoint_iff.2 $ h.eq_bot_of_le $ inf_le_of_right_le hle end semilattice_inf_bot section lattice variables [lattice α] [bounded_order α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff] @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff] end lattice section distrib_lattice_bot variables [distrib_lattice α] [order_bot α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ lemma disjoint.left_le_of_le_sup_right (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := le_of_inf_le_sup_le (le_trans hd bot_le) $ sup_le h le_sup_right lemma disjoint.left_le_of_le_sup_left (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := hd.left_le_of_le_sup_right $ by rwa sup_comm end distrib_lattice_bot end disjoint section codisjoint section semilattice_sup_top variables [semilattice_sup α] [order_top α] {a b c d : α} /-- Two elements of a lattice are codisjoint if their sup is the top element. -/ def codisjoint (a b : α) : Prop := ⊤ ≤ a ⊔ b lemma codisjoint_iff : codisjoint a b ↔ a ⊔ b = ⊤ := top_le_iff lemma codisjoint.eq_top : codisjoint a b → a ⊔ b = ⊤ := top_unique lemma codisjoint.comm : codisjoint a b ↔ codisjoint b a := by rw [codisjoint, codisjoint, sup_comm] @[symm] lemma codisjoint.symm ⦃a b : α⦄ : codisjoint a b → codisjoint b a := codisjoint.comm.1 lemma symmetric_codisjoint : symmetric (codisjoint : α → α → Prop) := codisjoint.symm lemma codisjoint_assoc : codisjoint (a ⊔ b) c ↔ codisjoint a (b ⊔ c) := by rw [codisjoint, codisjoint, sup_assoc] lemma codisjoint_left_comm : codisjoint a (b ⊔ c) ↔ codisjoint b (a ⊔ c) := by simp_rw [codisjoint, sup_left_comm] lemma codisjoint_right_comm : codisjoint (a ⊔ b) c ↔ codisjoint (a ⊔ c) b := by simp_rw [codisjoint, sup_right_comm] @[simp] lemma codisjoint_top_left : codisjoint ⊤ a := le_sup_left @[simp] lemma codisjoint_top_right : codisjoint a ⊤ := le_sup_right lemma codisjoint.mono (h₁ : a ≤ b) (h₂ : c ≤ d) : codisjoint a c → codisjoint b d := le_trans' $ sup_le_sup h₁ h₂ lemma codisjoint.mono_left (h : a ≤ b) : codisjoint a c → codisjoint b c := codisjoint.mono h le_rfl lemma codisjoint.mono_right : b ≤ c → codisjoint a b → codisjoint a c := codisjoint.mono le_rfl variables (c) lemma codisjoint.sup_left (h : codisjoint a b) : codisjoint (a ⊔ c) b := h.mono_left le_sup_left lemma codisjoint.sup_left' (h : codisjoint a b) : codisjoint (c ⊔ a) b := h.mono_left le_sup_right lemma codisjoint.sup_right (h : codisjoint a b) : codisjoint a (b ⊔ c) := h.mono_right le_sup_left lemma codisjoint.sup_right' (h : codisjoint a b) : codisjoint a (c ⊔ b) := h.mono_right le_sup_right variables {c} @[simp] lemma codisjoint_self : codisjoint a a ↔ a = ⊤ := by simp [codisjoint] /- TODO: Rename `codisjoint.eq_top` to `codisjoint.sup_eq` and `codisjoint.eq_top_of_self` to `codisjoint.eq_top` -/ alias codisjoint_self ↔ codisjoint.eq_top_of_self _ lemma codisjoint.ne (ha : a ≠ ⊤) (hab : codisjoint a b) : a ≠ b := λ h, ha $ codisjoint_self.1 $ by rwa ←h at hab lemma codisjoint.eq_top_of_ge (hab : codisjoint a b) (h : b ≤ a) : a = ⊤ := eq_top_iff.2 $ by rwa ←sup_eq_left.2 h lemma codisjoint.eq_top_of_le (hab : codisjoint a b) : a ≤ b → b = ⊤ := hab.symm.eq_top_of_ge lemma codisjoint.of_codisjoint_sup_of_le (h : codisjoint (a ⊔ b) c) (hle : c ≤ a) : codisjoint a b := codisjoint_iff.2 $ h.eq_top_of_ge $ le_sup_of_le_left hle lemma codisjoint.of_codisjoint_sup_of_le' (h : codisjoint (a ⊔ b) c) (hle : c ≤ b) : codisjoint a b := codisjoint_iff.2 $ h.eq_top_of_ge $ le_sup_of_le_right hle end semilattice_sup_top section lattice variables [lattice α] [bounded_order α] {a : α} @[simp] lemma codisjoint_bot : codisjoint a ⊥ ↔ a = ⊤ := by simp [codisjoint_iff] @[simp] lemma bot_codisjoint : codisjoint ⊥ a ↔ a = ⊤ := by simp [codisjoint_iff] end lattice section distrib_lattice_top variables [distrib_lattice α] [order_top α] {a b c : α} @[simp] lemma codisjoint_inf_left : codisjoint (a ⊓ b) c ↔ codisjoint a c ∧ codisjoint b c := by simp only [codisjoint_iff, sup_inf_right, inf_eq_top_iff] @[simp] lemma codisjoint_inf_right : codisjoint a (b ⊓ c) ↔ codisjoint a b ∧ codisjoint a c := by simp only [codisjoint_iff, sup_inf_left, inf_eq_top_iff] lemma codisjoint.inf_left (ha : codisjoint a c) (hb : codisjoint b c) : codisjoint (a ⊓ b) c := codisjoint_inf_left.2 ⟨ha, hb⟩ lemma codisjoint.inf_right (hb : codisjoint a b) (hc : codisjoint a c) : codisjoint a (b ⊓ c) := codisjoint_inf_right.2 ⟨hb, hc⟩ lemma codisjoint.left_le_of_le_inf_right (h : a ⊓ b ≤ c) (hd : codisjoint b c) : a ≤ c := le_of_inf_le_sup_le (le_inf h inf_le_right) $ le_top.trans hd.symm lemma codisjoint.left_le_of_le_inf_left (h : b ⊓ a ≤ c) (hd : codisjoint b c) : a ≤ c := hd.left_le_of_le_inf_right $ by rwa inf_comm end distrib_lattice_top end codisjoint lemma disjoint.dual [semilattice_inf α] [order_bot α] {a b : α} : disjoint a b → codisjoint (to_dual a) (to_dual b) := id lemma codisjoint.dual [semilattice_sup α] [order_top α] {a b : α} : codisjoint a b → disjoint (to_dual a) (to_dual b) := id @[simp] lemma disjoint_to_dual_iff [semilattice_sup α] [order_top α] {a b : α} : disjoint (to_dual a) (to_dual b) ↔ codisjoint a b := iff.rfl @[simp] lemma disjoint_of_dual_iff [semilattice_inf α] [order_bot α] {a b : αᵒᵈ} : disjoint (of_dual a) (of_dual b) ↔ codisjoint a b := iff.rfl @[simp] lemma codisjoint_to_dual_iff [semilattice_inf α] [order_bot α] {a b : α} : codisjoint (to_dual a) (to_dual b) ↔ disjoint a b := iff.rfl @[simp] lemma codisjoint_of_dual_iff [semilattice_sup α] [order_top α] {a b : αᵒᵈ} : codisjoint (of_dual a) (of_dual b) ↔ disjoint a b := iff.rfl section distrib_lattice variables [distrib_lattice α] [bounded_order α] {a b c : α} lemma disjoint.le_of_codisjoint (hab : disjoint a b) (hbc : codisjoint b c) : a ≤ c := begin rw [←@inf_top_eq _ _ _ a, ←@bot_sup_eq _ _ _ c, ←hab.eq_bot, ←hbc.eq_top, sup_inf_right], exact inf_le_inf_right _ le_sup_left, end end distrib_lattice section is_compl /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ @[protect_proj] structure is_compl [lattice α] [bounded_order α] (x y : α) : Prop := (disjoint : disjoint x y) (codisjoint : codisjoint x y) namespace is_compl section bounded_order variables [lattice α] [bounded_order α] {x y z : α} @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨h.1.symm, h.2.symm⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, ge_of_eq h₂⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := h.codisjoint.eq_top lemma dual (h : is_compl x y) : is_compl (to_dual x) (to_dual y) := ⟨h.2, h.1⟩ lemma of_dual {a b : αᵒᵈ} (h : is_compl a b) : is_compl (of_dual a) (of_dual b) := ⟨h.2, h.1⟩ end bounded_order variables [distrib_lattice α] [bounded_order α] {a b x y z : α} lemma inf_left_le_of_le_sup_right (h : is_compl x y) (hle : a ≤ b ⊔ y) : a ⊓ x ≤ b := calc a ⊓ x ≤ (b ⊔ y) ⊓ x : inf_le_inf hle le_rfl ... = (b ⊓ x) ⊔ (y ⊓ x) : inf_sup_right ... = b ⊓ x : by rw [h.symm.inf_eq_bot, sup_bot_eq] ... ≤ b : inf_le_left lemma le_sup_right_iff_inf_left_le {a b} (h : is_compl x y) : a ≤ b ⊔ y ↔ a ⊓ x ≤ b := ⟨h.inf_left_le_of_le_sup_right, h.symm.dual.inf_left_le_of_le_sup_right⟩ lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := by rw [← le_bot_iff, ← h.le_sup_right_iff_inf_left_le, bot_sup_eq] lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := by { rw disjoint_iff, exact h.inf_left_eq_bot_iff } lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := h.disjoint_right_iff.symm lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff protected lemma antitone {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.codisjoint (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antitone hxy $ le_refl x) (hxy.antitone hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end is_compl section variables [lattice α] [bounded_order α] {a b x : α} @[simp] lemma is_compl_to_dual_iff : is_compl (to_dual a) (to_dual b) ↔ is_compl a b := ⟨is_compl.of_dual, is_compl.dual⟩ @[simp] lemma is_compl_of_dual_iff {a b : αᵒᵈ} : is_compl (of_dual a) (of_dual b) ↔ is_compl a b := ⟨is_compl.dual, is_compl.of_dual⟩ lemma is_compl_bot_top : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ := sup_bot_eq.symm.trans h.sup_eq_top lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ := eq_top_of_is_compl_bot h.symm lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ := eq_top_of_is_compl_bot h.dual lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ := eq_top_of_bot_is_compl h.dual end /-- A complemented bounded lattice is one where every element has a (not necessarily unique) complement. -/ class complemented_lattice (α) [lattice α] [bounded_order α] : Prop := (exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b) export complemented_lattice (exists_is_compl) namespace complemented_lattice variables [lattice α] [bounded_order α] [complemented_lattice α] instance : complemented_lattice αᵒᵈ := ⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.dual⟩⟩ end complemented_lattice end is_compl section nontrivial variables [partial_order α] [bounded_order α] [nontrivial α] lemma bot_ne_top : (⊥ : α) ≠ ⊤ := λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_› lemma top_ne_bot : (⊤ : α) ≠ ⊥ := bot_ne_top.symm lemma bot_lt_top : (⊥ : α) < ⊤ := lt_top_iff_ne_top.2 bot_ne_top end nontrivial section bool open bool instance : bounded_order bool := { top := tt, le_top := λ x, le_tt, bot := ff, bot_le := λ x, ff_le } @[simp] lemma top_eq_tt : ⊤ = tt := rfl @[simp] lemma bot_eq_ff : ⊥ = ff := rfl end bool
68c5dfb01b86fcb3b888fd5f1b83f950328e396f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/inner_product_space/rayleigh.lean
7d9b1bed9dbca73e0778f056938d5faeb39fea81
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
12,579
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Frédéric Dupuis -/ import analysis.inner_product_space.calculus import analysis.inner_product_space.dual import analysis.inner_product_space.adjoint import analysis.calculus.lagrange_multipliers import linear_algebra.eigenspace.basic /-! # The Rayleigh quotient > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The Rayleigh quotient of a self-adjoint operator `T` on an inner product space `E` is the function `λ x, ⟪T x, x⟫ / ‖x‖ ^ 2`. The main results of this file are `is_self_adjoint.has_eigenvector_of_is_max_on` and `is_self_adjoint.has_eigenvector_of_is_min_on`, which state that if `E` is complete, and if the Rayleigh quotient attains its global maximum/minimum over some sphere at the point `x₀`, then `x₀` is an eigenvector of `T`, and the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ‖x‖ ^ 2` is the corresponding eigenvalue. The corollaries `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` and `is_self_adjoint.has_eigenvalue_supr_of_finite_dimensional` state that if `E` is finite-dimensional and nontrivial, then `T` has some (nonzero) eigenvectors with eigenvalue the `supr`/`infi` of `λ x, ⟪T x, x⟫ / ‖x‖ ^ 2`. ## TODO A slightly more elaborate corollary is that if `E` is complete and `T` is a compact operator, then `T` has some (nonzero) eigenvector with eigenvalue either `⨆ x, ⟪T x, x⟫ / ‖x‖ ^ 2` or `⨅ x, ⟪T x, x⟫ / ‖x‖ ^ 2` (not necessarily both). -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] variables {E : Type*} [normed_add_comm_group E] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y open_locale nnreal open module.End metric namespace continuous_linear_map variables (T : E →L[𝕜] E) local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ‖(x:E)‖ ^ 2 lemma rayleigh_smul (x : E) {c : 𝕜} (hc : c ≠ 0) : rayleigh_quotient (c • x) = rayleigh_quotient x := begin by_cases hx : x = 0, { simp [hx] }, have : ‖c‖ ≠ 0 := by simp [hc], have : ‖x‖ ≠ 0 := by simp [hx], field_simp [norm_smul, T.re_apply_inner_self_smul], ring end lemma image_rayleigh_eq_image_rayleigh_sphere {r : ℝ} (hr : 0 < r) : rayleigh_quotient '' {0}ᶜ = rayleigh_quotient '' (sphere 0 r) := begin ext a, split, { rintros ⟨x, (hx : x ≠ 0), hxT⟩, have : ‖x‖ ≠ 0 := by simp [hx], let c : 𝕜 := ↑‖x‖⁻¹ * r, have : c ≠ 0 := by simp [c, hx, hr.ne'], refine ⟨c • x, _, _⟩, { field_simp [norm_smul, abs_of_pos hr] }, { rw T.rayleigh_smul x this, exact hxT } }, { rintros ⟨x, hx, hxT⟩, exact ⟨x, ne_zero_of_mem_sphere hr.ne' ⟨x, hx⟩, hxT⟩ }, end lemma supr_rayleigh_eq_supr_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨆ x : sphere (0:E) r, rayleigh_quotient x := show (⨆ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [←@Sup_image' _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] lemma infi_rayleigh_eq_infi_rayleigh_sphere {r : ℝ} (hr : 0 < r) : (⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) = ⨅ x : sphere (0:E) r, rayleigh_quotient x := show (⨅ x : ({0} : set E)ᶜ, rayleigh_quotient x) = _, by simp only [←@Inf_image' _ _ _ _ rayleigh_quotient, T.image_rayleigh_eq_image_rayleigh_sphere hr] end continuous_linear_map namespace is_self_adjoint section real variables {F : Type*} [normed_add_comm_group F] [inner_product_space ℝ F] lemma _root_.linear_map.is_symmetric.has_strict_fderiv_at_re_apply_inner_self {T : F →L[ℝ] F} (hT : (T : F →ₗ[ℝ] F).is_symmetric) (x₀ : F) : has_strict_fderiv_at T.re_apply_inner_self (_root_.bit0 (innerSL ℝ (T x₀))) x₀ := begin convert T.has_strict_fderiv_at.inner _ (has_strict_fderiv_at_id x₀), ext y, simp_rw [_root_.bit0, continuous_linear_map.comp_apply, continuous_linear_map.add_apply, innerSL_apply, fderiv_inner_clm_apply, id.def, continuous_linear_map.prod_apply, continuous_linear_map.id_apply, hT.apply_clm x₀ y, real_inner_comm _ x₀], end variables [complete_space F] {T : F →L[ℝ] F} local notation `rayleigh_quotient` := λ x : F, T.re_apply_inner_self x / ‖(x:F)‖ ^ 2 lemma linearly_dependent_of_is_local_extr_on (hT : is_self_adjoint T) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ‖x₀‖) x₀) : ∃ a b : ℝ, (a, b) ≠ 0 ∧ a • x₀ + b • T x₀ = 0 := begin have H : is_local_extr_on T.re_apply_inner_self {x : F | ‖x‖ ^ 2 = ‖x₀‖ ^ 2} x₀, { convert hextr, ext x, simp [dist_eq_norm] }, -- find Lagrange multipliers for the function `T.re_apply_inner_self` and the -- hypersurface-defining function `λ x, ‖x‖ ^ 2` obtain ⟨a, b, h₁, h₂⟩ := is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at_1d H (has_strict_fderiv_at_norm_sq x₀) (hT.is_symmetric.has_strict_fderiv_at_re_apply_inner_self x₀), refine ⟨a, b, h₁, _⟩, apply (inner_product_space.to_dual_map ℝ F).injective, simp only [linear_isometry.map_add, linear_isometry.map_smul, linear_isometry.map_zero], change a • innerSL _ x₀ + b • innerSL _ (T x₀) = 0, apply smul_right_injective (F →L[ℝ] ℝ) (two_ne_zero : (2:ℝ) ≠ 0), simpa only [_root_.bit0, add_smul, smul_add, one_smul, add_zero] using h₂ end lemma eq_smul_self_of_is_local_extr_on_real (hT : is_self_adjoint T) {x₀ : F} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:F) ‖x₀‖) x₀) : T x₀ = (rayleigh_quotient x₀) • x₀ := begin obtain ⟨a, b, h₁, h₂⟩ := hT.linearly_dependent_of_is_local_extr_on hextr, by_cases hx₀ : x₀ = 0, { simp [hx₀] }, by_cases hb : b = 0, { have : a ≠ 0 := by simpa [hb] using h₁, refine absurd _ hx₀, apply smul_right_injective F this, simpa [hb] using h₂ }, let c : ℝ := - b⁻¹ * a, have hc : T x₀ = c • x₀, { have : b * (b⁻¹ * a) = a := by field_simp [mul_comm], apply smul_right_injective F hb, simp [c, eq_neg_of_add_eq_zero_left h₂, ← mul_smul, this] }, convert hc, have : ‖x₀‖ ≠ 0 := by simp [hx₀], field_simp, simpa [inner_smul_left, real_inner_self_eq_norm_mul_norm, sq] using congr_arg (λ x, ⟪x, x₀⟫_ℝ) hc, end end real section complete_space variables [complete_space E] {T : E →L[𝕜] E} local notation `rayleigh_quotient` := λ x : E, T.re_apply_inner_self x / ‖(x:E)‖ ^ 2 lemma eq_smul_self_of_is_local_extr_on (hT : is_self_adjoint T) {x₀ : E} (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ‖x₀‖) x₀) : T x₀ = (↑(rayleigh_quotient x₀) : 𝕜) • x₀ := begin letI := inner_product_space.is_R_or_C_to_real 𝕜 E, let hSA := hT.is_symmetric.restrict_scalars.to_self_adjoint.prop, exact hSA.eq_smul_self_of_is_local_extr_on_real hextr, end /-- For a self-adjoint operator `T`, a local extremum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`. -/ lemma has_eigenvector_of_is_local_extr_on (hT : is_self_adjoint T) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_local_extr_on T.re_apply_inner_self (sphere (0:E) ‖x₀‖) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(rayleigh_quotient x₀) x₀ := begin refine ⟨_, hx₀⟩, rw module.End.mem_eigenspace_iff, exact hT.eq_smul_self_of_is_local_extr_on hextr end /-- For a self-adjoint operator `T`, a maximum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global supremum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_max_on (hT : is_self_adjoint T) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_max_on T.re_apply_inner_self (sphere (0:E) ‖x₀‖) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨆ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inr hextr.localize), have hx₀' : 0 < ‖x₀‖ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (‖x₀‖) := by simp, rw T.supr_rayleigh_eq_supr_rayleigh_sphere hx₀', refine is_max_on.supr_eq hx₀'' _, intros x hx, dsimp, have : ‖x‖ = ‖x₀‖ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ‖x₀‖) (hextr hx) end /-- For a self-adjoint operator `T`, a minimum of the Rayleigh quotient of `T` on a sphere centred at the origin is an eigenvector of `T`, with eigenvalue the global infimum of the Rayleigh quotient. -/ lemma has_eigenvector_of_is_min_on (hT : is_self_adjoint T) {x₀ : E} (hx₀ : x₀ ≠ 0) (hextr : is_min_on T.re_apply_inner_self (sphere (0:E) ‖x₀‖) x₀) : has_eigenvector (T : E →ₗ[𝕜] E) ↑(⨅ x : {x : E // x ≠ 0}, rayleigh_quotient x) x₀ := begin convert hT.has_eigenvector_of_is_local_extr_on hx₀ (or.inl hextr.localize), have hx₀' : 0 < ‖x₀‖ := by simp [hx₀], have hx₀'' : x₀ ∈ sphere (0:E) (‖x₀‖) := by simp, rw T.infi_rayleigh_eq_infi_rayleigh_sphere hx₀', refine is_min_on.infi_eq hx₀'' _, intros x hx, dsimp, have : ‖x‖ = ‖x₀‖ := by simpa using hx, rw this, exact div_le_div_of_le (sq_nonneg ‖x₀‖) (hextr hx) end end complete_space end is_self_adjoint section finite_dimensional variables [finite_dimensional 𝕜 E] [_i : nontrivial E] {T : E →ₗ[𝕜] E} namespace linear_map namespace is_symmetric include _i /-- The supremum of the Rayleigh quotient of a symmetric operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_supr_of_finite_dimensional (hT : T.is_symmetric) : has_eigenvalue T ↑(⨆ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ‖(x:E)‖ ^ 2) := begin haveI := finite_dimensional.proper_is_R_or_C 𝕜 E, let T' := hT.to_self_adjoint, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ‖x‖) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ‖x‖).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a max obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_ge H₂ T'.val.re_apply_inner_self_continuous.continuous_on, have hx₀ : ‖x₀‖ = ‖x‖ := by simpa using hx₀', have : is_max_on T'.val.re_apply_inner_self (sphere 0 ‖x₀‖) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ‖x₀‖ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (T'.prop.has_eigenvector_of_is_max_on hx₀_ne this) end /-- The infimum of the Rayleigh quotient of a symmetric operator `T` on a nontrivial finite-dimensional vector space is an eigenvalue for that operator. -/ lemma has_eigenvalue_infi_of_finite_dimensional (hT : T.is_symmetric) : has_eigenvalue T ↑(⨅ x : {x : E // x ≠ 0}, is_R_or_C.re ⟪T x, x⟫ / ‖(x:E)‖ ^ 2) := begin haveI := finite_dimensional.proper_is_R_or_C 𝕜 E, let T' := hT.to_self_adjoint, obtain ⟨x, hx⟩ : ∃ x : E, x ≠ 0 := exists_ne 0, have H₁ : is_compact (sphere (0:E) ‖x‖) := is_compact_sphere _ _, have H₂ : (sphere (0:E) ‖x‖).nonempty := ⟨x, by simp⟩, -- key point: in finite dimension, a continuous function on the sphere has a min obtain ⟨x₀, hx₀', hTx₀⟩ := H₁.exists_forall_le H₂ T'.val.re_apply_inner_self_continuous.continuous_on, have hx₀ : ‖x₀‖ = ‖x‖ := by simpa using hx₀', have : is_min_on T'.val.re_apply_inner_self (sphere 0 ‖x₀‖) x₀, { simpa only [← hx₀] using hTx₀ }, have hx₀_ne : x₀ ≠ 0, { have : ‖x₀‖ ≠ 0 := by simp only [hx₀, norm_eq_zero, hx, ne.def, not_false_iff], simpa [← norm_eq_zero, ne.def] }, exact has_eigenvalue_of_has_eigenvector (T'.prop.has_eigenvector_of_is_min_on hx₀_ne this) end omit _i lemma subsingleton_of_no_eigenvalue_finite_dimensional (hT : T.is_symmetric) (hT' : ∀ μ : 𝕜, module.End.eigenspace (T : E →ₗ[𝕜] E) μ = ⊥) : subsingleton E := (subsingleton_or_nontrivial E).resolve_right (λ h, by exactI absurd (hT' _) hT.has_eigenvalue_supr_of_finite_dimensional) end is_symmetric end linear_map end finite_dimensional
fbfa25412eece918ea753196213fb57138c76625
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/module/submodule/lattice.lean
669c4f0ee22f9d481371262f56c5990b895eee36
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
12,013
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.module.submodule.basic import algebra.punit_instances /-! # The lattice structure on `submodule`s > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the lattice structure on submodules, `submodule.complete_lattice`, with `⊥` defined as `{0}` and `⊓` defined as intersection of the underlying carrier. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many results about operations on this lattice structure are defined in `linear_algebra/basic.lean`, most notably those which use `span`. ## Implementation notes This structure should match the `add_submonoid.complete_lattice` structure, and we should try to unify the APIs where possible. -/ variables {R S M : Type*} section add_comm_monoid variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] [module S M] variables [has_smul S R] [is_scalar_tower S R M] variables {p q : submodule R M} namespace submodule /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl @[simp] lemma bot_to_add_submonoid : (⊥ : submodule R M).to_add_submonoid = ⊥ := rfl section variables (R) @[simp] lemma restrict_scalars_bot : restrict_scalars S (⊥ : submodule R M) = ⊥ := rfl @[simp] lemma mem_bot {x : M} : x ∈ (⊥ : submodule R M) ↔ x = 0 := set.mem_singleton_iff end @[simp] lemma restrict_scalars_eq_bot_iff {p : submodule R M} : restrict_scalars S p = ⊥ ↔ p = ⊥ := by simp [set_like.ext_iff] instance unique_bot : unique (⊥ : submodule R M) := ⟨infer_instance, λ x, subtype.ext $ (mem_bot R).1 x.mem⟩ instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp [zero_mem] {contextual := tt} } protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) := ⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx, λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩ @[ext] protected lemma bot_ext (x y : (⊥ : submodule R M)) : x = y := begin rcases x with ⟨x, xm⟩, rcases y with ⟨y, ym⟩, congr, rw (submodule.eq_bot_iff _).mp rfl x xm, rw (submodule.eq_bot_iff _).mp rfl y ym, end protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) := by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] } lemma nonzero_mem_of_bot_lt {p : submodule R M} (bot_lt : ⊥ < p) : ∃ a : p, a ≠ 0 := let ⟨b, hb₁, hb₂⟩ := p.ne_bot_iff.mp bot_lt.ne' in ⟨⟨b, hb₁⟩, hb₂ ∘ (congr_arg coe)⟩ lemma exists_mem_ne_zero_of_ne_bot {p : submodule R M} (h : p ≠ ⊥) : ∃ b : M, b ∈ p ∧ b ≠ 0 := let ⟨b, hb₁, hb₂⟩ := p.ne_bot_iff.mp h in ⟨b, hb₁, hb₂⟩ /-- The bottom submodule is linearly equivalent to punit as an `R`-module. -/ @[simps] def bot_equiv_punit : (⊥ : submodule R M) ≃ₗ[R] punit := { to_fun := λ x, punit.star, inv_fun := λ x, 0, map_add' := by { intros, ext, }, map_smul' := by { intros, ext, }, left_inv := by { intro x, ext, }, right_inv := by { intro x, ext, }, } lemma eq_bot_of_subsingleton (p : submodule R M) [subsingleton p] : p = ⊥ := begin rw eq_bot_iff, intros v hv, exact congr_arg coe (subsingleton.elim (⟨v, hv⟩ : p) 0) end /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := set.univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = set.univ := rfl @[simp] lemma top_to_add_submonoid : (⊤ : submodule R M).to_add_submonoid = ⊤ := rfl @[simp] lemma mem_top {x : M} : x ∈ (⊤ : submodule R M) := trivial section variables (R) @[simp] lemma restrict_scalars_top : restrict_scalars S (⊤ : submodule R M) = ⊤ := rfl end @[simp] lemma restrict_scalars_eq_top_iff {p : submodule R M} : restrict_scalars S p = ⊤ ↔ p = ⊤ := by simp [set_like.ext_iff] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial } lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, h trivial, λ h x _, h x⟩ /-- The top submodule is linearly equivalent to the module. This is the module version of `add_submonoid.top_equiv`. -/ @[simps] def top_equiv : (⊤ : submodule R M) ≃ₗ[R] M := { to_fun := λ x, x, inv_fun := λ x, ⟨x, by simp⟩, map_add' := by { intros, refl, }, map_smul' := by { intros, refl, }, left_inv := by { intro x, ext, refl, }, right_inv := by { intro x, refl, }, } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, (s : set M), zero_mem' := by simp [zero_mem], add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := set.bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀q ∈ S, p ≤ q) → p ≤ Inf S := set.subset_Inter₂ instance : has_inf (submodule R M) := ⟨λ p q, { carrier := p ∩ q, zero_mem' := by simp [zero_mem], add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, set.subset_inter, inf_le_left := λ a b, set.inter_subset_left _ _, inf_le_right := λ a b, set.inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ q hq, hq _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot, ..set_like.partial_order } @[simp] theorem inf_coe : ↑(p ⊓ q) = (p ∩ q : set M) := rfl @[simp] theorem mem_inf {p q : submodule R M} {x : M} : x ∈ p ⊓ q ↔ x ∈ p ∧ x ∈ q := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem finset_inf_coe {ι} (s : finset ι) (p : ι → submodule R M) : (↑(s.inf p) : set M) = ⋂ i ∈ s, ↑(p i) := begin letI := classical.dec_eq ι, refine s.induction_on _ (λ i s hi ih, _), { simp }, { rw [finset.inf_insert, inf_coe, ih], simp }, end @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] lemma mem_Inf {S : set (submodule R M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] theorem mem_infi {ι} (p : ι → submodule R M) {x} : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← set_like.mem_coe, infi_coe, set.mem_Inter]; refl @[simp] theorem mem_finset_inf {ι} {s : finset ι} {p : ι → submodule R M} {x : M} : x ∈ s.inf p ↔ ∀ i ∈ s, x ∈ p i := by simp only [← set_like.mem_coe, finset_inf_coe, set.mem_Inter] lemma mem_sup_left {S T : submodule R M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : submodule R M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma add_mem_sup {S T : submodule R M} {s t : M} (hs : s ∈ S) (ht : t ∈ T) : s + t ∈ S ⊔ T := add_mem (mem_sup_left hs) (mem_sup_right ht) lemma sub_mem_sup {R' M' : Type*} [ring R'] [add_comm_group M'] [module R' M'] {S T : submodule R' M'} {s t : M'} (hs : s ∈ S) (ht : t ∈ T) : s - t ∈ S ⊔ T := begin rw sub_eq_add_neg, exact add_mem_sup hs (neg_mem ht), end lemma mem_supr_of_mem {ι : Sort*} {b : M} {p : ι → submodule R M} (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h open_locale big_operators lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M} (h : ∀ i, f i ∈ p i) : ∑ i, f i ∈ ⨆ i, p i := sum_mem $ λ i hi, mem_supr_of_mem i (h i) lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M} (h : ∀ i ∈ s, f i ∈ p i) : ∑ i in s, f i ∈ ⨆ i ∈ s, p i := sum_mem $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi) /-! Note that `submodule.mem_supr` is provided in `linear_algebra/basic.lean`. -/ lemma mem_Sup_of_mem {S : set (submodule R M)} {s : submodule R M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := disjoint_iff_inf_le.trans $ show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ lemma eq_zero_of_coe_mem_of_disjoint (hpq : disjoint p q) {a : p} (ha : (a : M) ∈ q) : a = 0 := by exact_mod_cast disjoint_def.mp hpq a (coe_mem a) ha end submodule section nat_submodule /-- An additive submonoid is equivalent to a ℕ-submodule. -/ def add_submonoid.to_nat_submodule : add_submonoid M ≃o submodule ℕ M := { to_fun := λ S, { smul_mem' := λ r s hs, show r • s ∈ S, from nsmul_mem hs _, ..S }, inv_fun := submodule.to_add_submonoid, left_inv := λ ⟨S, _, _⟩, rfl, right_inv := λ ⟨S, _, _, _⟩, rfl, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma add_submonoid.to_nat_submodule_symm : ⇑(add_submonoid.to_nat_submodule.symm : _ ≃o add_submonoid M) = submodule.to_add_submonoid := rfl @[simp] lemma add_submonoid.coe_to_nat_submodule (S : add_submonoid M) : (S.to_nat_submodule : set M) = S := rfl @[simp] lemma add_submonoid.to_nat_submodule_to_add_submonoid (S : add_submonoid M) : S.to_nat_submodule.to_add_submonoid = S := add_submonoid.to_nat_submodule.symm_apply_apply S @[simp] lemma submodule.to_add_submonoid_to_nat_submodule (S : submodule ℕ M) : S.to_add_submonoid.to_nat_submodule = S := add_submonoid.to_nat_submodule.apply_symm_apply S end nat_submodule end add_comm_monoid section int_submodule variables [add_comm_group M] /-- An additive subgroup is equivalent to a ℤ-submodule. -/ def add_subgroup.to_int_submodule : add_subgroup M ≃o submodule ℤ M := { to_fun := λ S, { smul_mem' := λ r s hs, S.zsmul_mem hs _, ..S}, inv_fun := submodule.to_add_subgroup, left_inv := λ ⟨S, _, _, _⟩, rfl, right_inv := λ ⟨S, _, _, _⟩, rfl, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma add_subgroup.to_int_submodule_symm : ⇑(add_subgroup.to_int_submodule.symm : _ ≃o add_subgroup M) = submodule.to_add_subgroup := rfl @[simp] lemma add_subgroup.coe_to_int_submodule (S : add_subgroup M) : (S.to_int_submodule : set M) = S := rfl @[simp] lemma add_subgroup.to_int_submodule_to_add_subgroup (S : add_subgroup M) : S.to_int_submodule.to_add_subgroup = S := add_subgroup.to_int_submodule.symm_apply_apply S @[simp] lemma submodule.to_add_subgroup_to_int_submodule (S : submodule ℤ M) : S.to_add_subgroup.to_int_submodule = S := add_subgroup.to_int_submodule.apply_symm_apply S end int_submodule
50b7ffed21a0d52103e00a5ba2c27acf14f2e3d5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/roots_of_unity.lean
220abd647157c80e3c10882190aa1c3e6558bdd6
[ "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
47,494
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.char_p.two import algebra.ne_zero import data.polynomial.ring_division import field_theory.finite.basic import field_theory.separable import group_theory.specific_groups.cyclic import number_theory.divisors import ring_theory.integral_domain import tactic.zify /-! # Roots of unity and primitive roots of unity We define roots of unity in the context of an arbitrary commutative monoid, as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative monoids, expressing that an element is a primitive root of unity. ## Main definitions * `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M` consisting of elements `x` that satisfy `x ^ n = 1`. * `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. * `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`. * `is_primitive_root.aut_to_pow`: the monoid hom that takes an automorphism of a ring to the power it sends that specific primitive root, as a member of `(zmod n)ˣ`. ## Main results * `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group. * `is_primitive_root.zmod_equiv_zpowers`: `zmod k` is equivalent to the subgroup generated by a primitive `k`-th root of unity. * `is_primitive_root.zpowers_eq`: in an integral domain, the subgroup generated by a primitive `k`-th root of unity is equal to the `k`-th roots of unity. * `is_primitive_root.card_primitive_roots`: if an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. ## Implementation details It is desirable that `roots_of_unity` is a subgroup, and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields. We therefore implement it as a subgroup of the units of a commutative monoid. We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`, because almost all lemmas need the positivity assumption, and in particular the type class instances for `fintype` and `is_cyclic`. On the other hand, for primitive roots of unity, it is desirable to have a predicate not just on units, but directly on elements of the ring/field. For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity in the complex numbers, without having to turn that number into a unit first. This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and `is_primitive_root.coe_units_iff` should provide the necessary glue. -/ open_locale classical big_operators polynomial noncomputable theory open polynomial open finset variables {M N G R S F : Type*} variables [comm_monoid M] [comm_monoid N] [division_comm_monoid G] section roots_of_unity variables {k l : ℕ+} /-- `roots_of_unity k M` is the subgroup of elements `m : Mˣ` that satisfy `m ^ k = 1` -/ def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup Mˣ := { carrier := { ζ | ζ ^ (k : ℕ) = 1 }, one_mem' := one_pow _, mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *, inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, inv_one] at * } @[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : Mˣ) : ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl lemma mem_roots_of_unity' (k : ℕ+) (ζ : Mˣ) : ζ ∈ roots_of_unity k M ↔ (ζ : M) ^ (k : ℕ) = 1 := by { rw [mem_roots_of_unity], norm_cast } lemma roots_of_unity.coe_injective {n : ℕ+} : function.injective (coe : (roots_of_unity n M) → M) := units.ext.comp (λ x y, subtype.ext) /-- Make an element of `roots_of_unity` from a member of the base ring, and a proof that it has a positive power equal to one. -/ @[simps coe_coe] def roots_of_unity.mk_of_pow_eq (ζ : M) {n : ℕ+} (h : ζ ^ (n : ℕ) = 1) : roots_of_unity n M := ⟨units.of_pow_eq_one ζ n h n.ne_zero, units.pow_of_pow_eq_one _ _⟩ @[simp] lemma roots_of_unity.coe_mk_of_pow_eq {ζ : M} {n : ℕ+} (h : ζ ^ (n : ℕ) = 1) : (roots_of_unity.mk_of_pow_eq _ h : M) = ζ := rfl lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M := begin obtain ⟨d, rfl⟩ := h, intros ζ h, simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *, end lemma map_roots_of_unity (f : Mˣ →* Nˣ) (k : ℕ+) : (roots_of_unity k M).map f ≤ roots_of_unity k N := begin rintros _ ⟨ζ, h, rfl⟩, simp only [←map_pow, *, mem_roots_of_unity, set_like.mem_coe, monoid_hom.map_one] at * end @[norm_cast] lemma roots_of_unity.coe_pow [comm_monoid R] (ζ : roots_of_unity k R) (m : ℕ) : ↑(ζ ^ m) = (ζ ^ m : R) := begin change ↑(↑(ζ ^ m) : Rˣ) = ↑(ζ : Rˣ) ^ m, rw [subgroup.coe_pow, units.coe_pow], end section comm_semiring variables [comm_semiring R] [comm_semiring S] /-- Restrict a ring homomorphism to the nth roots of unity -/ def restrict_roots_of_unity [ring_hom_class F R S] (σ : F) (n : ℕ+) : roots_of_unity n R →* roots_of_unity n S := let h : ∀ ξ : roots_of_unity n R, (σ ξ) ^ (n : ℕ) = 1 := λ ξ, by { change (σ (ξ : Rˣ)) ^ (n : ℕ) = 1, rw [←map_pow, ←units.coe_pow, show ((ξ : Rˣ) ^ (n : ℕ) = 1), from ξ.2, units.coe_one, map_one σ] } in { to_fun := λ ξ, ⟨@unit_of_invertible _ _ _ (invertible_of_pow_eq_one _ _ (h ξ) n.ne_zero), by { ext, rw units.coe_pow, exact h ξ }⟩, map_one' := by { ext, exact map_one σ }, map_mul' := λ ξ₁ ξ₂, by { ext, rw [subgroup.coe_mul, units.coe_mul], exact map_mul σ _ _ } } @[simp] lemma restrict_roots_of_unity_coe_apply [ring_hom_class F R S] (σ : F) (ζ : roots_of_unity k R) : ↑(restrict_roots_of_unity σ k ζ) = σ ↑ζ := rfl /-- Restrict a ring isomorphism to the nth roots of unity -/ def ring_equiv.restrict_roots_of_unity (σ : R ≃+* S) (n : ℕ+) : roots_of_unity n R ≃* roots_of_unity n S := { to_fun := restrict_roots_of_unity σ.to_ring_hom n, inv_fun :=restrict_roots_of_unity σ.symm.to_ring_hom n, left_inv := λ ξ, by { ext, exact σ.symm_apply_apply ξ }, right_inv := λ ξ, by { ext, exact σ.apply_symm_apply ξ }, map_mul' := (restrict_roots_of_unity _ n).map_mul } @[simp] lemma ring_equiv.restrict_roots_of_unity_coe_apply (σ : R ≃+* S) (ζ : roots_of_unity k R) : ↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ := rfl @[simp] lemma ring_equiv.restrict_roots_of_unity_symm (σ : R ≃+* S) : (σ.restrict_roots_of_unity k).symm = σ.symm.restrict_roots_of_unity k := rfl end comm_semiring section is_domain variables [comm_ring R] [is_domain R] lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : Rˣ} : ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) := by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow] variables (k R) /-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`. This is implemented as equivalence of subtypes, because `roots_of_unity` is a subgroup of the group of units, whereas `nth_roots` is a multiset. -/ def roots_of_unity_equiv_nth_roots : roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} := begin refine { to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩, inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩, left_inv := _, right_inv := _ }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, all_goals { rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx, simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx, tsub_add_cancel_of_le (show 1 ≤ (k : ℕ), from k.one_le)] }, { show (_ : Rˣ) ^ (k : ℕ) = 1, simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] } end variables {k R} @[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) : (roots_of_unity_equiv_nth_roots R k x : R) = x := rfl @[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) : ((roots_of_unity_equiv_nth_roots R k).symm x : R) = x := rfl variables (k R) instance roots_of_unity.fintype : fintype (roots_of_unity k R) := fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) := is_cyclic_of_subgroup_is_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype) (units.ext.comp subtype.val_injective) lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k := calc fintype.card (roots_of_unity k R) = fintype.card {x // x ∈ nth_roots k (1 : R)} : fintype.card_congr (roots_of_unity_equiv_nth_roots R k) ... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.dedup_le _) ... = (nth_roots k (1 : R)).card : multiset.card_attach ... ≤ k : card_nth_roots k 1 variables {k R} lemma map_root_of_unity_eq_pow_self [ring_hom_class F R R] (σ : F) (ζ : roots_of_unity k R) : ∃ m : ℕ, σ ζ = ζ ^ m := begin obtain ⟨m, hm⟩ := monoid_hom.map_cyclic (restrict_roots_of_unity σ k), rw [←restrict_roots_of_unity_coe_apply, hm, zpow_eq_mod_order_of, ←int.to_nat_of_nonneg (m.mod_nonneg (int.coe_nat_ne_zero.mpr (pos_iff_ne_zero.mp (order_of_pos ζ)))), zpow_coe_nat, roots_of_unity.coe_pow], exact ⟨(m % (order_of ζ)).to_nat, rfl⟩, end end is_domain section reduced variables (R) [comm_ring R] [is_reduced R] @[simp] lemma mem_roots_of_unity_prime_pow_mul_iff (p k : ℕ) (m : ℕ+) [hp : fact p.prime] [char_p R p] {ζ : Rˣ} : ζ ∈ roots_of_unity (⟨p, hp.1.pos⟩ ^ k * m) R ↔ ζ ∈ roots_of_unity m R := by simp [mem_roots_of_unity'] end reduced end roots_of_unity /-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/ structure is_primitive_root (ζ : M) (k : ℕ) : Prop := (pow_eq_one : ζ ^ (k : ℕ) = 1) (dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l) /-- Turn a primitive root μ into a member of the `roots_of_unity` subgroup. -/ @[simps] def is_primitive_root.to_roots_of_unity {μ : M} {n : ℕ+} (h : is_primitive_root μ n) : roots_of_unity n M := roots_of_unity.mk_of_pow_eq μ h.pow_eq_one section primitive_roots variables {k : ℕ} /-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity in the integral domain `R`. -/ def primitive_roots (k : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := (nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k) variables [comm_ring R] [is_domain R] @[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) : ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k := begin rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp], exact is_primitive_root.pow_eq_one end @[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ := by rw [primitive_roots, nth_roots_zero, multiset.to_finset_zero, finset.filter_empty] lemma is_primitive_root_of_mem_primitive_roots {ζ : R} (h : ζ ∈ primitive_roots k R) : is_primitive_root ζ k := k.eq_zero_or_pos.elim (λ hk, false.elim $ by simpa [hk] using h) (λ hk, (mem_primitive_roots hk).1 h) end primitive_roots namespace is_primitive_root variables {k l : ℕ} lemma iff_def (ζ : M) (k : ℕ) : is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) := ⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩ lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) : is_primitive_root ζ k := begin refine ⟨h1, λ l hl, _⟩, suffices : k.gcd l = k, { exact this ▸ k.gcd_dvd_right l }, rw eq_iff_le_not_lt, refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩, intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h', exact pow_gcd_eq_one _ h1 hl end section comm_monoid variables {ζ : M} {f : F} (h : is_primitive_root ζ k) @[nontriviality] lemma of_subsingleton [subsingleton M] (x : M) : is_primitive_root x 1 := ⟨subsingleton.elim _ _, λ _ _, one_dvd _⟩ lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l := ⟨h.dvd_of_pow_eq_one l, by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩ lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ := begin apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)), rw [← pow_succ, tsub_add_cancel_of_le h0.nat_succ_le, h.pow_eq_one] end lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 := mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl lemma ne_one (hk : 1 < k) : ζ ≠ 1 := h.pow_ne_one_of_pos_of_lt zero_lt_one hk ∘ (pow_one ζ).trans lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) : i = j := begin wlog hij : i ≤ j, apply le_antisymm hij, rw ← tsub_eq_zero_iff_le, apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt tsub_le_self hj), apply h.dvd_of_pow_eq_one, rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj, ← pow_add, tsub_add_cancel_of_le hij, H, one_mul] end lemma one : is_primitive_root (1 : M) 1 := { pow_eq_one := pow_one _, dvd_of_pow_eq_one := λ l hl, one_dvd _ } @[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 := begin split, { intro h, rw [← pow_one ζ, h.pow_eq_one] }, { rintro rfl, exact one } end @[simp] lemma coe_submonoid_class_iff {M B : Type*} [comm_monoid M] [set_like B M] [submonoid_class B M] {N : B} {ζ : N} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp [iff_def, ← submonoid_class.coe_pow] @[simp] lemma coe_units_iff {ζ : Mˣ} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one] lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : k = 0, { subst k, simp only [*, pow_one, nat.coprime_zero_right] at * }, rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩, rw [← units.coe_pow], rw coe_units_iff at h ⊢, refine { pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow], dvd_of_pow_eq_one := _ }, intros l hl, apply h.dvd_of_pow_eq_one, rw [← pow_one ζ, ← zpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, zpow_add, mul_pow, ← zpow_coe_nat, ← zpow_mul, mul_right_comm], simp only [zpow_mul, hl, h.pow_eq_one, one_zpow, one_pow, one_mul, zpow_coe_nat] end lemma pow_of_prime (h : is_primitive_root ζ k) {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ k) : is_primitive_root (ζ ^ p) k := h.pow_of_coprime p (hprime.coprime_iff_not_dvd.2 hdiv) lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) : is_primitive_root (ζ ^ i) k ↔ i.coprime k := begin refine ⟨_, h.pow_of_coprime i⟩, intro hi, obtain ⟨a, ha⟩ := i.gcd_dvd_left k, obtain ⟨b, hb⟩ := i.gcd_dvd_right k, suffices : b = k, { rwa [this, ← one_mul k, mul_left_inj' h0.ne', eq_comm] at hb { occs := occurrences.pos [1] } }, rw [ha] at hi, rw [mul_comm] at hb, apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _), rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow] end protected lemma order_of (ζ : M) : is_primitive_root ζ (order_of ζ) := ⟨pow_order_of_eq_one ζ, λ l, order_of_dvd_of_pow_eq_one⟩ lemma unique {ζ : M} (hk : is_primitive_root ζ k) (hl : is_primitive_root ζ l) : k = l := nat.dvd_antisymm (hk.2 _ hl.1) (hl.2 _ hk.1) lemma eq_order_of : k = order_of ζ := h.unique (is_primitive_root.order_of ζ) protected lemma iff (hk : 0 < k) : is_primitive_root ζ k ↔ ζ ^ k = 1 ∧ ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1 := begin refine ⟨λ h, ⟨h.pow_eq_one, λ l hl' hl, _⟩, λ ⟨hζ, hl⟩, is_primitive_root.mk_of_lt ζ hk hζ hl⟩, rw h.eq_order_of at hl, exact pow_ne_one_of_lt_order_of' hl'.ne' hl, end protected lemma not_iff : ¬ is_primitive_root ζ k ↔ order_of ζ ≠ k := ⟨λ h hk, h $ hk ▸ is_primitive_root.order_of ζ, λ h hk, h.symm $ hk.unique $ is_primitive_root.order_of ζ⟩ lemma pow_of_dvd (h : is_primitive_root ζ k) {p : ℕ} (hp : p ≠ 0) (hdiv : p ∣ k) : is_primitive_root (ζ ^ p) (k / p) := begin suffices : order_of (ζ ^ p) = k / p, { exact this ▸ is_primitive_root.order_of (ζ ^ p) }, rw [order_of_pow' _ hp, ← eq_order_of h, nat.gcd_eq_right hdiv] end protected lemma mem_roots_of_unity {ζ : Mˣ} {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n M := h.pow_eq_one /-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`, then there is a `b`-th primitive root of unity in `R`. -/ lemma pow {n : ℕ} {a b : ℕ} (hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) : is_primitive_root (ζ ^ a) b := begin subst n, simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and], intros l hl, have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn }, rwa ← mul_dvd_mul_iff_left ha0, exact h.dvd_of_pow_eq_one _ hl end section maps open function lemma map_of_injective [monoid_hom_class F M N] (h : is_primitive_root ζ k) (hf : injective f) : is_primitive_root (f ζ) k := { pow_eq_one := by rw [←map_pow, h.pow_eq_one, _root_.map_one], dvd_of_pow_eq_one := begin rw h.eq_order_of, intros l hl, rw [←map_pow, ←map_one f] at hl, exact order_of_dvd_of_pow_eq_one (hf hl) end } lemma of_map_of_injective [monoid_hom_class F M N] (h : is_primitive_root (f ζ) k) (hf : injective f) : is_primitive_root ζ k := { pow_eq_one := by { apply_fun f, rw [map_pow, _root_.map_one, h.pow_eq_one] }, dvd_of_pow_eq_one := begin rw h.eq_order_of, intros l hl, apply_fun f at hl, rw [map_pow, _root_.map_one] at hl, exact order_of_dvd_of_pow_eq_one hl end } lemma map_iff_of_injective [monoid_hom_class F M N] (hf : injective f) : is_primitive_root (f ζ) k ↔ is_primitive_root ζ k := ⟨λ h, h.of_map_of_injective hf, λ h, h.map_of_injective hf⟩ end maps end comm_monoid section comm_monoid_with_zero variables {M₀ : Type*} [comm_monoid_with_zero M₀] lemma zero [nontrivial M₀] : is_primitive_root (0 : M₀) 0 := ⟨pow_zero 0, λ l hl, by simpa [zero_pow_eq, show ∀ p, ¬p → false ↔ p, from @not_not] using hl⟩ protected lemma ne_zero [nontrivial M₀] {ζ : M₀} (h : is_primitive_root ζ k) : k ≠ 0 → ζ ≠ 0 := mt $ λ hn, h.unique (hn.symm ▸ is_primitive_root.zero) end comm_monoid_with_zero section division_comm_monoid variables {ζ : G} lemma zpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 := by { rw zpow_coe_nat, exact h.pow_eq_one } lemma zpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [zpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← zpow_neg, ← hl', zpow_coe_nat, inv_one] } end lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj, ← inv_pow, hl, inv_one] end } @[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h } lemma zpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, rw zpow_coe_nat, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff, ← zpow_neg, ← hi', zpow_coe_nat], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end end division_comm_monoid section is_domain variables {ζ : R} variables [comm_ring R] [is_domain R] @[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} := begin apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] }, { intros x hx, rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx, exact hx } end lemma ne_zero' {n : ℕ+} (hζ : is_primitive_root ζ n) : ne_zero ((n : ℕ) : R) := begin let p := ring_char R, have hfin := (multiplicity.finite_nat_iff.2 ⟨char_p.char_ne_one R p, n.pos⟩), obtain ⟨m, hm⟩ := multiplicity.exists_eq_pow_mul_and_not_dvd hfin, by_cases hp : p ∣ n, { obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero (multiplicity.pos_of_dvd hfin hp).ne', haveI : ne_zero p := ne_zero.of_pos (nat.pos_of_dvd_of_pos hp n.pos), haveI hpri : fact p.prime := char_p.char_is_prime_of_pos R p, have := hζ.pow_eq_one, rw [hm.1, hk, pow_succ, mul_assoc, pow_mul', ← frobenius_def, ← frobenius_one p] at this, exfalso, have hpos : 0 < p ^ k * m, { refine (mul_pos (pow_pos hpri.1.pos _) (nat.pos_of_ne_zero (λ h, _))), have H := hm.1, rw [h] at H, simpa using H }, refine hζ.pow_ne_one_of_pos_of_lt hpos _ (frobenius_inj R p this), { rw [hm.1, hk, pow_succ, mul_assoc, mul_comm p], exact lt_mul_of_one_lt_right hpos hpri.1.one_lt } }, { exact ne_zero.of_not_dvd R hp } end lemma mem_nth_roots_finset (hζ : is_primitive_root ζ k) (hk : 0 < k) : ζ ∈ nth_roots_finset k R := (mem_nth_roots_finset hk).2 hζ.pow_eq_one end is_domain section is_domain variables [comm_ring R] variables {ζ : Rˣ} (h : is_primitive_root ζ k) lemma eq_neg_one_of_two_right [no_zero_divisors R] {ζ : R} (h : is_primitive_root ζ 2) : ζ = -1 := begin apply (eq_or_eq_neg_of_sq_eq_sq ζ 1 _).resolve_left, { rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial }, { simp only [h.pow_eq_one, one_pow] } end lemma neg_one (p : ℕ) [nontrivial R] [h : char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 := begin convert is_primitive_root.order_of (-1 : R), rw [order_of_neg_one, if_neg], rwa ring_char.eq_iff.mpr h end /-- If `1 < k` then `(∑ i in range k, ζ ^ i) = 0`. -/ lemma geom_sum_eq_zero [is_domain R] {ζ : R} (hζ : is_primitive_root ζ k) (hk : 1 < k) : (∑ i in range k, ζ ^ i) = 0 := begin refine eq_zero_of_ne_zero_of_mul_left_eq_zero (sub_ne_zero_of_ne (hζ.ne_one hk).symm) _, rw [mul_neg_geom_sum, hζ.pow_eq_one, sub_self] end /-- If `1 < k`, then `ζ ^ k.pred = -(∑ i in range k.pred, ζ ^ i)`. -/ lemma pow_sub_one_eq [is_domain R] {ζ : R} (hζ : is_primitive_root ζ k) (hk : 1 < k) : ζ ^ k.pred = -(∑ i in range k.pred, ζ ^ i) := by rw [eq_neg_iff_add_eq_zero, add_comm, ←sum_range_succ, ←nat.succ_eq_add_one, nat.succ_pred_eq_of_pos (pos_of_gt hk), hζ.geom_sum_eq_zero hk] /-- The (additive) monoid equivalence between `zmod k` and the powers of a primitive root of unity `ζ`. -/ def zmod_equiv_zpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.zpowers ζ) := add_equiv.of_bijective (add_monoid_hom.lift_of_right_inverse (int.cast_add_hom $ zmod k) _ zmod.int_cast_right_inverse ⟨{ to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.zpowers ζ), map_zero' := by { simp only [zpow_zero], refl }, map_add' := by { intros i j, simp only [zpow_add], refl } }, (λ i hi, begin simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k, add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢, obtain ⟨i, rfl⟩ := hi, simp only [zpow_mul, h.pow_eq_one, one_zpow, zpow_coe_nat], refl end)⟩) begin split, { rw injective_iff_map_eq_zero, intros i hi, rw subtype.ext_iff at hi, have := (h.zpow_eq_one_iff_dvd _).mp hi, rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm], exact zmod.int_cast_right_inverse i }, { rintro ⟨ξ, i, rfl⟩, refine ⟨int.cast_add_hom _ i, _⟩, rw [add_monoid_hom.lift_of_right_inverse_comp_apply], refl } end @[simp] lemma zmod_equiv_zpowers_apply_coe_int (i : ℤ) : h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) := add_monoid_hom.lift_of_right_inverse_comp_apply _ _ zmod.int_cast_right_inverse _ _ @[simp] lemma zmod_equiv_zpowers_apply_coe_nat (i : ℕ) : h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) := begin have : (i : zmod k) = (i : ℤ), by norm_cast, simp only [this, zmod_equiv_zpowers_apply_coe_int, zpow_coe_nat], refl end @[simp] lemma zmod_equiv_zpowers_symm_apply_zpow (i : ℤ) : h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i := by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_int] @[simp] lemma zmod_equiv_zpowers_symm_apply_zpow' (i : ℤ) : h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_zpowers_symm_apply_zpow i @[simp] lemma zmod_equiv_zpowers_symm_apply_pow (i : ℕ) : h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i := by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_nat] @[simp] lemma zmod_equiv_zpowers_symm_apply_pow' (i : ℕ) : h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_zpowers_symm_apply_pow i variables [is_domain R] lemma zpowers_eq {k : ℕ+} {ζ : Rˣ} (h : is_primitive_root ζ k) : subgroup.zpowers ζ = roots_of_unity k R := begin apply set_like.coe_injective, haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_zpowers).to_equiv, refine @set.eq_of_subset_of_card_le Rˣ (subgroup.zpowers ζ) (roots_of_unity k R) F (roots_of_unity.fintype R k) (subgroup.zpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _, calc fintype.card (roots_of_unity k R) ≤ k : card_roots_of_unity R k ... = fintype.card (zmod k) : (zmod.card k).symm ... = fintype.card (subgroup.zpowers ζ) : fintype.card_congr (h.zmod_equiv_zpowers).to_equiv end lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : Rˣ} (h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) : ∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ := begin obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.zpowers_eq] at hξ, have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos, let i := n % k, have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0), lift i to ℕ using hi0 with i₀ hi₀, refine ⟨i₀, _, _⟩, { zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 }, { have aux := h.zpow_eq_one, rw [← coe_coe] at aux, rw [← zpow_coe_nat, hi₀, ← int.mod_add_div n k, zpow_add, zpow_mul, aux, one_zpow, mul_one] } end lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) : ∃ i < k, ζ ^ i = ξ := begin lift ζ to Rˣ using h.is_unit h0, lift ξ to Rˣ using is_unit_of_pow_eq_one hξ h0.ne', lift k to ℕ+ using h0, simp only [← units.coe_pow, ← units.ext_iff], rw coe_units_iff at h, apply h.eq_pow_of_mem_roots_of_unity, rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one] end lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : Rˣ} (h : is_primitive_root ζ k) : is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one, rw h.pow_iff_coprime k.pos at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) : is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0, rw h.pow_iff_coprime h0 at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin let e := h.zmod_equiv_zpowers, haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ e.to_equiv, calc fintype.card (roots_of_unity n R) = fintype.card (subgroup.zpowers ζ) : fintype.card_congr $ by rw h.zpowers_eq ... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm ... = n : zmod.card n end lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin obtain ⟨ζ, hζ⟩ := h.is_unit n.pos, rw [← hζ, is_primitive_root.coe_units_iff] at h, exact h.card_roots_of_unity' end /-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n` if there is a primitive root of unity in `R`. -/ lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).card = n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.card_zero, nth_roots_zero] }, rw eq_iff_le_not_lt, use card_nth_roots n 1, { rw [not_lt], have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)} ≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.dedup_le _), rw multiset.card_attach at hcard, rw ← pnat.to_pnat'_coe hpos at hcard h ⊢, set m := nat.to_pnat' n, rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard, exact hcard } end /-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements if there is a primitive root of unity in `R`. -/ lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.nodup_zero, nth_roots_zero] }, apply (@multiset.dedup_eq_self R _ _).1, rw eq_iff_le_not_lt, split, { exact multiset.dedup_le (nth_roots n (1 : R)) }, { by_contra ha, replace ha := multiset.card_lt_of_lt ha, rw card_nth_roots h at ha, have hrw : (nth_roots n (1 : R)).dedup.card = fintype.card {x // x ∈ (nth_roots n (1 : R))}, { set fs := (⟨(nth_roots n (1 : R)).dedup, multiset.nodup_dedup _⟩ : finset R), rw [← finset.card_mk, ← fintype.card_of_subtype fs _], intro x, simp only [multiset.mem_dedup, finset.mem_mk] }, rw ← pnat.to_pnat'_coe hpos at h hrw ha, set m := nat.to_pnat' n, rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at ha, exact nat.lt_asymm ha ha } end @[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots_finset n R).card = n := by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots] open_locale nat /-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/ lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) : (primitive_roots k R).card = φ k := begin by_cases h0 : k = 0, { simp [h0], }, symmetry, refine finset.card_congr (λ i _, ζ ^ i) _ _ _, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i - hi, rw mem_primitive_roots (nat.pos_of_ne_zero h0), exact h.pow_of_coprime i hi.symm }, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i j hi - hj - H, exact h.pow_inj hi hj H }, { simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ], intros ξ hξ, rw [mem_primitive_roots (nat.pos_of_ne_zero h0), h.is_primitive_root_iff (nat.pos_of_ne_zero h0)] at hξ, rcases hξ with ⟨i, hin, hi, H⟩, exact ⟨i, ⟨hin, hi.symm⟩, H⟩ } end /-- The sets `primitive_roots k R` are pairwise disjoint. -/ lemma disjoint {k l : ℕ} (h : k ≠ l) : disjoint (primitive_roots k R) (primitive_roots l R) := finset.disjoint_left.2 $ λ z hk hl, h $ (is_primitive_root_of_mem_primitive_roots hk).unique $ is_primitive_root_of_mem_primitive_roots hl /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. This holds for any `nat`, not just `pnat`, see `nth_roots_one_eq_bUnion_primitive_roots`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors ↑n).bUnion (λ i, (primitive_roots i R)) := begin symmetry, apply finset.eq_of_subset_of_card_le, { intros x, simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), exists_prop, finset.mem_bUnion, finset.mem_filter, finset.mem_range, mem_nth_roots, finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff], rintro ⟨a, ⟨d, hd⟩, ha⟩, have hazero : 0 < a, { contrapose! hd with ha0, simp only [nonpos_iff_eq_zero, zero_mul, *] at *, exact n.ne_zero }, rw mem_primitive_roots hazero at ha, rw [hd, pow_mul, ha.pow_eq_one, one_pow] }, { apply le_of_eq, rw [h.card_nth_roots_finset, finset.card_bUnion], { nth_rewrite_lhs 0 ← nat.sum_totient n, refine sum_congr rfl _, simp only [nat.mem_divisors], rintro k ⟨⟨d, hd⟩, -⟩, rw mul_comm at hd, rw (h.pow n.pos hd).card_primitive_roots }, { intros i hi j hj hdiff, exact disjoint hdiff } } end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors n).bUnion (λ i, (primitive_roots i R)) := begin by_cases hn : n = 0, { simp [hn], }, exact @nth_roots_one_eq_bUnion_primitive_roots' _ _ _ _ ⟨n, nat.pos_of_ne_zero hn⟩ h end end is_domain section minpoly open minpoly section comm_ring variables {n : ℕ} {K : Type*} [comm_ring K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) include n μ h hpos /--`μ` is integral over `ℤ`. -/ lemma is_integral : is_integral ℤ μ := begin use (X ^ n - 1), split, { exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) }, { simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub, sub_self] } end section is_domain variables [is_domain K] [char_zero K] omit hpos /--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/ lemma minpoly_dvd_X_pow_sub_one : minpoly ℤ μ ∣ X ^ n - 1 := begin rcases n.eq_zero_or_pos with rfl | hpos, { simp }, apply minpoly.gcd_domain_dvd (is_integral h hpos) (monic_X_pow_sub_C 1 hpos.ne').ne_zero, simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, eq_int_cast, int.cast_one, aeval_one, alg_hom.map_sub, sub_self] end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/ lemma separable_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) : separable (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := begin have hdvd : (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) ∣ X ^ n - 1, { simpa [polynomial.map_pow, map_X, polynomial.map_one, polynomial.map_sub] using ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))) (minpoly_dvd_X_pow_sub_one h) }, refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 hzero) end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/ lemma squarefree_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) : squarefree (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := (separable_minpoly_mod h hdiv).squarefree /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `expand ℤ p Q`. -/ lemma minpoly_dvd_expand {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ n) : minpoly ℤ μ ∣ expand ℤ p (minpoly ℤ (μ ^ p)) := begin rcases n.eq_zero_or_pos with rfl | hpos, { simp * at *, }, refine minpoly.gcd_domain_dvd (h.is_integral hpos) _ _, { apply monic.ne_zero, rw [polynomial.monic, leading_coeff, nat_degree_expand, mul_comm, coeff_expand_mul' (nat.prime.pos hprime), ← leading_coeff, ← polynomial.monic], exact minpoly.monic (is_integral (pow_of_prime h hprime hdiv) hpos) }, { rw [aeval_def, coe_expand, ← comp, eval₂_eq_eval_map, map_comp, polynomial.map_pow, map_X, eval_comp, eval_pow, eval_X, ← eval₂_eq_eval_map, ← aeval_def], exact minpoly.aeval _ _ } end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q ^ p` modulo `p`. -/ lemma minpoly_dvd_pow_mod {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) ^ p := begin set Q := minpoly ℤ (μ ^ p), have hfrob : map (int.cast_ring_hom (zmod p)) Q ^ p = map (int.cast_ring_hom (zmod p)) (expand ℤ p Q), by rw [← zmod.expand_card, map_expand], rw [hfrob], apply ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))), exact minpoly_dvd_expand h hprime.1 hdiv end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q` modulo `p`. -/ lemma minpoly_dvd_mod_p {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) := (unique_factorization_monoid.dvd_pow_iff_dvd_of_squarefree (squarefree_minpoly_mod h hdiv) hprime.1.ne_zero).1 (minpoly_dvd_pow_mod h hdiv) /-- If `p` is a prime that does not divide `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ p` are the same. -/ lemma minpoly_eq_pow {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : minpoly ℤ μ = minpoly ℤ (μ ^ p) := begin by_cases hn : n = 0, { simp * at *, }, have hpos := nat.pos_of_ne_zero hn, by_contra hdiff, set P := minpoly ℤ μ, set Q := minpoly ℤ (μ ^ p), have Pmonic : P.monic := minpoly.monic (h.is_integral hpos), have Qmonic : Q.monic := minpoly.monic ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have Pirr : irreducible P := minpoly.irreducible (h.is_integral hpos), have Qirr : irreducible Q := minpoly.irreducible ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have PQprim : is_primitive (P * Q) := Pmonic.is_primitive.mul Qmonic.is_primitive, have prod : P * Q ∣ X ^ n - 1, { rw [(is_primitive.int.dvd_iff_map_cast_dvd_map_cast (P * Q) (X ^ n - 1) PQprim (monic_X_pow_sub_C (1 : ℤ) (ne_of_gt hpos)).is_primitive), polynomial.map_mul], refine is_coprime.mul_dvd _ _ _, { have aux := is_primitive.int.irreducible_iff_irreducible_map_cast Pmonic.is_primitive, refine (dvd_or_coprime _ _ (aux.1 Pirr)).resolve_left _, rw map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic, intro hdiv, refine hdiff (eq_of_monic_of_associated Pmonic Qmonic _), exact associated_of_dvd_dvd hdiv (Pirr.dvd_symm Qirr hdiv) }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2, exact minpoly_dvd_X_pow_sub_one h }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Qmonic).2, exact minpoly_dvd_X_pow_sub_one (pow_of_prime h hprime.1 hdiv) } }, replace prod := ring_hom.map_dvd ((map_ring_hom (int.cast_ring_hom (zmod p)))) prod, rw [coe_map_ring_hom, polynomial.map_mul, polynomial.map_sub, polynomial.map_one, polynomial.map_pow, map_X] at prod, obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hdiv, rw [hR, ← mul_assoc, ← polynomial.map_mul, ← sq, polynomial.map_pow] at prod, have habs : map (int.cast_ring_hom (zmod p)) P ^ 2 ∣ map (int.cast_ring_hom (zmod p)) P ^ 2 * R, { use R }, replace habs := lt_of_lt_of_le (part_enat.coe_lt_coe.2 one_lt_two) (multiplicity.le_multiplicity_of_pow_dvd (dvd_trans habs prod)), have hfree : squarefree (X ^ n - 1 : (zmod p)[X]), { exact (separable_X_pow_sub_C 1 (λ h, hdiv $ (zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 h) one_ne_zero).squarefree }, cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree (map (int.cast_ring_hom (zmod p)) P) with hle hunit, { rw nat.cast_one at habs, exact hle.not_lt habs }, { replace hunit := degree_eq_zero_of_is_unit hunit, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom (zmod p)) _ at hunit, { exact (minpoly.degree_pos (is_integral h hpos)).ne' hunit }, simp only [Pmonic, eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ m` are the same. -/ lemma minpoly_eq_pow_coprime {m : ℕ} (hcop : nat.coprime m n) : minpoly ℤ μ = minpoly ℤ (μ ^ m) := begin revert n hcop, refine unique_factorization_monoid.induction_on_prime m _ _ _, { intros n hn h, congr, simpa [(nat.coprime_zero_left n).mp hn] using h }, { intros u hunit n hcop h, congr, simp [nat.is_unit_iff.mp hunit] }, { intros a p ha hprime hind n hcop h, rw hind (nat.coprime.coprime_mul_left hcop) h, clear hind, replace hprime := hprime.nat_prime, have hdiv := (nat.prime.coprime_iff_not_dvd hprime).1 (nat.coprime.coprime_mul_right hcop), haveI := fact.mk hprime, rw [minpoly_eq_pow (h.pow_of_coprime a (nat.coprime.coprime_mul_left hcop)) hdiv], congr' 1, ring_exp } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomial of a primitive `n`-th root of unity `μ` has `μ ^ m` as root. -/ lemma pow_is_root_minpoly {m : ℕ} (hcop : nat.coprime m n) : is_root (map (int.cast_ring_hom K) (minpoly ℤ μ)) (μ ^ m) := by simpa [minpoly_eq_pow_coprime h hcop, eval_map, aeval_def (μ ^ m) _] using minpoly.aeval ℤ (μ ^ m) /-- `primitive_roots n K` is a subset of the roots of the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma is_roots_of_minpoly : primitive_roots n K ⊆ (map (int.cast_ring_hom K) (minpoly ℤ μ)).roots.to_finset := begin by_cases hn : n = 0, { simp * at *, }, have hpos := nat.pos_of_ne_zero hn, intros x hx, obtain ⟨m, hle, hcop, rfl⟩ := (is_primitive_root_iff h hpos).1 ((mem_primitive_roots hpos).1 hx), simpa [multiset.mem_to_finset, mem_roots (map_monic_ne_zero $ minpoly.monic $ is_integral h hpos)] using pow_is_root_minpoly h hcop end /-- The degree of the minimal polynomial of `μ` is at least `totient n`. -/ lemma totient_le_degree_minpoly : nat.totient n ≤ (minpoly ℤ μ).nat_degree := let P : ℤ[X] := minpoly ℤ μ,-- minimal polynomial of `μ` P_K : K[X] := map (int.cast_ring_hom K) P -- minimal polynomial of `μ` sent to `K[X]` in calc n.totient = (primitive_roots n K).card : h.card_primitive_roots.symm ... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h) ... ≤ P_K.roots.card : multiset.to_finset_card_le _ ... ≤ P_K.nat_degree : card_roots' _ ... ≤ P.nat_degree : nat_degree_map_le _ _ end is_domain end comm_ring end minpoly section automorphisms variables {S} [comm_ring S] [is_domain S] {μ : S} {n : ℕ+} (hμ : is_primitive_root μ n) (R) [comm_ring R] [algebra R S] /-- The `monoid_hom` that takes an automorphism to the power of μ that μ gets mapped to under it. -/ noncomputable def aut_to_pow : (S ≃ₐ[R] S) →* (zmod n)ˣ := let μ' := hμ.to_roots_of_unity in have ho : order_of μ' = n := by rw [hμ.eq_order_of, ←hμ.coe_to_roots_of_unity_coe, order_of_units, order_of_subgroup], monoid_hom.to_hom_units { to_fun := λ σ, (map_root_of_unity_eq_pow_self σ.to_alg_hom μ').some, map_one' := begin generalize_proofs h1, have h := h1.some_spec, dsimp only [alg_equiv.one_apply, alg_equiv.to_ring_equiv_eq_coe, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom, alg_equiv.coe_ring_equiv] at *, replace h : μ' = μ' ^ h1.some := roots_of_unity.coe_injective (by simpa only [roots_of_unity.coe_pow] using h), rw ←pow_one μ' at h {occs := occurrences.pos [1]}, rw [←@nat.cast_one $ zmod n, zmod.nat_coe_eq_nat_coe_iff, ←ho, ←pow_eq_pow_iff_modeq μ', h] end, map_mul' := begin generalize_proofs hxy' hx' hy', have hxy := hxy'.some_spec, have hx := hx'.some_spec, have hy := hy'.some_spec, dsimp only [alg_equiv.to_ring_equiv_eq_coe, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom, alg_equiv.coe_ring_equiv, alg_equiv.mul_apply] at *, replace hxy : x (↑μ' ^ hy'.some) = ↑μ' ^ hxy'.some := hy ▸ hxy, rw x.map_pow at hxy, replace hxy : ((μ' : S) ^ hx'.some) ^ hy'.some = μ' ^ hxy'.some := hx ▸ hxy, rw ←pow_mul at hxy, replace hxy : μ' ^ (hx'.some * hy'.some) = μ' ^ hxy'.some := roots_of_unity.coe_injective (by simpa only [roots_of_unity.coe_pow] using hxy), rw [←nat.cast_mul, zmod.nat_coe_eq_nat_coe_iff, ←ho, ←pow_eq_pow_iff_modeq μ', hxy] end } -- We are not using @[simps] in aut_to_pow to avoid a timeout. lemma coe_aut_to_pow_apply (f : S ≃ₐ[R] S) : (aut_to_pow R hμ f : zmod n) = ((map_root_of_unity_eq_pow_self f hμ.to_roots_of_unity).some : zmod n) := rfl @[simp] lemma aut_to_pow_spec (f : S ≃ₐ[R] S) : μ ^ (hμ.aut_to_pow R f : zmod n).val = f μ := begin rw is_primitive_root.coe_aut_to_pow_apply, generalize_proofs h, have := h.some_spec, dsimp only [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom] at this, refine (_ : ↑hμ.to_roots_of_unity ^ _ = _).trans this.symm, rw [←roots_of_unity.coe_pow, ←roots_of_unity.coe_pow], congr' 1, rw [pow_eq_pow_iff_modeq, ←order_of_subgroup, ←order_of_units, hμ.coe_to_roots_of_unity_coe, ←hμ.eq_order_of, zmod.val_nat_cast], exact nat.mod_modeq _ _ end end automorphisms end is_primitive_root
4c82d8df9d782e44276e384eb86aa84f27331d39
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/types/sigma.hlean
20dceb82f5ddf565d7e084b55eae5b383058874b
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
18,788
hlean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about sigma-types (dependent sums) -/ import types.prod open eq sigma sigma.ops equiv is_equiv function is_trunc sum unit namespace sigma variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a} definition destruct := @sigma.cases_on /- Paths in a sigma-type -/ protected definition eta : Π (u : Σa, B a), ⟨u.1 , u.2⟩ = u | eta ⟨u₁, u₂⟩ := idp definition eta2 : Π (u : Σa b, C a b), ⟨u.1, u.2.1, u.2.2⟩ = u | eta2 ⟨u₁, u₂, u₃⟩ := idp definition eta3 : Π (u : Σa b c, D a b c), ⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩ = u | eta3 ⟨u₁, u₂, u₃, u₄⟩ := idp definition dpair_eq_dpair [unfold 8] (p : a = a') (q : b =[p] b') : ⟨a, b⟩ = ⟨a', b'⟩ := apo011 sigma.mk p q definition sigma_eq [unfold 3 4] (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v := by induction u; induction v; exact (dpair_eq_dpair p q) definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 := ap pr1 p postfix `..1`:(max+1) := eq_pr1 definition eq_pr2 [unfold 5] (p : u = v) : u.2 =[p..1] v.2 := by induction p; exact idpo postfix `..2`:(max+1) := eq_pr2 definition dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : ⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩ = ⟨p, q⟩ := by induction u; induction v;esimp at *;induction q;esimp definition sigma_eq_pr1 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p := (dpair_sigma_eq p q)..1 definition sigma_eq_pr2 (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..2 =[sigma_eq_pr1 p q] q := (dpair_sigma_eq p q)..2 definition sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity definition eq2_pr1 {p q : u = v} (r : p = q) : p..1 = q..1 := ap eq_pr1 r definition eq2_pr2 {p q : u = v} (r : p = q) : p..2 =[eq2_pr1 r] q..2 := !pathover_ap (apdo eq_pr2 r) definition tr_pr1_sigma_eq {B' : A → Type} (p : u.1 = v.1) (q : u.2 =[p] v.2) : transport (λx, B' x.1) (sigma_eq p q) = transport B' p := by induction u; induction v; esimp at *;induction q; reflexivity protected definition ap_pr1 (p : u = v) : ap (λx : sigma B, x.1) p = p..1 := idp /- the uncurried version of sigma_eq. We will prove that this is an equivalence -/ definition sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v | sigma_eq_unc ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂ definition dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), ⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩ = pq | dpair_sigma_eq_unc ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂ definition sigma_eq_pr1_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..1 = pq.1 := (dpair_sigma_eq_unc pq)..1 definition sigma_eq_pr2_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : (sigma_eq_unc pq)..2 =[sigma_eq_pr1_unc pq] pq.2 := (dpair_sigma_eq_unc pq)..2 definition sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p := sigma_eq_eta p definition tr_sigma_eq_pr1_unc {B' : A → Type} (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) : transport (λx, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 := destruct pq tr_pr1_sigma_eq definition is_equiv_sigma_eq [instance] (u v : Σa, B a) : is_equiv (@sigma_eq_unc A B u v) := adjointify sigma_eq_unc (λp, ⟨p..1, p..2⟩) sigma_eq_eta_unc dpair_sigma_eq_unc definition sigma_eq_equiv (u v : Σa, B a) : (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) := (equiv.mk sigma_eq_unc _)⁻¹ᵉ definition dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' ) (p2 : a' = a'') (q2 : b' =[p2] b'') : dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 := by induction q1; induction q2; reflexivity definition sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2) (p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) : sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 := by induction u; induction v; induction w; apply dpair_eq_dpair_con local attribute dpair_eq_dpair [reducible] definition dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') : dpair_eq_dpair p q = dpair_eq_dpair p !pathover_tr ⬝ dpair_eq_dpair idp (pathover_idp_of_eq (tr_eq_of_pathover q)) := by induction q; reflexivity /- eq_pr1 commutes with the groupoid structure. -/ definition eq_pr1_idp (u : Σa, B a) : (refl u) ..1 = refl (u.1) := idp definition eq_pr1_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := !ap_con definition eq_pr1_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := !ap_inv /- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/ definition ap_dpair (q : b₁ = b₂) : ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq q) := by induction q; reflexivity /- Dependent transport is the same as transport along a sigma_eq. -/ definition transportD_eq_transport (p : a = a') (c : C a b) : p ▸D c = transport (λu, C (u.1) (u.2)) (dpair_eq_dpair p !pathover_tr) c := by induction p; reflexivity definition sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'} (r : p1 = q1) (s : p2 =[r] q2) : sigma_eq p1 p2 = sigma_eq q1 q2 := by induction s; reflexivity /- A path between paths in a total space is commonly shown component wise. -/ definition sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r] q..2) : p = q := begin induction p, induction u with u1 u2, transitivity sigma_eq q..1 q..2, apply sigma_eq_eq_sigma_eq r s, apply sigma_eq_eta, end definition sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r] q..2) : p = q := destruct rs sigma_eq2 definition ap_dpair_eq_dpair (f : Πa, B a → A') (p : a = a') (q : b =[p] b') : ap (sigma.rec f) (dpair_eq_dpair p q) = apo011 f p q := by induction q; reflexivity /- Transport -/ /- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD]. In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/ definition sigma_transport (p : a = a') (bc : Σ(b : B a), C a b) : p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; reflexivity /- The special case when the second variable doesn't depend on the first is simpler. -/ definition sigma_transport_nondep {B : Type} {C : A → B → Type} (p : a = a') (bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, p ▸ bc.2⟩ := by induction p; induction bc; reflexivity /- Or if the second variable contains a first component that doesn't depend on the first. -/ definition sigma_transport2_nondep {C : A → Type} {D : Π a:A, B a → C a → Type} (p : a = a') (bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ := begin induction p, induction bcd with b cd, induction cd, reflexivity end /- Pathovers -/ definition etao (p : a = a') (bc : Σ(b : B a), C a b) : bc =[p] ⟨p ▸ bc.1, p ▸D bc.2⟩ := by induction p; induction bc; apply idpo definition sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b) (r : u.1 =[p] v.1) (s : u.2 =[apo011 C p r] v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, esimp [apo011] at s, induction s using idp_rec_on, apply idpo end /- TODO: * define the projections from the type u =[p] v * show that the uncurried version of sigma_pathover is an equivalence -/ /- Functorial action -/ variables (f : A → A') (g : Πa, B a → B' (f a)) definition sigma_functor [unfold 7] (u : Σa, B a) : Σa', B' a' := ⟨f u.1, g u.1 u.2⟩ definition total [reducible] [unfold 5] {B' : A → Type} (g : Πa, B a → B' a) (u : Σa, B a) : Σa', B' a' := sigma_functor id g u /- Equivalences -/ definition is_equiv_sigma_functor [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : is_equiv (sigma_functor f g) := adjointify (sigma_functor f g) (sigma_functor f⁻¹ (λ(a' : A') (b' : B' a'), ((g (f⁻¹ a'))⁻¹ (transport B' (right_inv f a')⁻¹ b')))) begin intro u', induction u' with a' b', apply sigma_eq (right_inv f a'), rewrite [▸*,right_inv (g (f⁻¹ a')),▸*], apply tr_pathover end begin intro u, induction u with a b, apply (sigma_eq (left_inv f a)), apply pathover_of_tr_eq, rewrite [▸*,adj f,-(fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹)), ▸*,tr_compose B' f,tr_inv_tr,left_inv] end definition sigma_equiv_sigma_of_is_equiv [constructor] [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') := equiv.mk (sigma_functor f g) !is_equiv_sigma_functor definition sigma_equiv_sigma [constructor] (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (to_fun Hf a)) : (Σa, B a) ≃ (Σa', B' a') := sigma_equiv_sigma_of_is_equiv (to_fun Hf) (λ a, to_fun (Hg a)) definition sigma_equiv_sigma_id [constructor] {B' : A → Type} (Hg : Π a, B a ≃ B' a) : (Σa, B a) ≃ Σa, B' a := sigma_equiv_sigma equiv.refl Hg definition sigma_equiv_sigma_left [constructor] (Hf : A ≃ A') : (Σa, B a) ≃ (Σa', B (to_inv Hf a')) := sigma_equiv_sigma Hf (λ a, equiv_ap B !right_inv⁻¹) definition ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') : ap (sigma_functor f g) (sigma_eq p q) = sigma_eq (ap f p) (pathover.rec_on q idpo) := by induction q; reflexivity -- definition ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) -- : ap (sigma_functor f g) (sigma_eq p q) = -- sigma_eq (ap f p) -- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) := -- by induction u; induction v; apply ap_sigma_functor_eq_dpair /- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/ definition is_equiv_pr1 [instance] [constructor] (B : A → Type) [H : Π a, is_contr (B a)] : is_equiv (@pr1 A B) := adjointify pr1 (λa, ⟨a, !center⟩) (λa, idp) (λu, sigma_eq idp (pathover_idp_of_eq !center_eq)) definition sigma_equiv_of_is_contr_right [constructor] [H : Π a, is_contr (B a)] : (Σa, B a) ≃ A := equiv.mk pr1 _ /- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/ definition sigma_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A] : (Σa, B a) ≃ B (center A) := equiv.MK (λu, (center_eq u.1)⁻¹ ▸ u.2) (λb, ⟨!center, b⟩) (λb, ap (λx, x ▸ b) !hprop_eq_of_is_contr) (λu, sigma_eq !center_eq !tr_pathover) /- Associativity -/ --this proof is harder than in Coq because we don't have eta definitionally for sigma definition sigma_assoc_equiv [constructor] (C : (Σa, B a) → Type) : (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩) (λuc, ⟨uc.1.1, uc.1.2, !sigma.eta⁻¹ ▸ uc.2⟩) begin intro uc, induction uc with u c, induction u, reflexivity end begin intro av, induction av with a v, induction v, reflexivity end) open prod prod.ops definition assoc_equiv_prod [constructor] (C : (A × A') → Type) : (Σa a', C (a,a')) ≃ (Σu, C u) := equiv.mk _ (adjointify (λav, ⟨(av.1, av.2.1), av.2.2⟩) (λuc, ⟨pr₁ (uc.1), pr₂ (uc.1), !prod.eta⁻¹ ▸ uc.2⟩) proof (λuc, destruct uc (λu, prod.destruct u (λa b c, idp))) qed proof (λav, destruct av (λa v, destruct v (λb c, idp))) qed) /- Symmetry -/ definition comm_equiv_unc (C : A × A' → Type) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) := calc (Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod ... ≃ Σv, C (flip v) : sigma_equiv_sigma !prod_comm_equiv (λu, prod.destruct u (λa a', equiv.refl)) ... ≃ Σa' a, C (a, a') : assoc_equiv_prod definition sigma_comm_equiv [constructor] (C : A → A' → Type) : (Σa a', C a a') ≃ (Σa' a, C a a') := comm_equiv_unc (λu, C (prod.pr1 u) (prod.pr2 u)) definition equiv_prod [constructor] (A B : Type) : (Σ(a : A), B) ≃ A × B := equiv.mk _ (adjointify (λs, (s.1, s.2)) (λp, ⟨pr₁ p, pr₂ p⟩) proof (λp, prod.destruct p (λa b, idp)) qed proof (λs, destruct s (λa b, idp)) qed) definition comm_equiv_nondep (A B : Type) : (Σ(a : A), B) ≃ Σ(b : B), A := calc (Σ(a : A), B) ≃ A × B : equiv_prod ... ≃ B × A : prod_comm_equiv ... ≃ Σ(b : B), A : equiv_prod /- Interaction with other type constructors -/ definition sigma_empty_left [constructor] (B : empty → Type) : (Σx, B x) ≃ empty := begin fapply equiv.MK, { intro v, induction v, contradiction}, { intro x, contradiction}, { intro x, contradiction}, { intro v, induction v, contradiction}, end definition sigma_empty_right [constructor] (A : Type) : (Σ(a : A), empty) ≃ empty := begin fapply equiv.MK, { intro v, induction v, contradiction}, { intro x, contradiction}, { intro x, contradiction}, { intro v, induction v, contradiction}, end definition sigma_unit_left [constructor] (B : unit → Type) : (Σx, B x) ≃ B star := !sigma_equiv_of_is_contr_left definition sigma_unit_right [constructor] (A : Type) : (Σ(a : A), unit) ≃ A := !sigma_equiv_of_is_contr_right definition sigma_sum_left [constructor] (B : A + A' → Type) : (Σp, B p) ≃ (Σa, B (inl a)) + (Σa, B (inr a)) := begin fapply equiv.MK, { intro v, induction v with p b, induction p: append (apply inl) (apply inr); constructor; assumption }, { intro p, induction p with v v: induction v; constructor; assumption}, { intro p, induction p with v v: induction v; reflexivity}, { intro v, induction v with p b, induction p: reflexivity}, end definition sigma_sum_right [constructor] (B C : A → Type) : (Σa, B a + C a) ≃ (Σa, B a) + (Σa, C a) := begin fapply equiv.MK, { intro v, induction v with a p, induction p: append (apply inl) (apply inr); constructor; assumption}, { intro p, induction p with v v: induction v; constructor; append (apply inl) (apply inr); assumption}, { intro p, induction p with v v: induction v; reflexivity}, { intro v, induction v with a p, induction p: reflexivity}, end /- ** Universal mapping properties -/ /- *** The positive universal property. -/ section definition is_equiv_sigma_rec [instance] (C : (Σa, B a) → Type) : is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) := adjointify _ (λ g a b, g ⟨a, b⟩) (λ g, proof eq_of_homotopy (λu, destruct u (λa b, idp)) qed) (λ f, refl f) definition equiv_sigma_rec (C : (Σa, B a) → Type) : (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) := equiv.mk sigma.rec _ /- *** The negative universal property. -/ protected definition coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A) : Σ(b : B a), C a b := ⟨fg.1 a, fg.2 a⟩ protected definition coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b := sigma.coind_unc ⟨f, g⟩ a --is the instance below dangerous? --in Coq this can be done without function extensionality definition is_equiv_coind [instance] (C : Πa, B a → Type) : is_equiv (@sigma.coind_unc _ _ C) := adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩) (λ h, proof eq_of_homotopy (λu, !sigma.eta) qed) (λfg, destruct fg (λ(f : Π (a : A), B a) (g : Π (x : A), C x (f x)), proof idp qed)) definition sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) := equiv.mk sigma.coind_unc _ end /- Subtypes (sigma types whose second components are hprops) -/ definition subtype [reducible] {A : Type} (P : A → Type) [H : Πa, is_hprop (P a)] := Σ(a : A), P a notation [parsing_only] `{` binder `|` r:(scoped:1 P, subtype P) `}` := r /- To prove equality in a subtype, we only need equality of the first component. -/ definition subtype_eq [H : Πa, is_hprop (B a)] {u v : {a | B a}} : u.1 = v.1 → u = v := sigma_eq_unc ∘ inv pr1 definition is_equiv_subtype_eq [H : Πa, is_hprop (B a)] (u v : {a | B a}) : is_equiv (subtype_eq : u.1 = v.1 → u = v) := !is_equiv_compose local attribute is_equiv_subtype_eq [instance] definition equiv_subtype [H : Πa, is_hprop (B a)] (u v : {a | B a}) : (u.1 = v.1) ≃ (u = v) := equiv.mk !subtype_eq _ definition subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_hprop (B a)] (u v : Σa, B a) : u = v → u.1 = v.1 := subtype_eq⁻¹ᶠ local attribute subtype_eq_inv [reducible] definition is_equiv_subtype_eq_inv {A : Type} {B : A → Type} [H : Πa, is_hprop (B a)] (u v : Σa, B a) : is_equiv (subtype_eq_inv u v) := _ /- truncatedness -/ theorem is_trunc_sigma (B : A → Type) (n : trunc_index) [HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) := begin revert A B HA HB, induction n with n IH, { intro A B HA HB, fapply is_trunc_equiv_closed_rev, apply sigma_equiv_of_is_contr_left}, { intro A B HA HB, apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply sigma_eq_equiv, exact IH _ _ _ _} end theorem is_trunc_subtype (B : A → hprop) (n : trunc_index) [HA : is_trunc (n.+1) A] : is_trunc (n.+1) (Σa, B a) := @(is_trunc_sigma B (n.+1)) _ (λa, !is_trunc_succ_of_is_hprop) end sigma attribute sigma.is_trunc_sigma [instance] [priority 1490] attribute sigma.is_trunc_subtype [instance] [priority 1200]
ac807f1dc187d57148d8868f0536b371ea58e7d0
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/types/prod/product_type_syntax.lean
4d7cabcb130c6462ff95303089bf198b4a4887fd
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
1,592
lean
/- We've seen how to write simple product types and associated funtions. -/ namespace ex1 inductive prod_nat_nat : Type | mk : ℕ → ℕ → prod_nat_nat def p := prod_nat_nat.mk 3 5 def fst (p : prod_nat_nat) : ℕ := match p with | prod_nat_nat.mk x y := x end def sec (p : prod_nat_nat) : ℕ := match p with | prod_nat_nat.mk x y := y end #eval fst (prod_nat_nat.mk 3 4) #eval sec (prod_nat_nat.mk 3 4) end ex1 /- We can also use C-style argument notation when defining the type. -/ namespace ex2 inductive prod_nat_nat : Type | mk (x y : ℕ) : prod_nat_nat def fst (p : prod_nat_nat) : ℕ := match p with | prod_nat_nat.mk x y := x end def sec (p : prod_nat_nat) : ℕ := match p with | prod_nat_nat.mk x y := x end #eval fst (prod_nat_nat.mk 3 4) #eval sec (prod_nat_nat.mk 3 4) end ex2 /- Even better though, when defining a product type, is to use "structure" syntax. The key idea is that we give names to fields, just as in Java or Python, and we can then refer to field values by name, rather than having to write our own "projection functions". Instead, projection functions are provided for us. This is what's really happening in Java, too. -/ namespace ex3 structure prod_nat_nat : Type := mk :: (fst : ℕ) (snd : ℕ) /- No more explicit projection functions! -/ #eval prod_nat_nat.fst (prod_nat_nat.mk 3 4) #eval prod_nat_nat.snd (prod_nat_nat.mk 3 4) #eval (prod_nat_nat.mk 3 4).fst #eval (prod_nat_nat.mk 3 4).snd def p := (prod_nat_nat.mk 3 4) #eval p.fst #eval p.snd end ex3
65dd851f90cfa4bc333aaff444991e9ab1dc2af2
db5883ff1bc38a1433ebf33b20d78352c2de4982
/LEAN/Basics.lean
415e6a6054558dd4ebf9966cec0e2fd5475fa331
[ "MIT" ]
permissive
FiveEyes/SoftwareFoundationsSolution
416d72e2c30e5ad085313d2965fc81904b95d538
d66c636107ac6fd7276504324c6da28c4775dd75
refs/heads/master
1,629,128,378,858
1,511,178,214,000
1,511,178,214,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
747
lean
inductive day : Type | monday : day | tuesday : day | wednesday : day | thursday : day | friday : day | saturday : day | sunday : day def next_weekday : day → day | day.monday := day.tuesday | day.tuesday := day.wednesday | day.wednesday := day.thursday | day.thursday := day.friday | day.friday := day.monday | day.saturday := day.monday | day.sunday := day.monday #eval (next_weekday day.friday) #eval (next_weekday (next_weekday day.saturday)) #check (next_weekday (next_weekday day.saturday)) /- def test_next_weekday : Prop := (next_weekday (next_weekday day.saturday)) = day.tuesday #check test_next_weekday -/ /- theorem test_next_weekday : (next_weekday (next_weekday day.saturday)) = day.tuesday := begin end -/
6ced9c26259f358fe54f342545e421633e87fdc4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/sym.lean
74370a7fa284359ab91f7de531231a83ee2e2335
[ "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
4,621
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller. -/ import data.multiset.basic import data.vector2 import tactic.tidy /-! # Symmetric powers This file defines symmetric powers of a type. The nth symmetric power consists of homogeneous n-tuples modulo permutations by the symmetric group. The special case of 2-tuples is called the symmetric square, which is addressed in more detail in `data.sym2`. TODO: This was created as supporting material for `data.sym2`; it needs a fleshed-out interface. ## Tags symmetric powers -/ universes u /-- The nth symmetric power is n-tuples up to permutation. We define it as a subtype of `multiset` since these are well developed in the library. We also give a definition `sym.sym'` in terms of vectors, and we show these are equivalent in `sym.sym_equiv_sym'`. -/ def sym (α : Type u) (n : ℕ) := {s : multiset α // s.card = n} /-- This is the `list.perm` setoid lifted to `vector`. -/ def vector.perm.is_setoid (α : Type u) (n : ℕ) : setoid (vector α n) := { r := λ a b, list.perm a.1 b.1, iseqv := by { rcases list.perm.eqv α with ⟨hr, hs, ht⟩, tidy, } } local attribute [instance] vector.perm.is_setoid namespace sym variables {α : Type u} {n : ℕ} /-- This is the quotient map that takes a list of n elements as an n-tuple and produces an nth symmetric power. -/ def of_vector (x : vector α n) : sym α n := ⟨↑x.val, by { rw multiset.coe_card, exact x.2 }⟩ instance : has_lift (vector α n) (sym α n) := { lift := of_vector } /-- The unique element in `sym α 0`. -/ @[pattern] def nil : sym α 0 := ⟨0, by tidy⟩ /-- Inserts an element into the term of `sym α n`, increasing the length by one. -/ @[pattern] def cons : α → sym α n → sym α (nat.succ n) | a ⟨s, h⟩ := ⟨a ::ₘ s, by rw [multiset.card_cons, h]⟩ notation a :: b := cons a b @[simp] lemma cons_inj_right (a : α) (s s' : sym α n) : a :: s = a :: s' ↔ s = s' := by { cases s, cases s', delta cons, simp, } @[simp] lemma cons_inj_left (a a' : α) (s : sym α n) : a :: s = a' :: s ↔ a = a' := by { cases s, delta cons, simp, } lemma cons_swap (a b : α) (s : sym α n) : a :: b :: s = b :: a :: s := by { cases s, ext, delta cons, rw subtype.coe_mk, dsimp, exact multiset.cons_swap a b s_val } /-- `α ∈ s` means that `a` appears as one of the factors in `s`. -/ def mem (a : α) (s : sym α n) : Prop := a ∈ s.1 instance : has_mem α (sym α n) := ⟨mem⟩ instance decidable_mem [decidable_eq α] (a : α) (s : sym α n) : decidable (a ∈ s) := by { cases s, change decidable (a ∈ s_val), apply_instance } @[simp] lemma mem_cons {a b : α} {s : sym α n} : a ∈ b :: s ↔ a = b ∨ a ∈ s := begin cases s, change a ∈ b ::ₘ s_val ↔ a = b ∨ a ∈ s_val, simp, end lemma mem_cons_of_mem {a b : α} {s : sym α n} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 (or.inr h) @[simp] lemma mem_cons_self (a : α) (s : sym α n) : a ∈ a :: s := mem_cons.2 (or.inl rfl) lemma cons_of_coe_eq (a : α) (v : vector α n) : a :: (↑v : sym α n) = ↑(a ::ᵥ v) := by { unfold_coes, delta of_vector, delta cons, delta vector.cons, tidy } lemma sound {a b : vector α n} (h : a.val ~ b.val) : (↑a : sym α n) = ↑b := begin cases a, cases b, unfold_coes, dunfold of_vector, simp only [subtype.mk_eq_mk, multiset.coe_eq_coe], exact h, end /-- Another definition of the nth symmetric power, using vectors modulo permutations. (See `sym`.) -/ def sym' (α : Type u) (n : ℕ) := quotient (vector.perm.is_setoid α n) /-- This is `cons` but for the alternative `sym'` definition. -/ def cons' {α : Type u} {n : ℕ} : α → sym' α n → sym' α (nat.succ n) := λ a, quotient.map (vector.cons a) (λ ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ h, list.perm.cons _ h) notation a :: b := cons' a b /-- Multisets of cardinality n are equivalent to length-n vectors up to permutations. -/ def sym_equiv_sym' {α : Type u} {n : ℕ} : sym α n ≃ sym' α n := equiv.subtype_quotient_equiv_quotient_subtype _ _ (λ _, by refl) (λ _ _, by refl) lemma cons_equiv_eq_equiv_cons (α : Type u) (n : ℕ) (a : α) (s : sym α n) : a :: sym_equiv_sym' s = sym_equiv_sym' (a :: s) := by tidy section inhabited -- Instances to make the linter happy instance inhabited_sym [inhabited α] (n : ℕ) : inhabited (sym α n) := ⟨⟨multiset.repeat (default α) n, multiset.card_repeat _ _⟩⟩ instance inhabited_sym' [inhabited α] (n : ℕ) : inhabited (sym' α n) := ⟨quotient.mk' (vector.repeat (default α) n)⟩ end inhabited end sym
b4a77e4894247b7a27d9248470333d21b5d28c73
76df16d6c3760cb415f1294caee997cc4736e09b
/rosette-benchmarks-3/jitterbug/jitterbug/lean/src/bv/lemmas.lean
cfe25683a0393354b309f4639ec024d5fb4eeb86
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
20,841
lean
import .basic import .helper namespace bv open nat open bv.helper section fin variable {n : ℕ} @[simp] lemma lsb_cons (b : bool) (v : bv n) : (cons b v).lsb = b := fin.cons_zero _ _ @[simp] lemma tail_cons (b : bool) (v : bv n) : (cons b v).tail = v := fin.tail_cons _ _ @[simp] lemma cons_lsb_tail (v : bv (n + 1)) : cons v.lsb v.tail = v := fin.cons_self_tail _ @[simp] lemma msb_snoc (v : bv n) (b : bool) : (snoc v b).msb = b := fin.snoc_last _ _ @[simp] lemma init_snoc (v : bv n) (b : bool) : (snoc v b).init = v := fin.init_snoc _ _ @[simp] lemma snoc_init_msb (v : bv (n + 1)) : snoc v.init v.msb = v := fin.snoc_init_self _ lemma cons_snoc_eq_snoc_cons (b₁ : bool) (v : bv n) (b₂ : bool) : cons b₁ (snoc v b₂) = snoc (cons b₁ v) b₂ := fin.cons_snoc_eq_snoc_cons _ _ _ end fin section list variable {n : ℕ} @[norm_cast, simp] lemma nil_to_list (v : bv 0) : (v : list bool) = [] := rfl @[norm_cast] lemma cons_to_list (b : bool) (v : bv n) : (cons b v : list bool) = b :: (v : list bool) := by unfold_coes; simp [to_list, cons, list.of_fn_succ] @[norm_cast] lemma snoc_to_list : ∀ {n : ℕ} (v : bv n) (b : bool), (snoc v b : list bool) = (v : list bool) ++ [b] | 0 _ _ := rfl | (n + 1) v b := calc (v.snoc b : list bool) = (cons v.lsb (snoc v.tail b) : list bool) : by simp [cons_snoc_eq_snoc_cons] ... = (v.lsb :: v.tail : list bool) ++ [b] : by push_cast; simp [snoc_to_list] ... = (v : list bool) ++ [b] : by { norm_cast; simp } @[simp] lemma to_list_length {n : ℕ} (v : bv n) : (v : list bool).length = n := list.length_of_fn v @[norm_cast] lemma to_list_nth_le {n : ℕ} {v : bv n} (i : ℕ) (h h') : (v : list bool).nth_le i h' = v ⟨i, h⟩ := list.nth_le_of_fn' v h' @[norm_cast] theorem to_list_inj (v₁ v₂ : bv n) : (v₁ : list bool) = (v₂ : list bool) ↔ v₁ = v₂ := begin split; intro h; try { cc }, ext ⟨i, _⟩, rw [← @to_list_nth_le _ v₁, ← @to_list_nth_le _ v₂]; try { simpa }, congr, cc end @[ext] lemma heq_ext {n₁ n₂ : ℕ} (h : n₁ = n₂) {v₁ : bv n₁} {v₂ : bv n₂} : (∀ (i : fin n₁), v₁ i = v₂ ⟨i.val, h ▸ i.2⟩) → v₁ == v₂ := by simp [fin.heq_fun_iff h] theorem heq_iff_to_list {n₁ n₂ : ℕ} (h : n₁ = n₂) {v₁ : bv n₁} {v₂ : bv n₂} : v₁ == v₂ ↔ (v₁ : list bool) = (v₂ : list bool) := by induction h; simp [heq_iff_eq, to_list_inj] end list section nat variable {n : ℕ} @[norm_cast, simp] lemma nil_to_nat (v : bv 0) : (v : ℕ) = 0 := rfl @[norm_cast] lemma cons_to_nat (b : bool) (v : bv n) : (cons b v : ℕ) = nat.bit b (v : ℕ) := by unfold_coes; simp [to_nat] lemma to_nat_of_lsb_tail (v : bv (n + 1)) : (v : ℕ) = nat.bit v.lsb (v.tail : ℕ) := rfl @[norm_cast] lemma snoc_to_nat : ∀ {n : ℕ} (v : bv n) (b : bool), (snoc v b : ℕ) = (v : ℕ) + 2^n * cond b 1 0 | 0 _ b := by cases b; refl | (n + 1) v b := calc (snoc v b : ℕ) = (cons v.lsb (snoc v.tail b) : ℕ) : by simp [cons_snoc_eq_snoc_cons] ... = 2 * (snoc v.tail b : ℕ) + cond v.lsb 1 0 : by push_cast [bit_val] ... = 2 * (v.tail : ℕ) + cond v.lsb 1 0 + 2^(n + 1) * cond b 1 0 : by rw snoc_to_nat; ring_exp ... = (v : ℕ) + 2^(n + 1) * cond b 1 0 : by rw ← bit_val; norm_cast; simp lemma to_nat_le : ∀ {n : ℕ} (v : bv n), (v : ℕ) ≤ 2^n - 1 | 0 _ := by refl | (n + 1) v := calc (v : ℕ) = (v.init : ℕ) + 2^n * cond v.msb 1 0 : by norm_cast; simp ... ≤ 2^n - 1 + 2^n * cond v.msb 1 0 : by mono ... ≤ 2^n - 1 + 2^n : by cases v.msb; simp ... = 2^(n + 1) - 1 : by rw ← nat.sub_add_comm (pow2_pos _); ring_exp lemma to_nat_lt (v : bv n) : (v : ℕ) < 2^n := calc v.to_nat ≤ 2^n - 1 : to_nat_le _ ... < 2^n : sub_lt (pow2_pos _) one_pos @[simp] lemma to_nat_mod_eq (v : bv n) : (v : ℕ) % 2^n = (v : ℕ) := by { apply mod_eq_of_lt, apply to_nat_lt } @[norm_cast] lemma to_of_nat : ∀ (n a : ℕ), (@of_nat n a : ℕ) = a % 2^n | 0 _ := by simp [of_nat] | (n + 1) a := calc (@of_nat (n + 1) a : ℕ) = bit a.bodd ↑(@of_nat n a.div2) : by norm_cast ... = bit a.bodd (a.div2 % 2^n) : by rw to_of_nat ... = 2 * (a / 2 % 2^n) + a % 2 : by rw [bit_val, div2_val, mod_two_of_bodd] ... = a % 2^(n + 1) : by rw nat.mod_pow_succ two_pos @[simp] lemma of_to_nat : ∀ {n : ℕ} (v : bv n), bv.of_nat (v : ℕ) = v | 0 _ := dec_trivial | (n + 1) v := calc of_nat (v : ℕ) = of_nat (cons v.lsb v.tail : ℕ) : by simp ... = v : by push_cast; rw [of_nat, nat.bodd_bit, nat.div2_bit]; simp [of_to_nat] @[norm_cast] theorem to_nat_inj (v₁ v₂ : bv n) : (v₁ : ℕ) = (v₂ : ℕ) ↔ v₁ = v₂ := ⟨λ h, function.left_inverse.injective of_to_nat h, congr_arg _⟩ lemma to_int_mod_eq (v : bv n) : v.to_int % 2^n = (v : ℕ) := begin simp [to_int], cases decidable.em ((v : ℕ) < 2^(n - 1)) with h h; simp [h, int.sub_mod_self]; norm_cast; simp; congr end lemma of_to_int (v : bv n) : bv.of_int v.to_int = v := by simp [of_int, to_int_mod_eq] theorem to_int_inj (v₁ v₂ : bv n) : v₁.to_int = v₂.to_int ↔ v₁ = v₂ := ⟨λ h, function.left_inverse.injective of_to_int h, congr_arg _⟩ lemma msb_eq_ff_iff (v : bv (n + 1)) : v.msb = ff ↔ (v : ℕ) < 2^n := begin rw [← snoc_init_msb v], push_cast, cases v.msb; simp, apply to_nat_lt end end nat section literals variable {n : ℕ} @[norm_cast, simp] lemma zero_to_nat : ∀ {n : ℕ}, ((0 : bv n) : ℕ) = 0 | 0 := rfl | (n + 1) := calc ((0 : bv (n + 1)) : ℕ) = (cons ff (0 : bv n) : ℕ) : by push_cast; refl ... = 0 : by push_cast; simp [zero_to_nat] @[norm_cast] lemma umax_to_nat : ∀ {n : ℕ}, ((bv.umax : bv n) : ℕ) = 2^n - 1 | 0 := rfl | (n + 1) := calc ((bv.umax : bv (n + 1)) : ℕ) = ((cons tt (bv.umax : bv n)) : ℕ) : by push_cast; refl ... = 2 * (2^n - 1 + 1) - 1: by push_cast [bit_val, umax_to_nat]; ring ... = 2^(n + 1) - 1 : by rw [nat.sub_add_cancel (pow2_pos _)]; ring_exp @[norm_cast, simp] lemma one_to_nat : ((1 : bv (n + 1)) : ℕ) = 1 := calc ((1 : bv (n + 1)) : ℕ) = ((cons tt (0 : bv n)) : ℕ) : rfl ... = 1: by push_cast; simp [bit_val] @[norm_cast] lemma smin_to_nat : ((bv.smin : bv (n + 1)) : ℕ) = 2^n := calc ((bv.smin : bv (n + 1)) : ℕ) = ((snoc (0 : bv n) tt) : ℕ) : rfl ... = 2^n : by push_cast; simp @[norm_cast] lemma smax_to_nat : ((bv.smax : bv (n + 1)) : ℕ) = 2^n - 1 := calc ((bv.smax : bv (n + 1)) : ℕ) = ((snoc (bv.umax : bv n) ff) : ℕ) : rfl ... = 2^n - 1 : by push_cast; simp end literals section concatenation @[norm_cast] lemma concat_to_list {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) : (concat v₁ v₂ : list bool) = ↑v₂ ++ ↑v₁ := begin apply list.ext_le, { simp [add_comm] }, { intros i h₁ h₂, simp at h₁ h₂, rw to_list_nth_le _ h₁, cases decidable.em (i < n₂) with hlt hlt; simp [hlt, concat], { rw [list.nth_le_append, to_list_nth_le]; simpa }, { rw [list.nth_le_append_right, to_list_nth_le]; simp; omega } } end lemma concat_nil {n₁ : ℕ} (v₁ : bv n₁) (v₂ : bv 0) : v₁.concat v₂ = v₁ := by push_cast [← to_list_inj]; simp lemma concat_cons {n₁ n₂ : ℕ} (v₁ : bv n₁) (b : bool) (v₂ : bv n₂) : v₁.concat (cons b v₂) = cons b (v₁.concat v₂) := by push_cast [← to_list_inj]; simp @[norm_cast] lemma concat_to_nat : ∀ {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂), (concat v₁ v₂ : ℕ) = v₁ * 2^n₂ + v₂ | _ 0 _ _ := by simp [concat_nil] | _ (n₂ + 1) v₁ v₂ := calc (v₁.concat v₂ : ℕ) = ↑(v₁.concat (cons v₂.lsb v₂.tail)) : by simp ... = ↑(cons v₂.lsb (v₁.concat v₂.tail)) : by rw concat_cons ... = v₁ * 2^(n₂ + 1) + ↑(cons v₂.lsb v₂.tail) : by push_cast [bit_val, concat_to_nat]; ring_exp ... = v₁ * 2^(n₂ + 1) + v₂ : by simp @[simp] lemma zero_extend_to_nat (i : ℕ) {n : ℕ} (v : bv n) : (v.zero_extend i : ℕ) = v := by dsimp [zero_extend]; push_cast; simp end concatenation section extraction variables {n₁ n₂ : ℕ} @[norm_cast] lemma extract_to_list {n : ℕ} (i j : ℕ) (h₁ : i < n) (h₂ : j ≤ i) (v : bv n) : (v.extract i j h₁ h₂ : list bool) = ((v : list bool).take (i + 1)).drop j := begin apply list.ext_le, { simp, rw min_eq_left; omega }, { intros, rw [← list.nth_le_drop, ← list.nth_le_take], repeat { rw to_list_nth_le }, simp [extract], all_goals { simp at *; omega } } end @[norm_cast] lemma drop_to_list (v : bv (n₁ + n₂)) : (v.drop n₂ : list bool) = (v : list bool).drop n₂ := begin apply list.ext_le, { simp }, { intros, rw ← list.nth_le_drop, repeat { rw to_list_nth_le }, simp [drop], all_goals { simp at *; omega } } end @[norm_cast] lemma take_to_list (v : bv (n₁ + n₂)) : (v.take n₂ : list bool) = (v : list bool).take n₂ := begin apply list.ext_le, { simp }, { intros, rw ← list.nth_le_take, repeat { rw to_list_nth_le }, simp [take], all_goals { simp at *; omega } } end lemma drop_zero {n : ℕ} (v : bv n) : drop 0 v = v := by push_cast [← to_list_inj]; simp lemma drop_cons {n₁ n₂ : ℕ} (b : bool) (v : bv (n₁ + n₂)) : drop (n₂ + 1) (cons b v) = drop n₂ v := by push_cast [← to_list_inj]; simp @[norm_cast] lemma drop_to_nat : ∀ {n₁ n₂ : ℕ} (v : bv (n₁ + n₂)), (drop n₂ v : ℕ) = (v : ℕ) / 2^n₂ | _ 0 _ := by simp [drop_zero] | _ (n₂ + 1) v := by { rw [← cons_lsb_tail v, drop_cons, drop_to_nat], push_cast, simp [pow2_succ, ← nat.div_div_eq_div_mul] } lemma take_zero {n : ℕ} (v : bv n) : take 0 v = nil := dec_trivial lemma take_cons {n₁ n₂ : ℕ} (b : bool) (v : bv (n₁ + n₂)) : take (n₂ + 1) (cons b v) = cons b (take n₂ v) := by push_cast [← to_list_inj]; simp @[norm_cast] lemma take_to_nat : ∀ {n₁ n₂ : ℕ} (v : bv (n₁ + n₂)), (take n₂ v : ℕ) = (v : ℕ) % 2^n₂ | _ 0 _ := by simp [take_zero] | _ (n₂ + 1) v := by { rw [← cons_lsb_tail v, take_cons], push_cast, simp [take_to_nat, mod_pow_succ two_pos, ← bit_val] } lemma concat_drop_take {n₁ n₂ : ℕ} (v : bv (n₁ + n₂)) : concat (drop n₂ v) (take n₂ v) = v := by push_cast [← to_list_inj]; simp [list.take_append_drop] lemma drop_concat {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) : drop n₂ (concat v₁ v₂) = v₁ := by push_cast [← to_list_inj]; simp [list.drop_left'] lemma take_concat {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) : take n₂ (concat v₁ v₂) = v₂ := by push_cast [← to_list_inj]; simp [list.take_left'] end extraction section bitwise variable {n : ℕ} @[norm_cast] lemma not_to_nat (v : bv n) : (v.not : ℕ) = 2^n - 1 - v := begin apply symm, rw [nat.sub_eq_iff_eq_add (to_nat_le _), nat.sub_eq_iff_eq_add (pow2_pos _)], apply symm, induction n with n ih; try { refl }, calc (v.not : ℕ) + v + 1 = bit (!v.lsb) v.tail.not + bit v.lsb v.tail + 1 : rfl ... = 2 * (v.tail.not + v.tail + 1) : by cases v.lsb; simp [bit_val]; ring ... = 2^(n + 1) : by rw ih; ring_exp end @[norm_cast] lemma map₂_to_nat {f : bool → bool → bool} (h : f ff ff = ff) : ∀ {n : ℕ} (v₁ v₂ : bv n), (map₂ f v₁ v₂ : ℕ) = nat.bitwise f ↑v₁ ↑v₂ | 0 _ _ := by simp | (n + 1) v₁ v₂ := calc ↑(map₂ f v₁ v₂) = nat.bit (f v₁.lsb v₂.lsb) ↑(map₂ f v₁.tail v₂.tail) : rfl ... = nat.bitwise f (nat.bit v₁.lsb ↑(v₁.tail)) (nat.bit v₂.lsb ↑(v₂.tail)) : by rw [map₂_to_nat, nat.bitwise_bit h] ... = nat.bitwise f ↑v₁ ↑v₂ : by norm_cast; simp @[norm_cast] lemma and_to_nat : ∀ (v₁ v₂ : bv n), (v₁.and v₂ : ℕ) = nat.land ↑v₁ ↑v₂ := map₂_to_nat rfl @[norm_cast] lemma or_to_nat : ∀ (v₁ v₂ : bv n), (v₁.or v₂ : ℕ) = nat.lor ↑v₁ ↑v₂ := map₂_to_nat rfl @[norm_cast] lemma xor_to_nat : ∀ (v₁ v₂ : bv n), (v₁.xor v₂ : ℕ) = nat.lxor ↑v₁ ↑v₂ := map₂_to_nat rfl end bitwise section arithmetic variable {n : ℕ} @[norm_cast] lemma neg_to_nat (v : bv n) : (((-v) : bv n) : ℕ) = if (v : ℕ) = 0 then 0 else 2^n - v := begin have h : -v = bv.neg v := rfl, push_cast [h, bv.neg], cases eq.decidable (v : ℕ) 0 with h h; simp [h], apply mod_eq_of_lt, apply sub_lt (pow2_pos _) (nat.pos_of_ne_zero h) end @[norm_cast] lemma add_to_nat (v₁ v₂ : bv n) : ((v₁ + v₂ : bv n) : ℕ) = ((v₁ : ℕ) + (v₂ : ℕ)) % 2^n := begin have h : v₁ + v₂ = bv.add v₁ v₂ := rfl, push_cast [h, bv.add] end @[norm_cast] lemma sub_to_nat (v₁ v₂ : bv n) : ((v₁ - v₂ : bv n) : ℕ) = if (v₂ : ℕ) ≤ (v₁ : ℕ) then (v₁ : ℕ) - (v₂ : ℕ) else 2^n + (v₁ : ℕ) - (v₂ : ℕ) := begin have h : v₁ - v₂ = v₁ + -v₂ := rfl, push_cast [h], cases eq.decidable (v₂ : ℕ) 0 with hz hz; simp [hz], rw [← nat.add_sub_assoc (le_of_lt (to_nat_lt _)), add_comm], have h₁ := to_nat_lt v₁, have h₂ := to_nat_lt v₂, cases decidable.em ((v₂ : ℕ) ≤ (v₁ : ℕ)) with hcmp hcmp; simp [hcmp], { rw nat.add_sub_assoc hcmp, rw add_mod_left, apply mod_eq_of_lt, omega }, { apply mod_eq_of_lt, omega } end @[norm_cast] lemma mul_to_nat (v₁ v₂ : bv n) : ((v₁ * v₂ : bv n) : ℕ) = ((v₁ : ℕ) * (v₂ : ℕ)) % 2^n := begin have h : v₁ * v₂ = bv.mul v₁ v₂ := rfl, push_cast [h, bv.mul] end -- note that a % 0 = 0 for nat (rather than 2^n - 1) @[norm_cast] lemma udiv_to_nat (v₁ v₂ : bv n) : ((v₁ / v₂ : bv n) : ℕ) = if (v₂ : ℕ) = 0 then 2^n - 1 else (v₁ / v₂ : ℕ) := begin have h : v₁ / v₂ = bv.udiv v₁ v₂ := rfl, push_cast [h, bv.udiv], cases nat.decidable_eq (v₂ : ℕ) 0 with h h; simp [h], apply mod_eq_of_lt, apply lt_of_le_of_lt (nat.div_le_self _ _) (to_nat_lt _) end -- drop the zero case as a % 0 = a for nat @[norm_cast] lemma urem_to_nat (v₁ v₂ : bv n) : ((v₁ % v₂ : bv n) : ℕ) = (v₁ % v₂ : ℕ) := begin have h : v₁ % v₂ = bv.urem v₁ v₂ := rfl, push_cast [h, bv.urem], cases nat.decidable_eq (v₂ : ℕ) 0 with h h; simp [h], apply mod_eq_of_lt, apply lt_of_le_of_lt (mod_le _ _) (to_nat_lt _) end theorem urem_add_udiv (v₁ v₂ : bv n) : v₁ % v₂ + v₂ * (v₁ / v₂) = v₁ := begin push_cast [← to_nat_inj], cases nat.decidable_eq (v₂ : ℕ) 0 with h h; simp [h], simp [nat.mod_add_div] end end arithmetic section ring variable {n : ℕ} protected lemma add_comm (v₁ v₂ : bv n) : v₁ + v₂ = v₂ + v₁ := by push_cast [← to_nat_inj, add_comm] protected lemma add_zero (v : bv n) : v + 0 = v := by push_cast [← to_nat_inj]; simp protected lemma zero_add (v : bv n) : 0 + v = v := bv.add_comm v 0 ▸ bv.add_zero v protected lemma add_assoc (v₁ v₂ v₃ : bv n) : v₁ + v₂ + v₃ = v₁ + (v₂ + v₃) := by push_cast [← to_nat_inj]; simp [add_assoc] protected lemma add_left_neg (v : bv n) : -v + v = 0 := begin push_cast [← to_nat_inj], cases eq.decidable (v : ℕ) 0 with h h; simp [h], rw nat.sub_add_cancel; simp, apply le_of_lt (to_nat_lt _) end protected lemma mul_comm (v₁ v₂ : bv n) : v₁ * v₂ = v₂ * v₁ := by push_cast [← to_nat_inj, mul_comm] protected lemma mul_one (v : bv n) : v * 1 = v := by cases n; push_cast [← to_nat_inj]; simp protected lemma one_mul (v : bv n) : 1 * v = v := bv.mul_comm v 1 ▸ bv.mul_one v protected lemma mul_assoc (v₁ v₂ v₃ : bv n) : v₁ * v₂ * v₃ = v₁ * (v₂ * v₃) := begin push_cast [← to_nat_inj], conv_lhs { rw [mul_mod, mod_mod, ← mul_mod] }, conv_rhs { rw [mul_mod, mod_mod, ← mul_mod] }, rw mul_assoc end protected lemma distrib_left (v₁ v₂ v₃ : bv n) : v₁ * (v₂ + v₃) = v₁ * v₂ + v₁ * v₃ := begin push_cast [← to_nat_inj], conv_lhs { rw [mul_mod, mod_mod, ← mul_mod] }, simp [nat.left_distrib] end protected lemma distrib_right (v₁ v₂ v₃ : bv n) : (v₁ + v₂) * v₃ = v₁ * v₃ + v₂ * v₃ := begin rw [bv.mul_comm, bv.distrib_left], simp [bv.mul_comm] end instance : comm_ring (bv n) := { add := bv.add, add_comm := bv.add_comm, add_assoc := bv.add_assoc, zero := 0, zero_add := bv.zero_add, add_zero := bv.add_zero, neg := bv.neg, add_left_neg := bv.add_left_neg, mul := bv.mul, mul_comm := bv.mul_comm, mul_assoc := bv.mul_assoc, one := 1, one_mul := bv.one_mul, mul_one := bv.mul_one, left_distrib := bv.distrib_left, right_distrib := bv.distrib_right } end ring section bitwise variable {n : ℕ} @[norm_cast] lemma shl_to_nat (v₁ v₂ : bv n) : (v₁.shl v₂ : ℕ) = (v₁ : ℕ) * (2^(v₂ : ℕ)) % 2^n := by push_cast [shl] lemma shl_above (v₁ v₂ : bv n) (h : n ≤ v₂.to_nat) : v₁.shl v₂ = 0 := begin push_cast [← to_nat_inj], apply mod_eq_zero_of_dvd, apply dvd_trans _ (dvd_mul_left _ _), apply pow_dvd_pow _ h end @[norm_cast] lemma lshr_to_nat (v₁ v₂ : bv n) : (v₁.lshr v₂ : ℕ) = (v₁ : ℕ) / 2^(v₂ : ℕ) := begin push_cast [lshr], apply mod_eq_of_lt, apply lt_of_le_of_lt (nat.div_le_self _ _) (to_nat_lt _) end lemma lshr_above (v₁ v₂ : bv n) (h : n ≤ v₂.to_nat) : v₁.lshr v₂ = 0 := begin push_cast [← to_nat_inj], apply div_eq_of_lt, apply lt_of_lt_of_le (to_nat_lt _), apply pow_le_pow_of_le_right two_pos h end end bitwise section order variable {n : ℕ} @[norm_cast] lemma ult_to_nat (v₁ v₂ : bv n) : ((v₁ : ℕ) < (v₂ : ℕ)) = (v₁ < v₂) := rfl @[norm_cast] lemma ule_to_nat (v₁ v₂ : bv n) : ((v₁ : ℕ) ≤ (v₂ : ℕ)) ↔ (v₁ ≤ v₂) := begin rw [le_iff_eq_or_lt, or_comm], norm_cast end protected lemma ule_refl (v : bv n) : v ≤ v := by simp [← ule_to_nat] protected lemma ule_trans (v₁ v₂ v₃ : bv n) : v₁ ≤ v₂ → v₂ ≤ v₃ → v₁ ≤ v₃ := begin simp [← ule_to_nat], apply le_trans end protected lemma ule_antisymm (v₁ v₂ : bv n) : v₁ ≤ v₂ → v₂ ≤ v₁ → v₁ = v₂ := begin simp [← ule_to_nat, ← to_nat_inj], apply le_antisymm end protected lemma ule_total (v₁ v₂ : bv n) : v₁ ≤ v₂ ∨ v₂ ≤ v₁ := by simp [← ule_to_nat, le_total] protected lemma ult_iff_ule_not_ule (v₁ v₂ : bv n) : v₁ < v₂ ↔ v₁ ≤ v₂ ∧ ¬ v₂ ≤ v₁ := begin rw ← ult_to_nat, repeat { rw ← ule_to_nat }, apply lt_iff_le_not_le end @[priority 101] instance unsigned : linear_order (bv n) := { le := bv.ule, decidable_le := bv.decidable_ule, le_refl := bv.ule_refl, le_trans := bv.ule_trans, le_antisymm := bv.ule_antisymm, le_total := bv.ule_total, lt := bv.ult, decidable_lt := bv.decidable_ult, lt_iff_le_not_le := bv.ult_iff_ule_not_ule } lemma slt_to_int (v₁ v₂ : bv (n + 1)) : v₁.to_int < v₂.to_int = v₁.slt v₂ := begin simp [bv.slt, to_int, ← msb_eq_ff_iff], have h₁ := to_nat_lt v₁, have h₂ := to_nat_lt v₂, cases v₁.msb; cases v₂.msb; simp [← ult_to_nat]; linarith end protected lemma sle_iff_eq_or_slt (v₁ v₂ : bv (n + 1)) : v₁.sle v₂ = (v₁ = v₂ ∨ v₁.slt v₂) := begin simp [bv.sle, bv.slt, le_iff_eq_or_lt], cases eq.decidable v₁ v₂ with h h; simp [h] end lemma sle_to_int (v₁ v₂ : bv (n + 1)) : (v₁.to_int ≤ v₂.to_int) = v₁.sle v₂ := by rw [le_iff_eq_or_lt, to_int_inj, slt_to_int, bv.sle_iff_eq_or_slt] protected lemma sle_refl (v : bv (n + 1)) : v.sle v := by simp [bv.sle, bv.ule_refl] protected lemma sle_trans (v₁ v₂ v₃ : bv (n + 1)) : v₁.sle v₂ → v₂.sle v₃ → v₁.sle v₃ := begin simp [← sle_to_int], apply le_trans end protected lemma sle_antisymm (v₁ v₂ : bv (n + 1)) : v₁.sle v₂ → v₂.sle v₁ → v₁ = v₂ := begin simp [bv.sle], finish end protected lemma sle_total (v₁ v₂ : bv (n + 1)) : v₁.sle v₂ ∨ v₂.sle v₁ := by simp [← sle_to_int, le_total] protected lemma slt_iff_sle_not_sle (v₁ v₂ : bv (n + 1)) : v₁.slt v₂ ↔ v₁.sle v₂ ∧ ¬ v₂.sle v₁ := begin rw ← slt_to_int, repeat { rw ← sle_to_int }, apply lt_iff_le_not_le end @[priority 100] instance signed : linear_order (bv (n + 1)) := { le := bv.sle, decidable_le := bv.decidable_sle, le_refl := bv.sle_refl, le_trans := bv.sle_trans, le_antisymm := bv.sle_antisymm, le_total := bv.sle_total, lt := bv.slt, decidable_lt := bv.decidable_slt, lt_iff_le_not_le := bv.slt_iff_sle_not_sle } end order end bv
3de47b6407af9e2b0772da69ea99c90b1567ac14
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/completion.lean
0715c852b22ce1a473265d7df56e9702efbc1e68
[ "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
3,722
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed.group.completion import analysis.normed_space.operator_norm import topology.algebra.uniform_ring /-! # Normed space structure on the completion of a normed space If `E` is a normed space over `𝕜`, then so is `uniform_space.completion E`. In this file we provide necessary instances and define `uniform_space.completion.to_complₗᵢ` - coercion `E → uniform_space.completion E` as a bundled linear isometry. We also show that if `A` is a normed algebra over `𝕜`, then so is `uniform_space.completion A`. TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`. -/ noncomputable theory namespace uniform_space namespace completion variables (𝕜 E : Type*) [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] @[priority 100] instance normed_space.to_has_uniform_continuous_const_smul : has_uniform_continuous_const_smul 𝕜 E := ⟨λ c, (lipschitz_with_smul c).uniform_continuous⟩ instance : normed_space 𝕜 (completion E) := { smul := (•), norm_smul_le := λ c x, induction_on x (is_closed_le (continuous_const_smul _).norm (continuous_const.mul continuous_norm)) $ λ y, by simp only [← coe_smul, norm_coe, norm_smul], .. completion.module } variables {𝕜 E} /-- Embedding of a normed space to its completion as a linear isometry. -/ def to_complₗᵢ : E →ₗᵢ[𝕜] completion E := { to_fun := coe, map_smul' := coe_smul, norm_map' := norm_coe, .. to_compl } @[simp] lemma coe_to_complₗᵢ : ⇑(to_complₗᵢ : E →ₗᵢ[𝕜] completion E) = coe := rfl /-- Embedding of a normed space to its completion as a continuous linear map. -/ def to_complL : E →L[𝕜] completion E := to_complₗᵢ.to_continuous_linear_map @[simp] lemma coe_to_complL : ⇑(to_complL : E →L[𝕜] completion E) = coe := rfl @[simp] lemma norm_to_complL {𝕜 E : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [nontrivial E] : ∥(to_complL : E →L[𝕜] completion E)∥ = 1 := (to_complₗᵢ : E →ₗᵢ[𝕜] completion E).norm_to_continuous_linear_map section algebra variables (𝕜) (A : Type*) instance [semi_normed_ring A] : normed_ring (completion A) := { dist_eq := λ x y, begin apply completion.induction_on₂ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, completion.dist_eq, dist_eq_norm] } end, norm_mul := λ x y, begin apply completion.induction_on₂ x y; clear x y, { exact is_closed_le (continuous.comp (continuous_norm) continuous_mul) (continuous.comp real.continuous_mul (continuous.prod_map continuous_norm continuous_norm)) }, { intros x y, simp only [← coe_mul, norm_coe], exact norm_mul_le x y, } end, ..completion.ring, ..completion.metric_space } instance [semi_normed_comm_ring A] [normed_algebra 𝕜 A] [has_uniform_continuous_const_smul 𝕜 A] : normed_algebra 𝕜 (completion A) := { norm_smul_le := λ r x, begin apply completion.induction_on x; clear x, { exact is_closed_le (continuous.comp (continuous_norm) (continuous_const_smul r)) (continuous.comp (continuous_mul_left _) continuous_norm), }, { intros x, simp only [← coe_smul, norm_coe], exact normed_space.norm_smul_le r x } end, ..completion.algebra A 𝕜} end algebra end completion end uniform_space
3e249f073e0c6aba70eec6e348d9b267d8bc7655
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/category_theory/monad/products.lean
b4b09e68a870f1e3d083c60a8a4d9185b3ac1e99
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,973
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.over import category_theory.limits.preserves.basic import category_theory.limits.creates import category_theory.limits.shapes.binary_products import category_theory.monad.algebra /-! # Algebras for the coproduct monad The functor `Y ↦ X ⨿ Y` forms a monad, whose category of monads is equivalent to the under category of `X`. Similarly, `Y ↦ X ⨯ Y` forms a comonad, whose category of comonads is equivalent to the over category of `X`. ## TODO Show that `over.forget X : over X ⥤ C` is a comonadic left adjoint and `under.forget : under X ⥤ C` is a monadic right adjoint. -/ noncomputable theory universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category limits variables {C : Type u} [category.{v} C] (X : C) section open comonad variable [has_binary_products C] /-- `X ⨯ -` has a comonad structure. This is sometimes called the writer comonad. -/ @[simps] instance : comonad (prod.functor.obj X) := { ε := { app := λ Y, limits.prod.snd }, δ := { app := λ Y, prod.lift limits.prod.fst (𝟙 _) } } /-- The forward direction of the equivalence from coalgebras for the product comonad to the over category. -/ @[simps] def coalgebra_to_over : coalgebra (prod.functor.obj X) ⥤ over X := { obj := λ A, over.mk (A.a ≫ limits.prod.fst), map := λ A₁ A₂ f, over.hom_mk f.f (by simp [←f.h_assoc]) } /-- The backward direction of the equivalence from coalgebras for the product comonad to the over category. -/ @[simps] def over_to_coalgebra : over X ⥤ coalgebra (prod.functor.obj X) := { obj := λ f, { A := f.left, a := prod.lift f.hom (𝟙 _) }, map := λ f₁ f₂ g, { f := g.left } } /-- The equivalence from coalgebras for the product comonad to the over category. -/ def coalgebra_equiv_over : coalgebra (prod.functor.obj X) ≌ over X := { functor := coalgebra_to_over X, inverse := over_to_coalgebra X, unit_iso := nat_iso.of_components (λ A, coalgebra.iso_mk (iso.refl _) (prod.hom_ext (by { dsimp, simp }) (by { dsimp, simpa using A.counit }))) (λ A₁ A₂ f, by { ext, simp }), counit_iso := nat_iso.of_components (λ f, over.iso_mk (iso.refl _)) (λ f g k, by tidy) }. end section open monad variable [has_binary_coproducts C] /-- `X ⨿ -` has a monad structure. This is sometimes called the either monad. -/ @[simps] instance : monad (coprod.functor.obj X) := { η := { app := λ Y, coprod.inr }, μ := { app := λ Y, coprod.desc coprod.inl (𝟙 _) } } /-- The forward direction of the equivalence from algebras for the coproduct monad to the under category. -/ @[simps] def algebra_to_under : monad.algebra (coprod.functor.obj X) ⥤ under X := { obj := λ A, under.mk (coprod.inl ≫ A.a), map := λ A₁ A₂ f, under.hom_mk f.f (by { dsimp, simp [←f.h] }) } /-- The backward direction of the equivalence from algebras for the coproduct monad to the under category. -/ @[simps] def under_to_algebra : under X ⥤ monad.algebra (coprod.functor.obj X) := { obj := λ f, { A := f.right, a := coprod.desc f.hom (𝟙 _) }, map := λ f₁ f₂ g, { f := g.right } } /-- The equivalence from algebras for the coproduct monad to the under category. -/ @[simps] def algebra_equiv_under : monad.algebra (coprod.functor.obj X) ≌ under X := { functor := algebra_to_under X, inverse := under_to_algebra X, unit_iso := nat_iso.of_components (λ A, monad.algebra.iso_mk (iso.refl _) (coprod.hom_ext (by tidy) (by { dsimp, simpa using A.unit.symm }))) (λ A₁ A₂ f, by { ext, simp }), counit_iso := nat_iso.of_components (λ f, under.iso_mk (iso.refl _) (by tidy)) (λ f g k, by tidy) }. end end category_theory
75adff6cc7cd501c63641c70530d4a5cb9ad517e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/combinatorics/simple_graph/adj_matrix.lean
b2538ca69e647b5398c4bf19fac879a8454deb84
[ "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
7,994
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Lu-Ming Zhang -/ import combinatorics.simple_graph.basic import data.rel import linear_algebra.matrix.trace import linear_algebra.matrix.symmetric /-! # Adjacency Matrices This module defines the adjacency matrix of a graph, and provides theorems connecting graph properties to computational properties of the matrix. ## Main definitions * `matrix.is_adj_matrix`: `A : matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. * `matrix.is_adj_matrix.to_graph`: for `A : matrix V V α` and `h : A.is_adj_matrix`, `h.to_graph` is the simple graph induced by `A`. * `matrix.compl`: for `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A`. * `simple_graph.adj_matrix`: the adjacency matrix of a `simple_graph`. -/ open_locale big_operators matrix open finset matrix simple_graph variables {V α β : Type*} namespace matrix /-- `A : matrix V V α` is qualified as an "adjacency matrix" if (1) every entry of `A` is `0` or `1`, (2) `A` is symmetric, (3) every diagonal entry of `A` is `0`. -/ structure is_adj_matrix [has_zero α] [has_one α] (A : matrix V V α) : Prop := (zero_or_one : ∀ i j, (A i j) = 0 ∨ (A i j) = 1 . obviously) (symm : A.is_symm . obviously) (apply_diag : ∀ i, A i i = 0 . obviously) namespace is_adj_matrix variables {A : matrix V V α} @[simp] lemma apply_diag_ne [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i : V) : ¬ A i i = 1 := by simp [h.apply_diag i] @[simp] lemma apply_ne_one_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) : ¬ A i j = 1 ↔ A i j = 0 := by { obtain (h|h) := h.zero_or_one i j; simp [h] } @[simp] lemma apply_ne_zero_iff [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) (i j : V) : ¬ A i j = 0 ↔ A i j = 1 := by rw [←apply_ne_one_iff h, not_not] /-- For `A : matrix V V α` and `h : is_adj_matrix A`, `h.to_graph` is the simple graph whose adjacency matrix is `A`. -/ @[simps] def to_graph [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) : simple_graph V := { adj := λ i j, A i j = 1, symm := λ i j hij, by rwa h.symm.apply i j, loopless := λ i, by simp [h] } instance [mul_zero_one_class α] [nontrivial α] [decidable_eq α] (h : is_adj_matrix A) : decidable_rel h.to_graph.adj := by { simp only [to_graph], apply_instance } end is_adj_matrix /-- For `A : matrix V V α`, `A.compl` is supposed to be the adjacency matrix of the complement graph of the graph induced by `A.adj_matrix`. -/ def compl [has_zero α] [has_one α] [decidable_eq α] [decidable_eq V] (A : matrix V V α) : matrix V V α := λ i j, ite (i = j) 0 (ite (A i j = 0) 1 0) section compl variables [decidable_eq α] [decidable_eq V] (A : matrix V V α) @[simp] lemma compl_apply_diag [has_zero α] [has_one α] (i : V) : A.compl i i = 0 := by simp [compl] @[simp] lemma compl_apply [has_zero α] [has_one α] (i j : V) : A.compl i j = 0 ∨ A.compl i j = 1 := by { unfold compl, split_ifs; simp, } @[simp] lemma is_symm_compl [has_zero α] [has_one α] (h : A.is_symm) : A.compl.is_symm := by { ext, simp [compl, h.apply, eq_comm], } @[simp] lemma is_adj_matrix_compl [has_zero α] [has_one α] (h : A.is_symm) : is_adj_matrix A.compl := { symm := by simp [h] } namespace is_adj_matrix variable {A} @[simp] lemma compl [has_zero α] [has_one α] (h : is_adj_matrix A) : is_adj_matrix A.compl := is_adj_matrix_compl A h.symm lemma to_graph_compl_eq [mul_zero_one_class α] [nontrivial α] (h : is_adj_matrix A) : h.compl.to_graph = (h.to_graph)ᶜ := begin ext v w, cases h.zero_or_one v w with h h; by_cases hvw : v = w; simp [matrix.compl, h, hvw] end end is_adj_matrix end compl end matrix open matrix namespace simple_graph variables (G : simple_graph V) [decidable_rel G.adj] variables (α) /-- `adj_matrix G α` is the matrix `A` such that `A i j = (1 : α)` if `i` and `j` are adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/ def adj_matrix [has_zero α] [has_one α] : matrix V V α | i j := if (G.adj i j) then 1 else 0 variable {α} @[simp] lemma adj_matrix_apply (v w : V) [has_zero α] [has_one α] : G.adj_matrix α v w = if (G.adj v w) then 1 else 0 := rfl @[simp] theorem transpose_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α)ᵀ = G.adj_matrix α := by { ext, simp [adj_comm] } @[simp] lemma is_symm_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α).is_symm := transpose_adj_matrix G variable (α) /-- The adjacency matrix of `G` is an adjacency matrix. -/ @[simp] lemma is_adj_matrix_adj_matrix [has_zero α] [has_one α] : (G.adj_matrix α).is_adj_matrix := { zero_or_one := λ i j, by by_cases G.adj i j; simp [h] } /-- The graph induced by the adjacency matrix of `G` is `G` itself. -/ lemma to_graph_adj_matrix_eq [mul_zero_one_class α] [nontrivial α] : (G.is_adj_matrix_adj_matrix α).to_graph = G := begin ext, simp only [is_adj_matrix.to_graph_adj, adj_matrix_apply, ite_eq_left_iff, zero_ne_one], apply not_not, end variables {α} [fintype V] @[simp] lemma adj_matrix_dot_product [non_assoc_semiring α] (v : V) (vec : V → α) : dot_product (G.adj_matrix α v) vec = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter] @[simp] lemma dot_product_adj_matrix [non_assoc_semiring α] (v : V) (vec : V → α) : dot_product vec (G.adj_matrix α v) = ∑ u in G.neighbor_finset v, vec u := by simp [neighbor_finset_eq_filter, dot_product, sum_filter, finset.sum_apply] @[simp] lemma adj_matrix_mul_vec_apply [non_assoc_semiring α] (v : V) (vec : V → α) : ((G.adj_matrix α).mul_vec vec) v = ∑ u in G.neighbor_finset v, vec u := by rw [mul_vec, adj_matrix_dot_product] @[simp] lemma adj_matrix_vec_mul_apply [non_assoc_semiring α] (v : V) (vec : V → α) : ((G.adj_matrix α).vec_mul vec) v = ∑ u in G.neighbor_finset v, vec u := begin rw [← dot_product_adj_matrix, vec_mul], refine congr rfl _, ext, rw [← transpose_apply (adj_matrix α G) x v, transpose_adj_matrix], end @[simp] lemma adj_matrix_mul_apply [non_assoc_semiring α] (M : matrix V V α) (v w : V) : (G.adj_matrix α ⬝ M) v w = ∑ u in G.neighbor_finset v, M u w := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter] @[simp] lemma mul_adj_matrix_apply [non_assoc_semiring α] (M : matrix V V α) (v w : V) : (M ⬝ G.adj_matrix α) v w = ∑ u in G.neighbor_finset w, M v u := by simp [mul_apply, neighbor_finset_eq_filter, sum_filter, adj_comm] variable (α) theorem trace_adj_matrix [non_assoc_semiring α] [semiring β] [module β α]: matrix.trace _ β _ (G.adj_matrix α) = 0 := by simp variable {α} theorem adj_matrix_mul_self_apply_self [non_assoc_semiring α] (i : V) : ((G.adj_matrix α) ⬝ (G.adj_matrix α)) i i = degree G i := by simp [degree] variable {G} @[simp] lemma adj_matrix_mul_vec_const_apply [semiring α] {a : α} {v : V} : (G.adj_matrix α).mul_vec (function.const _ a) v = G.degree v * a := by simp [degree] lemma adj_matrix_mul_vec_const_apply_of_regular [semiring α] {d : ℕ} {a : α} (hd : G.is_regular_of_degree d) {v : V} : (G.adj_matrix α).mul_vec (function.const _ a) v = (d * a) := by simp [hd v] end simple_graph namespace matrix.is_adj_matrix variables [mul_zero_one_class α] [nontrivial α] variables {A : matrix V V α} (h : is_adj_matrix A) /-- If `A` is qualified as an adjacency matrix, then the adjacency matrix of the graph induced by `A` is itself. -/ lemma adj_matrix_to_graph_eq [decidable_eq α] : h.to_graph.adj_matrix α = A := begin ext i j, obtain (h'|h') := h.zero_or_one i j; simp [h'], end end matrix.is_adj_matrix
1996afbb7432834b2f8e97d280d0c341dd6419ba
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/projection.lean
9476c4d4b9babe462a3ddc90f376dbede43a8d6a
[ "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
16,925
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import linear_algebra.quotient import linear_algebra.prod /-! # Projection to a subspace In this file we define * `linear_proj_of_is_compl (p q : submodule R E) (h : is_compl p q)`: the projection of a module `E` to a submodule `p` along its complement `q`; it is the unique linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. * `is_compl_equiv_proj p`: equivalence between submodules `q` such that `is_compl p q` and projections `f : E → p`, `∀ x ∈ p, f x = x`. We also provide some lemmas justifying correctness of our definitions. ## Tags projection, complement subspace -/ section ring variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {G : Type*} [add_comm_group G] [module R G] (p q : submodule R E) variables {S : Type*} [semiring S] {M : Type*} [add_comm_monoid M] [module S M] (m : submodule S M) noncomputable theory namespace linear_map variable {p} open submodule lemma ker_id_sub_eq_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) : ker (id - p.subtype.comp f) = p := begin ext x, simp only [comp_apply, mem_ker, subtype_apply, sub_apply, id_apply, sub_eq_zero], exact ⟨λ h, h.symm ▸ submodule.coe_mem _, λ hx, by erw [hf ⟨x, hx⟩, subtype.coe_mk]⟩ end lemma range_eq_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) : range f = ⊤ := range_eq_top.2 $ λ x, ⟨x, hf x⟩ lemma is_compl_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) : is_compl p f.ker := begin split, { rintros x ⟨hpx, hfx⟩, erw [set_like.mem_coe, mem_ker, hf ⟨x, hpx⟩, mk_eq_zero] at hfx, simp only [hfx, set_like.mem_coe, zero_mem] }, { intros x hx, rw [mem_sup'], refine ⟨f x, ⟨x - f x, _⟩, add_sub_cancel'_right _ _⟩, rw [mem_ker, linear_map.map_sub, hf, sub_self] } end end linear_map namespace submodule open linear_map /-- If `q` is a complement of `p`, then `M/p ≃ q`. -/ def quotient_equiv_of_is_compl (h : is_compl p q) : (E ⧸ p) ≃ₗ[R] q := linear_equiv.symm $ linear_equiv.of_bijective (p.mkq.comp q.subtype) (by simp only [← ker_eq_bot, ker_comp, ker_mkq, disjoint_iff_comap_eq_bot.1 h.symm.disjoint]) (by simp only [← range_eq_top, range_comp, range_subtype, map_mkq_eq_top, h.sup_eq_top]) @[simp] lemma quotient_equiv_of_is_compl_symm_apply (h : is_compl p q) (x : q) : (quotient_equiv_of_is_compl p q h).symm x = quotient.mk x := rfl @[simp] lemma quotient_equiv_of_is_compl_apply_mk_coe (h : is_compl p q) (x : q) : quotient_equiv_of_is_compl p q h (quotient.mk x) = x := (quotient_equiv_of_is_compl p q h).apply_symm_apply x @[simp] lemma mk_quotient_equiv_of_is_compl_apply (h : is_compl p q) (x : E ⧸ p) : (quotient.mk (quotient_equiv_of_is_compl p q h x) : E ⧸ p) = x := (quotient_equiv_of_is_compl p q h).symm_apply_apply x /-- If `q` is a complement of `p`, then `p × q` is isomorphic to `E`. It is the unique linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. -/ def prod_equiv_of_is_compl (h : is_compl p q) : (p × q) ≃ₗ[R] E := begin apply linear_equiv.of_bijective (p.subtype.coprod q.subtype), { simp only [←ker_eq_bot, ker_eq_bot', prod.forall, subtype_apply, prod.mk_eq_zero, coprod_apply], -- TODO: if I add `submodule.forall`, it unfolds the outer `∀` but not the inner one. rintros ⟨x, hx⟩ ⟨y, hy⟩, simp only [coe_mk, mk_eq_zero, ← eq_neg_iff_add_eq_zero], rintro rfl, rw [neg_mem_iff] at hx, simp [disjoint_def.1 h.disjoint y hx hy] }, { rw [← range_eq_top, ← sup_eq_range, h.sup_eq_top] } end @[simp] lemma coe_prod_equiv_of_is_compl (h : is_compl p q) : (prod_equiv_of_is_compl p q h : (p × q) →ₗ[R] E) = p.subtype.coprod q.subtype := rfl @[simp] lemma coe_prod_equiv_of_is_compl' (h : is_compl p q) (x : p × q) : prod_equiv_of_is_compl p q h x = x.1 + x.2 := rfl @[simp] lemma prod_equiv_of_is_compl_symm_apply_left (h : is_compl p q) (x : p) : (prod_equiv_of_is_compl p q h).symm x = (x, 0) := (prod_equiv_of_is_compl p q h).symm_apply_eq.2 $ by simp @[simp] lemma prod_equiv_of_is_compl_symm_apply_right (h : is_compl p q) (x : q) : (prod_equiv_of_is_compl p q h).symm x = (0, x) := (prod_equiv_of_is_compl p q h).symm_apply_eq.2 $ by simp @[simp] lemma prod_equiv_of_is_compl_symm_apply_fst_eq_zero (h : is_compl p q) {x : E} : ((prod_equiv_of_is_compl p q h).symm x).1 = 0 ↔ x ∈ q := begin conv_rhs { rw [← (prod_equiv_of_is_compl p q h).apply_symm_apply x] }, rw [coe_prod_equiv_of_is_compl', submodule.add_mem_iff_left _ (submodule.coe_mem _), mem_right_iff_eq_zero_of_disjoint h.disjoint] end @[simp] lemma prod_equiv_of_is_compl_symm_apply_snd_eq_zero (h : is_compl p q) {x : E} : ((prod_equiv_of_is_compl p q h).symm x).2 = 0 ↔ x ∈ p := begin conv_rhs { rw [← (prod_equiv_of_is_compl p q h).apply_symm_apply x] }, rw [coe_prod_equiv_of_is_compl', submodule.add_mem_iff_right _ (submodule.coe_mem _), mem_left_iff_eq_zero_of_disjoint h.disjoint] end @[simp] lemma prod_comm_trans_prod_equiv_of_is_compl (h : is_compl p q) : linear_equiv.prod_comm R q p ≪≫ₗ prod_equiv_of_is_compl p q h = prod_equiv_of_is_compl q p h.symm := linear_equiv.ext $ λ _, add_comm _ _ /-- Projection to a submodule along its complement. -/ def linear_proj_of_is_compl (h : is_compl p q) : E →ₗ[R] p := (linear_map.fst R p q) ∘ₗ ↑(prod_equiv_of_is_compl p q h).symm variables {p q} @[simp] lemma linear_proj_of_is_compl_apply_left (h : is_compl p q) (x : p) : linear_proj_of_is_compl p q h x = x := by simp [linear_proj_of_is_compl] @[simp] lemma linear_proj_of_is_compl_range (h : is_compl p q) : (linear_proj_of_is_compl p q h).range = ⊤ := range_eq_of_proj (linear_proj_of_is_compl_apply_left h) @[simp] lemma linear_proj_of_is_compl_apply_eq_zero_iff (h : is_compl p q) {x : E} : linear_proj_of_is_compl p q h x = 0 ↔ x ∈ q:= by simp [linear_proj_of_is_compl] lemma linear_proj_of_is_compl_apply_right' (h : is_compl p q) (x : E) (hx : x ∈ q) : linear_proj_of_is_compl p q h x = 0 := (linear_proj_of_is_compl_apply_eq_zero_iff h).2 hx @[simp] lemma linear_proj_of_is_compl_apply_right (h : is_compl p q) (x : q) : linear_proj_of_is_compl p q h x = 0 := linear_proj_of_is_compl_apply_right' h x x.2 @[simp] lemma linear_proj_of_is_compl_ker (h : is_compl p q) : (linear_proj_of_is_compl p q h).ker = q := ext $ λ x, mem_ker.trans (linear_proj_of_is_compl_apply_eq_zero_iff h) lemma linear_proj_of_is_compl_comp_subtype (h : is_compl p q) : (linear_proj_of_is_compl p q h).comp p.subtype = id := linear_map.ext $ linear_proj_of_is_compl_apply_left h lemma linear_proj_of_is_compl_idempotent (h : is_compl p q) (x : E) : linear_proj_of_is_compl p q h (linear_proj_of_is_compl p q h x) = linear_proj_of_is_compl p q h x := linear_proj_of_is_compl_apply_left h _ lemma exists_unique_add_of_is_compl_prod (hc : is_compl p q) (x : E) : ∃! (u : p × q), (u.fst : E) + u.snd = x := (prod_equiv_of_is_compl _ _ hc).to_equiv.bijective.exists_unique _ lemma exists_unique_add_of_is_compl (hc : is_compl p q) (x : E) : ∃ (u : p) (v : q), ((u : E) + v = x ∧ ∀ (r : p) (s : q), (r : E) + s = x → r = u ∧ s = v) := let ⟨u, hu₁, hu₂⟩ := exists_unique_add_of_is_compl_prod hc x in ⟨u.1, u.2, hu₁, λ r s hrs, prod.eq_iff_fst_eq_snd_eq.1 (hu₂ ⟨r, s⟩ hrs)⟩ lemma linear_proj_add_linear_proj_of_is_compl_eq_self (hpq : is_compl p q) (x : E) : (p.linear_proj_of_is_compl q hpq x + q.linear_proj_of_is_compl p hpq.symm x : E) = x := begin dunfold linear_proj_of_is_compl, rw ←prod_comm_trans_prod_equiv_of_is_compl _ _ hpq, exact (prod_equiv_of_is_compl _ _ hpq).apply_symm_apply x, end end submodule namespace linear_map open submodule /-- Given linear maps `φ` and `ψ` from complement submodules, `of_is_compl` is the induced linear map over the entire module. -/ def of_is_compl {p q : submodule R E} (h : is_compl p q) (φ : p →ₗ[R] F) (ψ : q →ₗ[R] F) : E →ₗ[R] F := (linear_map.coprod φ ψ) ∘ₗ ↑(submodule.prod_equiv_of_is_compl _ _ h).symm variables {p q} @[simp] lemma of_is_compl_left_apply (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (u : p) : of_is_compl h φ ψ (u : E) = φ u := by simp [of_is_compl] @[simp] lemma of_is_compl_right_apply (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (v : q) : of_is_compl h φ ψ (v : E) = ψ v := by simp [of_is_compl] lemma of_is_compl_eq (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} {χ : E →ₗ[R] F} (hφ : ∀ u, φ u = χ u) (hψ : ∀ u, ψ u = χ u) : of_is_compl h φ ψ = χ := begin ext x, obtain ⟨_, _, rfl, _⟩ := exists_unique_add_of_is_compl h x, simp [of_is_compl, hφ, hψ] end lemma of_is_compl_eq' (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} {χ : E →ₗ[R] F} (hφ : φ = χ.comp p.subtype) (hψ : ψ = χ.comp q.subtype) : of_is_compl h φ ψ = χ := of_is_compl_eq h (λ _, hφ.symm ▸ rfl) (λ _, hψ.symm ▸ rfl) @[simp] lemma of_is_compl_zero (h : is_compl p q) : (of_is_compl h 0 0 : E →ₗ[R] F) = 0 := of_is_compl_eq _ (λ _, rfl) (λ _, rfl) @[simp] lemma of_is_compl_add (h : is_compl p q) {φ₁ φ₂ : p →ₗ[R] F} {ψ₁ ψ₂ : q →ₗ[R] F} : of_is_compl h (φ₁ + φ₂) (ψ₁ + ψ₂) = of_is_compl h φ₁ ψ₁ + of_is_compl h φ₂ ψ₂ := of_is_compl_eq _ (by simp) (by simp) @[simp] lemma of_is_compl_smul {R : Type*} [comm_ring R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] {p q : submodule R E} (h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (c : R) : of_is_compl h (c • φ) (c • ψ) = c • of_is_compl h φ ψ := of_is_compl_eq _ (by simp) (by simp) section variables {R₁ : Type*} [comm_ring R₁] [module R₁ E] [module R₁ F] /-- The linear map from `(p →ₗ[R₁] F) × (q →ₗ[R₁] F)` to `E →ₗ[R₁] F`. -/ def of_is_compl_prod {p q : submodule R₁ E} (h : is_compl p q) : ((p →ₗ[R₁] F) × (q →ₗ[R₁] F)) →ₗ[R₁] (E →ₗ[R₁] F) := { to_fun := λ φ, of_is_compl h φ.1 φ.2, map_add' := by { intros φ ψ, rw [prod.snd_add, prod.fst_add, of_is_compl_add] }, map_smul' := by { intros c φ, simp [prod.smul_snd, prod.smul_fst, of_is_compl_smul] } } @[simp] lemma of_is_compl_prod_apply {p q : submodule R₁ E} (h : is_compl p q) (φ : (p →ₗ[R₁] F) × (q →ₗ[R₁] F)) : of_is_compl_prod h φ = of_is_compl h φ.1 φ.2 := rfl /-- The natural linear equivalence between `(p →ₗ[R₁] F) × (q →ₗ[R₁] F)` and `E →ₗ[R₁] F`. -/ def of_is_compl_prod_equiv {p q : submodule R₁ E} (h : is_compl p q) : ((p →ₗ[R₁] F) × (q →ₗ[R₁] F)) ≃ₗ[R₁] (E →ₗ[R₁] F) := { inv_fun := λ φ, ⟨φ.dom_restrict p, φ.dom_restrict q⟩, left_inv := begin intros φ, ext, { exact of_is_compl_left_apply h x }, { exact of_is_compl_right_apply h x } end, right_inv := begin intro φ, ext, obtain ⟨a, b, hab, _⟩ := exists_unique_add_of_is_compl h x, rw [← hab], simp, end, .. of_is_compl_prod h } end @[simp] lemma linear_proj_of_is_compl_of_proj (f : E →ₗ[R] p) (hf : ∀ x : p, f x = x) : p.linear_proj_of_is_compl f.ker (is_compl_of_proj hf) = f := begin ext x, have : x ∈ p ⊔ f.ker, { simp only [(is_compl_of_proj hf).sup_eq_top, mem_top] }, rcases mem_sup'.1 this with ⟨x, y, rfl⟩, simp [hf] end /-- If `f : E →ₗ[R] F` and `g : E →ₗ[R] G` are two surjective linear maps and their kernels are complement of each other, then `x ↦ (f x, g x)` defines a linear equivalence `E ≃ₗ[R] F × G`. -/ def equiv_prod_of_surjective_of_is_compl (f : E →ₗ[R] F) (g : E →ₗ[R] G) (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : E ≃ₗ[R] F × G := linear_equiv.of_bijective (f.prod g) (by simp [← ker_eq_bot, hfg.inf_eq_bot]) (by simp [← range_eq_top, range_prod_eq hfg.sup_eq_top, *]) @[simp] lemma coe_equiv_prod_of_surjective_of_is_compl {f : E →ₗ[R] F} {g : E →ₗ[R] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) : (equiv_prod_of_surjective_of_is_compl f g hf hg hfg : E →ₗ[R] F × G) = f.prod g := rfl @[simp] lemma equiv_prod_of_surjective_of_is_compl_apply {f : E →ₗ[R] F} {g : E →ₗ[R] G} (hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) (x : E): equiv_prod_of_surjective_of_is_compl f g hf hg hfg x = (f x, g x) := rfl end linear_map namespace submodule open linear_map /-- Equivalence between submodules `q` such that `is_compl p q` and linear maps `f : E →ₗ[R] p` such that `∀ x : p, f x = x`. -/ def is_compl_equiv_proj : {q // is_compl p q} ≃ {f : E →ₗ[R] p // ∀ x : p, f x = x} := { to_fun := λ q, ⟨linear_proj_of_is_compl p q q.2, linear_proj_of_is_compl_apply_left q.2⟩, inv_fun := λ f, ⟨(f : E →ₗ[R] p).ker, is_compl_of_proj f.2⟩, left_inv := λ ⟨q, hq⟩, by simp only [linear_proj_of_is_compl_ker, subtype.coe_mk], right_inv := λ ⟨f, hf⟩, subtype.eq $ f.linear_proj_of_is_compl_of_proj hf } @[simp] lemma coe_is_compl_equiv_proj_apply (q : {q // is_compl p q}) : (p.is_compl_equiv_proj q : E →ₗ[R] p) = linear_proj_of_is_compl p q q.2 := rfl @[simp] lemma coe_is_compl_equiv_proj_symm_apply (f : {f : E →ₗ[R] p // ∀ x : p, f x = x}) : (p.is_compl_equiv_proj.symm f : submodule R E) = (f : E →ₗ[R] p).ker := rfl end submodule namespace linear_map open submodule /-- A linear endomorphism of a module `E` is a projection onto a submodule `p` if it sends every element of `E` to `p` and fixes every element of `p`. The definition allow more generally any `fun_like` type and not just linear maps, so that it can be used for example with `continuous_linear_map` or `matrix`. -/ structure is_proj {F : Type*} [fun_like F M (λ _, M)] (f : F) : Prop := (map_mem : ∀ x, f x ∈ m) (map_id : ∀ x ∈ m, f x = x) lemma is_proj_iff_idempotent (f : M →ₗ[S] M) : (∃ p : submodule S M, is_proj p f) ↔ f ∘ₗ f = f := begin split, { intro h, obtain ⟨p, hp⟩ := h, ext, rw comp_apply, exact hp.map_id (f x) (hp.map_mem x), }, { intro h, use f.range, split, { intro x, exact mem_range_self f x, }, { intros x hx, obtain ⟨y, hy⟩ := mem_range.1 hx, rw [←hy, ←comp_apply, h], }, }, end namespace is_proj variables {p m} /-- Restriction of the codomain of a projection of onto a subspace `p` to `p` instead of the whole space. -/ def cod_restrict {f : M →ₗ[S] M} (h : is_proj m f) : M →ₗ[S] m := f.cod_restrict m h.map_mem @[simp] lemma cod_restrict_apply {f : M →ₗ[S] M} (h : is_proj m f) (x : M) : ↑(h.cod_restrict x) = f x := f.cod_restrict_apply m x @[simp] lemma cod_restrict_apply_cod {f : M →ₗ[S] M} (h : is_proj m f) (x : m) : h.cod_restrict x = x := by {ext, rw [cod_restrict_apply], exact h.map_id x x.2} lemma cod_restrict_ker {f : M →ₗ[S] M} (h : is_proj m f) : h.cod_restrict.ker = f.ker := f.ker_cod_restrict m _ lemma is_compl {f : E →ₗ[R] E} (h : is_proj p f) : is_compl p f.ker := by { rw ←cod_restrict_ker, exact is_compl_of_proj h.cod_restrict_apply_cod, } lemma eq_conj_prod_map' {f : E →ₗ[R] E} (h : is_proj p f) : f = (p.prod_equiv_of_is_compl f.ker h.is_compl).to_linear_map ∘ₗ prod_map id 0 ∘ₗ (p.prod_equiv_of_is_compl f.ker h.is_compl).symm.to_linear_map := begin refine (linear_map.cancel_right (p.prod_equiv_of_is_compl f.ker h.is_compl).surjective).1 _, ext, { simp only [coe_comp, linear_equiv.coe_to_linear_map, coe_inl, function.comp_app, linear_equiv.of_top_apply, linear_equiv.of_injective_apply, coprod_apply, submodule.coe_subtype, coe_zero, add_zero, prod_equiv_of_is_compl_symm_apply_left, prod_map_apply, id_coe, id.def, zero_apply, coe_prod_equiv_of_is_compl', h.map_id x x.2], }, {simp only [coe_comp, linear_equiv.coe_to_linear_map, coe_inr, function.comp_app, linear_equiv.of_top_apply, linear_equiv.of_injective_apply, coprod_apply, submodule.coe_subtype, coe_zero, zero_add, map_coe_ker, prod_equiv_of_is_compl_symm_apply_right, prod_map_apply, id_coe, id.def, zero_apply, coe_prod_equiv_of_is_compl'], } end end is_proj end linear_map end ring section comm_ring namespace linear_map variables {R : Type*} [comm_ring R] {E : Type*} [add_comm_group E] [module R E] {p : submodule R E} lemma is_proj.eq_conj_prod_map {f : E →ₗ[R] E} (h : is_proj p f) : f = (p.prod_equiv_of_is_compl f.ker h.is_compl).conj (prod_map id 0) := by {rw linear_equiv.conj_apply, exact h.eq_conj_prod_map'} end linear_map end comm_ring
779e677cb3f977c00f13feea36dd28db1fee9e0f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/group/prod.lean
7ec27994a99ac8aed79ebf53a9f2857cc5dd6b94
[ "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
13,191
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import algebra.group.hom import data.equiv.mul_add import data.prod import algebra.opposites /-! # Monoid, group etc structures on `M × N` In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. -/ variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace prod @[to_additive] instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ @[simp, to_additive] lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive] lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive] lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl @[to_additive] instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ @[simp, to_additive] lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl @[simp, to_additive] lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl @[to_additive] lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl @[simp, to_additive] lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 := mk.inj_iff @[to_additive] lemma fst_mul_snd [mul_one_class M] [mul_one_class N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive] lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive] lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl @[simp, to_additive] lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl @[to_additive] instance [has_div M] [has_div N] : has_div (M × N) := ⟨λ p q, ⟨p.1 / q.1, p.2 / q.2⟩⟩ @[simp] lemma fst_sub [add_group A] [add_group B] (a b : A × B) : (a - b).1 = a.1 - b.1 := rfl @[simp] lemma snd_sub [add_group A] [add_group B] (a b : A × B) : (a - b).2 = a.2 - b.2 := rfl @[simp] lemma mk_sub_mk [add_group A] [add_group B] (x₁ x₂ : A) (y₁ y₂ : B) : (x₁, y₁) - (x₂, y₂) = (x₁ - x₂, y₁ - y₂) := rfl instance [mul_zero_class M] [mul_zero_class N] : mul_zero_class (M × N) := { zero_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, .. prod.has_zero, .. prod.has_mul } @[to_additive] instance [semigroup M] [semigroup N] : semigroup (M × N) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } instance [semigroup_with_zero M] [semigroup_with_zero N] : semigroup_with_zero (M × N) := { .. prod.mul_zero_class, .. prod.semigroup } @[to_additive] instance [mul_one_class M] [mul_one_class N] : mul_one_class (M × N) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.has_mul, .. prod.has_one } @[to_additive] instance [monoid M] [monoid N] : monoid (M × N) := { .. prod.semigroup, .. prod.mul_one_class } @[to_additive] instance [group G] [group H] : group (G × H) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, div_eq_mul_inv := λ a b, mk.inj_iff.mpr ⟨div_eq_mul_inv _ _, div_eq_mul_inv _ _⟩, .. prod.monoid, .. prod.has_inv, .. prod.has_div } @[to_additive] instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } @[to_additive] instance [left_cancel_semigroup G] [left_cancel_semigroup H] : left_cancel_semigroup (G × H) := { mul_left_cancel := λ a b c h, prod.ext (mul_left_cancel (prod.ext_iff.1 h).1) (mul_left_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [right_cancel_semigroup G] [right_cancel_semigroup H] : right_cancel_semigroup (G × H) := { mul_right_cancel := λ a b c h, prod.ext (mul_right_cancel (prod.ext_iff.1 h).1) (mul_right_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [left_cancel_monoid M] [left_cancel_monoid N] : left_cancel_monoid (M × N) := { .. prod.left_cancel_semigroup, .. prod.monoid } @[to_additive] instance [right_cancel_monoid M] [right_cancel_monoid N] : right_cancel_monoid (M × N) := { .. prod.right_cancel_semigroup, .. prod.monoid } @[to_additive] instance [cancel_monoid M] [cancel_monoid N] : cancel_monoid (M × N) := { .. prod.right_cancel_monoid, .. prod.left_cancel_monoid } @[to_additive] instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) := { .. prod.comm_semigroup, .. prod.monoid } @[to_additive] instance [cancel_comm_monoid M] [cancel_comm_monoid N] : cancel_comm_monoid (M × N) := { .. prod.left_cancel_monoid, .. prod.comm_monoid } instance [mul_zero_one_class M] [mul_zero_one_class N] : mul_zero_one_class (M × N) := { .. prod.mul_zero_class, .. prod.mul_one_class } instance [monoid_with_zero M] [monoid_with_zero N] : monoid_with_zero (M × N) := { .. prod.monoid, .. prod.mul_zero_one_class } instance [comm_monoid_with_zero M] [comm_monoid_with_zero N] : comm_monoid_with_zero (M × N) := { .. prod.comm_monoid, .. prod.monoid_with_zero } @[to_additive] instance [comm_group G] [comm_group H] : comm_group (G × H) := { .. prod.comm_semigroup, .. prod.group } end prod namespace monoid_hom variables (M N) [mul_one_class M] [mul_one_class N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`."] def inl : M →* M × N := ⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`."] def inr : N →* M × N := ⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl @[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl @[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl @[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl section prod variable [mul_one_class P] /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)` -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →* N) (g : M →* P) : M →* N × P := { to_fun := λ x, (f x, g x), map_one' := prod.ext f.map_one g.map_one, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[simp, to_additive prod_apply] lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] [mul_one_class P] (f : M →* M') (g : N →* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [comm_monoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[simp, to_additive] lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id $ M × N) lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end monoid_hom namespace mul_equiv section variables {M N} [mul_one_class M] [mul_one_class N] /-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/ @[to_additive prod_comm "The equivalence between `M × N` and `N × M` given by swapping the components is additive."] def prod_comm : M × N ≃* N × M := { map_mul' := λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, rfl, ..equiv.prod_comm M N } @[simp, to_additive coe_prod_comm] lemma coe_prod_comm : ⇑(prod_comm : M × N ≃* N × M) = prod.swap := rfl @[simp, to_additive coe_prod_comm_symm] lemma coe_prod_comm_symm : ⇑((prod_comm : M × N ≃* N × M).symm) = prod.swap := rfl end section variables {M N} [monoid M] [monoid N] /-- The monoid equivalence between units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive prod_add_units "The additive monoid equivalence between additive units of a product of two additive monoids, and the product of the additive units of each additive monoid."] def prod_units : units (M × N) ≃* units M × units N := { to_fun := (units.map (monoid_hom.fst M N)).prod (units.map (monoid_hom.snd M N)), inv_fun := λ u, ⟨(u.1, u.2), (↑u.1⁻¹, ↑u.2⁻¹), by simp, by simp⟩, left_inv := λ u, by simp, right_inv := λ ⟨u₁, u₂⟩, by simp [units.map], map_mul' := monoid_hom.map_mul _ } end end mul_equiv section units open opposite /-- Canonical homomorphism of monoids from `units α` into `α × αᵒᵖ`. Used mainly to define the natural topology of `units α`. -/ def embed_product (α : Type*) [monoid α] : units α →* α × αᵒᵖ := { to_fun := λ x, ⟨x, op ↑x⁻¹⟩, map_one' := by simp only [one_inv, eq_self_iff_true, units.coe_one, op_one, prod.mk_eq_one, and_self], map_mul' := λ x y, by simp only [mul_inv_rev, op_mul, units.coe_mul, prod.mk_mul_mk] } end units
6e6adf693bfe141ece97e3c4a9f99255e6c670f0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/group/units.lean
067809ddbd65aa0875c4e6af49d597530be96ab9
[ "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
16,346
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a monoid An element of a `monoid` is a unit if it has a two-sided inverse. ## Main declarations * `units M`: the group of units (i.e., invertible elements) of a monoid. * `is_unit x`: a predicate asserting that `x` is a unit (i.e., invertible element) of a monoid. For both declarations, there is an additive counterpart: `add_units` and `is_add_unit`. ## Notation We provide `Mˣ` as notation for `units M`, resembling the notation $R^{\times}$ for the units of a ring, which is common in mathematics. -/ universe u variable {α : Type u} /-- Units of a `monoid`, bundled version. Notation: `αˣ`. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) postfix `ˣ`:1025 := units -- We don't provide notation for the additive version, because its use is somewhat rare. /-- Units of an `add_monoid`, bundled version. An element of an `add_monoid` is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units section has_elem @[to_additive] lemma unique_has_one {α : Type*} [unique α] [has_one α] : default = (1 : α) := unique.default_eq 1 end has_elem namespace units variables [monoid α] @[to_additive] instance : has_coe αˣ α := ⟨val⟩ @[to_additive] instance : has_inv αˣ := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : αˣ) : α := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : αˣ) : α := ↑(u⁻¹) initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix) initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : αˣ → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : αˣ} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : αˣ} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq αˣ := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : αˣ) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : αˣ) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : αˣ := { val := val, inv := inv, inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv } @[to_additive] lemma copy_eq (u : αˣ) (val hv inv hi) : u.copy val hv inv hi = u := ext hv /-- Units of a monoid form a group. -/ @[to_additive] instance : group αˣ := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := has_inv.inv, mul_left_inv := λ u, ext u.inv_val } variables (a b : αˣ) {c : αˣ} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : αˣ) : α) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_eq_one {a : αˣ} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[simp, to_additive] lemma val_eq_coe : a.val = (↑a : α) := rfl @[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : αˣ) : α) := rfl @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {u : αˣ} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv_of_eq {u : αˣ} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : αˣ) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : αˣ) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : αˣ) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : αˣ) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited αˣ := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group αˣ := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr αˣ := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : αˣ) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : αˣ) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : αˣ} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : αˣ} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := inv_eq_of_mul_eq_one $ by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : αˣ := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : αˣ) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : αˣ) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : αˣ) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : αˣ) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : αˣ) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : αˣ) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : αˣ) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : αˣ) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : αˣ} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : αˣ} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : αˣ) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : αˣ} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : αˣ) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : Mˣ`, where `Mˣ` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : Mˣ, (u : M) = a @[nontriviality, to_additive is_add_unit_of_subsingleton] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ attribute [nontriviality] is_add_unit_of_subsingleton @[to_additive] instance [monoid M] : can_lift M Mˣ := { coe := coe, cond := is_unit, prf := λ _, id } @[to_additive] instance [monoid M] [subsingleton M] : unique Mˣ := { default := 1, uniq := λ a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 } @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : Mˣ) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨λ h, h.exists_right_inv, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } /-- Multiplication by a `u : Mˣ` on the right doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` on the right doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : Mˣ) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (λ v, v.mul u.is_unit) /-- Multiplication by a `u : Mˣ` on the left doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_units_add "Addition of a `u : add_units M` on the left doesn't affect `is_add_unit`."] theorem units.is_unit_units_mul {M : Type*} [monoid M] (u : Mˣ) (a : M) : is_unit (↑u * a) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (↑u⁻¹ * (↑u * a)), by existsi u⁻¹ * v; rw [←hv, units.coe_mul], by rwa [←mul_assoc, units.inv_mul, one_mul] at this) u.is_unit.mul @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[simp, to_additive] lemma is_unit.mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ @[to_additive "The element of the additive group of additive units, corresponding to an element of an additive monoid which is an additive unit."] noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : Mˣ := (classical.some h).copy a (classical.some_spec h).symm _ rfl @[to_additive] lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := rfl @[to_additive] lemma is_unit.coe_inv_mul [monoid M] {a : M} (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := units.mul_inv _ @[to_additive] lemma is_unit.mul_coe_inv [monoid M] {a : M} (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := begin convert units.mul_inv _, simp [h.unit_spec] end end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
02d7962f26385fc5b3ead2f90e7580f26210faea
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/topology/subset_properties.lean
f49c531e08c588ec9bc098c459b1f07a4b929b78
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
55,274
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import topology.continuous_on /-! # Properties of subsets of topological spaces ## Main definitions `compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`, `is_totally_separated` TODO: write better docs ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible and connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible` and `is_preconnected` respectively. In other words, the only difference is whether the empty space counts as irreducible and/or connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} [topological_space α] /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def is_compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ 𝓟 s → ∃a∈s, cluster_pt a f lemma is_compact.inter_right {s t : set α} (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := assume f hnf hstf, let ⟨a, hsa, (ha : cluster_pt a f)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in have a ∈ t, from ht.mem_of_nhds_within_ne_bot $ ne_bot_of_le_ne_bot ha $ inf_le_inf_left _ (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), ⟨a, ⟨hsa, this⟩, ha⟩ lemma is_compact.inter_left {s t : set α} (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs lemma compact_diff {s t : set α} (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) lemma compact_of_is_closed_subset {s t : set α} (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma is_compact.adherence_nhdset {s t : set α} {f : filter α} (hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_eq_bot $ assume : f ⊓ 𝓟 tᶜ ≠ ⊥, let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha (hfa.of_inf_left), have tᶜ ∩ t ∈ nhds_within a (tᶜ), from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this), have A : nhds_within a tᶜ = ⊥, from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this, have nhds_within a tᶜ ≠ ⊥, from hfa.of_inf_right, absurd A this lemma compact_iff_ultrafilter_le_nhds {s : set α} : is_compact s ↔ (∀f, is_ultrafilter f → f ≤ 𝓟 s → ∃a∈s, f ≤ 𝓝 a) := ⟨assume hs : is_compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, is_ultrafilter f → f ≤ 𝓟 s → ∃a∈s, f ≤ 𝓝 a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have cluster_pt a (ultrafilter_of f), from cluster_pt.of_le_nhds h (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, this.mono ultrafilter_of_le⟩⟩ /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover {s : set α} {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := classical.by_contradiction $ assume h, have h : ∀ t : finset ι, ¬ s ⊆ ⋃ i ∈ t, U i, from assume t ht, h ⟨t, ht⟩, let f : filter α := (⨅t:finset ι, 𝓟 (s \ ⋃ i ∈ t, U i)), ⟨a, ha⟩ := (@ne_empty_iff_nonempty α s).1 (assume h', h ∅ $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_ne_bot_of_directed ⟨a⟩ (assume t₁ t₂, ⟨t₁ ∪ t₂, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_right _ _⟩) (assume t, show 𝓟 (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h _), have f ≤ 𝓟 s, from infi_le_of_le ∅ $ show 𝓟 (s \ _) ≤ 𝓟 s, from le_principal_iff.2 (diff_subset _ _), let ⟨a, ha, (h : cluster_pt a f)⟩ := hs f ‹f ≠ ⊥› this, ⟨_, ⟨i, rfl⟩, (ha : a ∈ U i)⟩ := hsU ha in have f ≤ 𝓟 (U i)ᶜ, from infi_le_of_le {i} $ principal_mono.mpr $ show s \ _ ⊆ (U i)ᶜ, by simp [diff_subset_iff], have is_closed (U i)ᶜ, from is_open_compl_iff.mp $ by rw compl_compl; exact hUo i, have a ∈ (U i)ᶜ, from is_closed_iff_cluster_pt.mp this _ (h.mono ‹f ≤ 𝓟 (U i)ᶜ›), this ‹a ∈ U i› /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) hZc (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hι hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, refine nonempty.mono _ (hZn i₁), exact subset_inter hi₁.left (subset_bInter hi₁.right) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd, have hZd : directed (⊇) Z, from directed_of_sup Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := begin rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩, refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩, { intros i hi, erw finset.mem_image at hi, rcases hi with ⟨s, hsd, rfl⟩, exact s.property }, { refine subset.trans hd _, rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩, refine ⟨c s.val, ⟨s.val, _⟩, H⟩, simp [finset.mem_image_of_mem subtype.val hsd] }, { rintro ⟨i, hi⟩, exact hc₁ i hi }, { refine subset.trans hc₂ _, rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩, exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ }, end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_of_finite_subfamily_closed {s : set α} (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : is_compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [cluster_pt, not_exists, not_not], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝 x ⊓ 𝓟 t₂, from (𝓝 x ⊓ 𝓟 t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝 x ⊓ 𝓟 t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_cluster_pts] at hx; exact hx t₂ ht₂ this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂i∈t, subtype.val i) ∈ f, from Inter_mem_sets t.finite_to_set $ assume i hi, i.2, have s ∩ (⋂i∈t, subtype.val i) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit), show false, from hxi this, hfn $ by rwa [empty_in_sets_eq_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_of_finite_subcover {s : set α} (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : is_compact s := compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_iff_finite_subcover {s : set α} : is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_iff_finite_subfamily_closed {s : set α} : is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩ @[simp] lemma compact_empty : is_compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf @[simp] lemma compact_singleton {a : α} : is_compact ({a} : set α) := compact_of_finite_subcover $ assume ι U hUo hsU, let ⟨i, hai⟩ := (show ∃i : ι, a ∈ U i, from mem_Union.1 $ singleton_subset_iff.1 hsU) in ⟨{i}, singleton_subset_iff.2 (by simpa only [finset.bUnion_singleton])⟩ lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s) (hf : ∀i ∈ s, is_compact (f i)) : is_compact (⋃i ∈ s, f i) := compact_of_finite_subcover $ assume ι U hUo hsU, have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bind finset.univ finite_subcovers in have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma compact_Union {f : β → set α} [fintype β] (h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.is_compact {s : set α} (hs : finite s) : is_compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton) lemma is_compact.union {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) section tube_lemma variables [topological_space β] /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : is_compact (univ : set α)) lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] {f : filter α} (h : f ≠ ⊥) : ∃ x, cluster_pt x f := by simpa using compact_univ f h (by simpa using f.univ_sets) theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) : compact_space α := { compact_univ := begin apply compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) : is_compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) variables [topological_space β] lemma is_compact.image_of_continuous_on {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := begin intros l lne ls, have ne_bot : l.comap f ⊓ 𝓟 s ≠ ⊥, from comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), rcases hs (l.comap f ⊓ 𝓟 s) ne_bot inf_le_right with ⟨a, has, ha⟩, use [f a, mem_image_of_mem f has], apply ne_bot_of_le_ne_bot (@@map_ne_bot f ha), convert (tendsto_comap.inf (hf a has) : tendsto f (comap f l ⊓ (𝓝 a ⊓ 𝓟 s)) _) using 1 ; ac_refl end lemma is_compact.image {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : is_compact (range f) := by rw ← image_univ; exact compact_univ.image hf local notation `𝓟` := principal /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_cluster_pt at hC ⊢, assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)), have : map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, { suffices : map πY (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, from map_ne_bot (λ h, this $ by rw h ; exact map_bot ), calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal ... ≠ ⊥ : y_closure }, obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), from cluster_point_of_compact this, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw [cluster_pt, ← filter.map_ne_bot_iff πX], calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm ... ≠ ⊥ : hx, end lemma embedding.compact_iff_compact_image {s : set α} {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := iff.intro (assume h, h.image hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ 𝓟 (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : is_compact s ↔ is_compact ((coe : _ → α) '' s) := embedding_subtype_coe.compact_iff_compact_image lemma compact_iff_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl lemma compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases hs (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases ht (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := set.finite_univ.is_compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (compact_range continuous_inl).union (compact_range continuous_inr) end⟩ section tychonoff variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {s : Πi:ι, set (π i)} : (∀i, is_compact (s i)) → is_compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ 𝓝 a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end /-- A version of Tychonoff's theorem that uses `set.pi`. -/ lemma compact_univ_pi {s : Πi:ι, set (π i)} (h : ∀i, is_compact (s i)) : is_compact (set.pi set.univ s) := by { convert compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] } instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : is_compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s) /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := begin rcases locally_compact_space.local_compact_nhds x U _ with ⟨K, h1K, h2K, h3K⟩, { refine ⟨K, h3K, _, h2K⟩, rwa [ mem_interior_iff_mem_nhds] }, rwa [← mem_interior_iff_mem_nhds, interior_eq_of_open hU] end end compact section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩ theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ := ⟨hs.2, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩ theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := is_clopen_inter hs (is_clopen_compl ht) end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, rfl, h2, h4⟩⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) end prio attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority] theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← set.mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [set.inter_comm s u', ← u'_eq] at this, rw [set.inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← set.mem_preimage, apply set.mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h t₁ᶜ t₂ᶜ, simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end end preirreducible section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := ⟨H.nonempty.closure, H.is_preconnected.closure⟩ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩ theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (subset_connected_component is_connected_connected_component.closure.is_preconnected (subset_closure mem_connected_component)) subset_closure theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component is_irreducible_irreducible_component.is_connected.is_preconnected mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) export preconnected_space (is_preconnected_univ) section prio set_option default_priority 100 -- see Note [default priority] /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) end prio attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := classical.or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := classical.or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, push_neg at hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end end preconnected section totally_disconnected /-- A set is called totally disconnected if all of its connected components are singletons. -/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → subsingleton t theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩ theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q, from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩ /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $ assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in (ext_iff.1 huv r).1 hruv⟩ /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ end totally_separated
a6520520ebab513eab60dd51df58f5b66956f0bd
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/complete_lattice.lean
97aeb7ec0a527da849c49947bd611e31e69b9398
[ "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
52,129
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 /-! # 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_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 α) _ _ 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 {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := @supr_range (order_dual α) _ _ _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := by rw [← infi_subtype'', infi, range_comp, subtype.range_coe] 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 := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq (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 Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) := by rw [Sup_eq_supr, supr_subtype']; refl 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⟩) := 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 _ _) 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)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) 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)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_of_left_le $ infi_le _ _ | sum.inr j := inf_le_of_right_le $ infi_le _ _ end) 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 complete_lattice_Prop : 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, .. bounded_distrib_lattice_Prop } @[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
202894b1ccb02018b8042be53d03245d48bba126
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/p_series.lean
63e598c9b49616c73e1824a12f5b3e4db66d7408
[ "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
10,267
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import analysis.special_functions.pow /-! # Convergence of `p`-series In this file we prove that the series `∑' k in ℕ, 1 / k ^ p` converges if and only if `p > 1`. The proof is based on the [Cauchy condensation test](https://en.wikipedia.org/wiki/Cauchy_condensation_test): `∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. We prove this test in `nnreal.summable_condensed_iff` and `summable_condensed_iff_of_nonneg`, then use it to prove `summable_one_div_rpow`. After this transformation, a `p`-series turns into a geometric series. ## TODO It should be easy to generalize arguments to Schlömilch's generalization of the Cauchy condensation test once we need it. ## Tags p-series, Cauchy condensation test -/ open filter open_locale big_operators ennreal nnreal topological_space /-! ### Cauchy condensation test In this section we prove the Cauchy condensation test: for `f : ℕ → ℝ≥0` or `f : ℕ → ℝ`, `∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. Instead of giving a monolithic proof, we split it into a series of lemmas with explicit estimates of partial sums of each series in terms of the partial sums of the other series. -/ namespace finset variables {M : Type*} [ordered_add_comm_monoid M] {f : ℕ → M} lemma le_sum_condensed' (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in Ico 1 (2 ^ n), f k) ≤ ∑ k in range n, (2 ^ k) •ℕ f (2 ^ k) := begin induction n with n ihn, { simp }, suffices : (∑ k in Ico (2 ^ n) (2 ^ (n + 1)), f k) ≤ (2 ^ n) •ℕ f (2 ^ n), { rw [sum_range_succ, add_comm, ← sum_Ico_consecutive], exact add_le_add ihn this, exacts [n.one_le_two_pow, nat.pow_le_pow_of_le_right zero_lt_two n.le_succ] }, have : ∀ k ∈ Ico (2 ^ n) (2 ^ (n + 1)), f k ≤ f (2 ^ n) := λ k hk, hf (pow_pos zero_lt_two _) (Ico.mem.mp hk).1, convert sum_le_sum this, simp [pow_succ, two_mul] end lemma le_sum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range (2 ^ n), f k) ≤ f 0 + ∑ k in range n, (2 ^ k) •ℕ f (2 ^ k) := begin convert add_le_add_left (le_sum_condensed' hf n) (f 0), rw [← sum_range_add_sum_Ico _ n.one_le_two_pow, sum_range_succ, sum_range_zero, add_zero] end lemma sum_condensed_le' (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range n, (2 ^ k) •ℕ f (2 ^ (k + 1))) ≤ ∑ k in Ico 2 (2 ^ n + 1), f k := begin induction n with n ihn, { simp }, suffices : (2 ^ n) •ℕ f (2 ^ (n + 1)) ≤ ∑ k in Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f k, { rw [sum_range_succ, add_comm, ← sum_Ico_consecutive], exact add_le_add ihn this, exacts [add_le_add_right n.one_le_two_pow _, add_le_add_right (nat.pow_le_pow_of_le_right zero_lt_two n.le_succ) _] }, have : ∀ k ∈ Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f (2 ^ (n + 1)) ≤ f k := λ k hk, hf (n.one_le_two_pow.trans_lt $ (nat.lt_succ_of_le le_rfl).trans_le (Ico.mem.mp hk).1) (nat.le_of_lt_succ $ (Ico.mem.mp hk).2), convert sum_le_sum this, simp [pow_succ, two_mul] end lemma sum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range (n + 1), (2 ^ k) •ℕ f (2 ^ k)) ≤ f 1 + 2 •ℕ ∑ k in Ico 2 (2 ^ n + 1), f k := begin convert add_le_add_left (nsmul_le_nsmul_of_le_right (sum_condensed_le' hf n) 2) (f 1), simp [sum_range_succ', add_comm, pow_succ, mul_nsmul, sum_nsmul] end end finset namespace ennreal variable {f : ℕ → ennreal} lemma le_tsum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : (∑' k, f k) ≤ f 0 + ∑' k : ℕ, (2 ^ k) * f (2 ^ k) := begin rw [ennreal.tsum_eq_supr_nat' (nat.tendsto_pow_at_top_at_top_of_one_lt _root_.one_lt_two)], refine supr_le (λ n, (finset.le_sum_condensed hf n).trans (add_le_add_left _ _)), simp only [nsmul_eq_mul, nat.cast_pow, nat.cast_two], apply ennreal.sum_le_tsum end lemma tsum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) : (∑' k : ℕ, (2 ^ k) * f (2 ^ k)) ≤ f 1 + 2 * ∑' k, f k := begin rw [ennreal.tsum_eq_supr_nat' (tendsto_at_top_mono nat.le_succ tendsto_id), two_mul, ← two_nsmul], refine supr_le (λ n, le_trans _ (add_le_add_left (nsmul_le_nsmul_of_le_right (ennreal.sum_le_tsum $ finset.Ico 2 (2^n + 1)) _) _)), simpa using finset.sum_condensed_le hf n end end ennreal namespace nnreal /-- Cauchy condensation test for a series of `nnreal` version. -/ lemma summable_condensed_iff {f : ℕ → ℝ≥0} (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f := begin simp only [← ennreal.tsum_coe_ne_top_iff_summable, ne.def, not_iff_not, ennreal.coe_mul, ennreal.coe_pow, ennreal.coe_two], split; intro h, { replace hf : ∀ m n, 1 < m → m ≤ n → (f n : ennreal) ≤ f m := λ m n hm hmn, ennreal.coe_le_coe.2 (hf (zero_lt_one.trans hm) hmn), simpa [h, ennreal.add_eq_top] using (ennreal.tsum_condensed_le hf) }, { replace hf : ∀ m n, 0 < m → m ≤ n → (f n : ennreal) ≤ f m := λ m n hm hmn, ennreal.coe_le_coe.2 (hf hm hmn), simpa [h, ennreal.add_eq_top] using (ennreal.le_tsum_condensed hf) } end end nnreal /-- Cauchy condensation test for series of nonnegative real numbers. -/ lemma summable_condensed_iff_of_nonneg {f : ℕ → ℝ} (h_nonneg : ∀ n, 0 ≤ f n) (h_mono : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f := begin set g : ℕ → ℝ≥0 := λ n, ⟨f n, h_nonneg n⟩, have : f = λ n, g n := rfl, simp only [this], have : ∀ ⦃m n⦄, 0 < m → m ≤ n → g n ≤ g m := λ m n hm h, nnreal.coe_le_coe.2 (h_mono hm h), exact_mod_cast nnreal.summable_condensed_iff this end open real /-! ### Convergence of the `p`-series In this section we prove that for a real number `p`, the series `∑' n : ℕ, 1 / (n ^ p)` converges if and only if `1 < p`. There are many different proofs of this fact. The proof in this file uses the Cauchy condensation test we formalized above. This test implies that `∑ n, 1 / (n ^ p)` converges if and only if `∑ n, 2 ^ n / ((2 ^ n) ^ p)` converges, and the latter series is a geometric series with common ratio `2 ^ {1 - p}`. -/ /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges if and only if `1 < p`. -/ @[simp] lemma real.summable_nat_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p := begin cases le_or_lt 0 p with hp hp, /- Cauchy condensation test applies only to monotonically decreasing sequences, so we consider the cases `0 ≤ p` and `p < 0` separately. -/ { rw ← summable_condensed_iff_of_nonneg, { simp_rw [nat.cast_pow, nat.cast_two, ← rpow_nat_cast, ← rpow_mul zero_lt_two.le, mul_comm _ p, rpow_mul zero_lt_two.le, rpow_nat_cast, ← inv_pow', ← mul_pow, summable_geometric_iff_norm_lt_1], nth_rewrite 0 [← rpow_one 2], rw [← division_def, ← rpow_sub zero_lt_two, norm_eq_abs, abs_of_pos (rpow_pos_of_pos zero_lt_two _), rpow_lt_one_iff zero_lt_two.le], norm_num }, { intro n, exact inv_nonneg.2 (rpow_nonneg_of_nonneg n.cast_nonneg _) }, { intros m n hm hmn, exact inv_le_inv_of_le (rpow_pos_of_pos (nat.cast_pos.2 hm) _) (rpow_le_rpow m.cast_nonneg (nat.cast_le.2 hmn) hp) } }, /- If `p < 0`, then `1 / n ^ p` tends to infinity, thus the series diverges. -/ { suffices : ¬summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ), { have : ¬(1 < p) := λ hp₁, hp.not_le (zero_le_one.trans hp₁.le), simpa [this, -one_div] }, { intro h, obtain ⟨k : ℕ, hk₁ : ((k ^ p)⁻¹ : ℝ) < 1, hk₀ : k ≠ 0⟩ := ((h.tendsto_cofinite_zero.eventually (gt_mem_nhds zero_lt_one)).and (eventually_cofinite_ne 0)).exists, apply hk₀, rw [← zero_lt_iff_ne_zero, ← @nat.cast_pos ℝ] at hk₀, simpa [inv_lt_one_iff_of_pos (rpow_pos_of_pos hk₀ _), one_lt_rpow_iff_of_pos hk₀, hp, hp.not_lt, hk₀] using hk₁ } } end /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges if and only if `1 < p`. -/ lemma real.summable_one_div_nat_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p := by simp /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges if and only if `1 < p`. -/ @[simp] lemma real.summable_nat_pow_inv {p : ℕ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p := by simp only [← rpow_nat_cast, real.summable_nat_rpow_inv, nat.one_lt_cast] /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges if and only if `1 < p`. -/ lemma real.summable_one_div_nat_pow {p : ℕ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p := by simp /-- Harmonic series is not unconditionally summable. -/ lemma real.not_summable_nat_cast_inv : ¬summable (λ n, n⁻¹ : ℕ → ℝ) := have ¬summable (λ n, (n^1)⁻¹ : ℕ → ℝ), from mt real.summable_nat_pow_inv.1 (lt_irrefl 1), by simpa /-- Harmonic series is not unconditionally summable. -/ lemma real.not_summable_one_div_nat_cast : ¬summable (λ n, 1 / n : ℕ → ℝ) := by simpa only [inv_eq_one_div] using real.not_summable_nat_cast_inv /-- Harmonic series diverges. -/ lemma real.tendsto_sum_range_one_div_nat_succ_at_top : tendsto (λ n, ∑ i in finset.range n, (1 / (i + 1) : ℝ)) at_top at_top := begin rw ← not_summable_iff_tendsto_nat_at_top_of_nonneg, { exact_mod_cast mt (summable_nat_add_iff 1).1 real.not_summable_one_div_nat_cast }, { exact λ i, div_nonneg zero_le_one i.cast_add_one_pos.le } end @[simp] lemma nnreal.summable_one_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ≥0) ↔ 1 < p := by simp [← nnreal.summable_coe] lemma nnreal.summable_one_div_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ≥0) ↔ 1 < p := by simp
d2059e9048b6c4d7fcce9d24ab6761ea940b141e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finsupp/ne_locus.lean
3a37840ccb78e01c1b3b9cd97ce267679c3a5541
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,537
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.finsupp.defs /-! # Locus of unequal values of finitely supported functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `α N` be two Types, assume that `N` has a `0` and let `f g : α →₀ N` be finitely supported functions. ## Main definition * `finsupp.ne_locus f g : finset α`, the finite subset of `α` where `f` and `g` differ. In the case in which `N` is an additive group, `finsupp.ne_locus f g` coincides with `finsupp.support (f - g)`. -/ variables {α M N P : Type*} namespace finsupp variable [decidable_eq α] section N_has_zero variables [decidable_eq N] [has_zero N] (f g : α →₀ N) /-- Given two finitely supported functions `f g : α →₀ N`, `finsupp.ne_locus f g` is the `finset` where `f` and `g` differ. This generalizes `(f - g).support` to situations without subtraction. -/ def ne_locus (f g : α →₀ N) : finset α := (f.support ∪ g.support).filter (λ x, f x ≠ g x) @[simp] lemma mem_ne_locus {f g : α →₀ N} {a : α} : a ∈ f.ne_locus g ↔ f a ≠ g a := by simpa only [ne_locus, finset.mem_filter, finset.mem_union, mem_support_iff, and_iff_right_iff_imp] using ne.ne_or_ne _ lemma not_mem_ne_locus {f g : α →₀ N} {a : α} : a ∉ f.ne_locus g ↔ f a = g a := mem_ne_locus.not.trans not_ne_iff @[simp] lemma coe_ne_locus : ↑(f.ne_locus g) = {x | f x ≠ g x} := by { ext, exact mem_ne_locus } @[simp] lemma ne_locus_eq_empty {f g : α →₀ N} : f.ne_locus g = ∅ ↔ f = g := ⟨λ h, ext (λ a, not_not.mp (mem_ne_locus.not.mp (finset.eq_empty_iff_forall_not_mem.mp h a))), λ h, h ▸ by simp only [ne_locus, ne.def, eq_self_iff_true, not_true, finset.filter_false]⟩ @[simp] lemma nonempty_ne_locus_iff {f g : α →₀ N} : (f.ne_locus g).nonempty ↔ f ≠ g := finset.nonempty_iff_ne_empty.trans ne_locus_eq_empty.not lemma ne_locus_comm : f.ne_locus g = g.ne_locus f := by simp_rw [ne_locus, finset.union_comm, ne_comm] @[simp] lemma ne_locus_zero_right : f.ne_locus 0 = f.support := by { ext, rw [mem_ne_locus, mem_support_iff, coe_zero, pi.zero_apply] } @[simp] lemma ne_locus_zero_left : (0 : α →₀ N).ne_locus f = f.support := (ne_locus_comm _ _).trans (ne_locus_zero_right _) end N_has_zero section ne_locus_and_maps lemma subset_map_range_ne_locus [decidable_eq N] [has_zero N] [decidable_eq M] [has_zero M] (f g : α →₀ N) {F : N → M} (F0 : F 0 = 0) : (f.map_range F F0).ne_locus (g.map_range F F0) ⊆ f.ne_locus g := λ x, by simpa only [mem_ne_locus, map_range_apply, not_imp_not] using congr_arg F lemma zip_with_ne_locus_eq_left [decidable_eq N] [has_zero M] [decidable_eq P] [has_zero P] [has_zero N] {F : M → N → P} (F0 : F 0 0 = 0) (f : α →₀ M) (g₁ g₂ : α →₀ N) (hF : ∀ f, function.injective (λ g, F f g)) : (zip_with F F0 f g₁).ne_locus (zip_with F F0 f g₂) = g₁.ne_locus g₂ := by { ext, simpa only [mem_ne_locus] using (hF _).ne_iff } lemma zip_with_ne_locus_eq_right [decidable_eq M] [has_zero M] [decidable_eq P] [has_zero P] [has_zero N] {F : M → N → P} (F0 : F 0 0 = 0) (f₁ f₂ : α →₀ M) (g : α →₀ N) (hF : ∀ g, function.injective (λ f, F f g)) : (zip_with F F0 f₁ g).ne_locus (zip_with F F0 f₂ g) = f₁.ne_locus f₂ := by { ext, simpa only [mem_ne_locus] using (hF _).ne_iff } lemma map_range_ne_locus_eq [decidable_eq N] [decidable_eq M] [has_zero M] [has_zero N] (f g : α →₀ N) {F : N → M} (F0 : F 0 = 0) (hF : function.injective F) : (f.map_range F F0).ne_locus (g.map_range F F0) = f.ne_locus g := by { ext, simpa only [mem_ne_locus] using hF.ne_iff } end ne_locus_and_maps variables [decidable_eq N] @[simp] lemma ne_locus_add_left [add_left_cancel_monoid N] (f g h : α →₀ N) : (f + g).ne_locus (f + h) = g.ne_locus h := zip_with_ne_locus_eq_left _ _ _ _ add_right_injective @[simp] lemma ne_locus_add_right [add_right_cancel_monoid N] (f g h : α →₀ N) : (f + h).ne_locus (g + h) = f.ne_locus g := zip_with_ne_locus_eq_right _ _ _ _ add_left_injective section add_group variables [add_group N] (f f₁ f₂ g g₁ g₂ : α →₀ N) @[simp] lemma ne_locus_neg_neg : ne_locus (-f) (-g) = f.ne_locus g := map_range_ne_locus_eq _ _ neg_zero neg_injective lemma ne_locus_neg : ne_locus (-f) g = f.ne_locus (-g) := by rw [←ne_locus_neg_neg, neg_neg] lemma ne_locus_eq_support_sub : f.ne_locus g = (f - g).support := by rw [←ne_locus_add_right _ _ (-g), add_right_neg, ne_locus_zero_right, sub_eq_add_neg] @[simp] lemma ne_locus_sub_left : ne_locus (f - g₁) (f - g₂) = ne_locus g₁ g₂ := by simp only [sub_eq_add_neg, ne_locus_add_left, ne_locus_neg_neg] @[simp] lemma ne_locus_sub_right : ne_locus (f₁ - g) (f₂ - g) = ne_locus f₁ f₂ := by simpa only [sub_eq_add_neg] using ne_locus_add_right _ _ _ @[simp] lemma ne_locus_self_add_right : ne_locus f (f + g) = g.support := by rw [←ne_locus_zero_left, ←ne_locus_add_left f 0 g, add_zero] @[simp] lemma ne_locus_self_add_left : ne_locus (f + g) f = g.support := by rw [ne_locus_comm, ne_locus_self_add_right] @[simp] lemma ne_locus_self_sub_right : ne_locus f (f - g) = g.support := by rw [sub_eq_add_neg, ne_locus_self_add_right, support_neg] @[simp] lemma ne_locus_self_sub_left : ne_locus (f - g) f = g.support := by rw [ne_locus_comm, ne_locus_self_sub_right] end add_group end finsupp
a7fb35a5d28ff8faf0dc1bc337efb265783a9266
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/witt_vector/teichmuller.lean
545542633db73b3491306729dfdb395772ddc476
[ "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
4,495
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.witt_vector.basic /-! # Teichmüller lifts This file defines `witt_vector.teichmuller`, a monoid hom `R →* 𝕎 R`, which embeds `r : R` as the `0`-th component of a Witt vector whose other coefficients are `0`. ## Main declarations - `witt_vector.teichmuller`: the Teichmuller map. - `witt_vector.map_teichmuller`: `witt_vector.teichmuller` is a natural transformation. - `witt_vector.ghost_component_teichmuller`: the `n`-th ghost component of `witt_vector.teichmuller p r` is `r ^ p ^ n`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector open mv_polynomial variables (p : ℕ) {R S : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` /-- The underlying function of the monoid hom `witt_vector.teichmuller`. The `0`-th coefficient of `teichmuller_fun p r` is `r`, and all others are `0`. -/ def teichmuller_fun (r : R) : 𝕎 R := ⟨p, λ n, if n = 0 then r else 0⟩ /-! ## `teichmuller` is a monoid homomorphism On ghost components, it is clear that `teichmuller_fun` is a monoid homomorphism. But in general the ghost map is not injective. We follow the same strategy as for proving that the the ring operations on `𝕎 R` satisfy the ring axioms. 1. We first prove it for rings `R` where `p` is invertible, because then the ghost map is in fact an isomorphism. 2. After that, we derive the result for `mv_polynomial R ℤ`, 3. and from that we can prove the result for arbitrary `R`. -/ include hp private lemma ghost_component_teichmuller_fun (r : R) (n : ℕ) : ghost_component n (teichmuller_fun p r) = r ^ p ^ n := begin rw [ghost_component_apply, aeval_witt_polynomial, finset.sum_eq_single 0, pow_zero, one_mul, nat.sub_zero], { refl }, { intros i hi h0, convert mul_zero _, convert zero_pow _, { cases i, { contradiction }, { refl } }, { apply pow_pos, apply nat.prime.pos, assumption } }, { rw finset.mem_range, intro h, exact (h (nat.succ_pos n)).elim } end private lemma map_teichmuller_fun (f : R →+* S) (r : R) : map f (teichmuller_fun p r) = teichmuller_fun p (f r) := by { ext n, cases n, { refl }, { exact f.map_zero } } private lemma teichmuller_mul_aux₁ (x y : mv_polynomial R ℚ) : teichmuller_fun p (x * y) = teichmuller_fun p x * teichmuller_fun p y := begin apply (ghost_map.bijective_of_invertible p (mv_polynomial R ℚ)).1, rw ring_hom.map_mul, ext1 n, simp only [pi.mul_apply, ghost_map_apply, ghost_component_teichmuller_fun, mul_pow], end private lemma teichmuller_mul_aux₂ (x y : mv_polynomial R ℤ) : teichmuller_fun p (x * y) = teichmuller_fun p x * teichmuller_fun p y := begin refine map_injective (mv_polynomial.map (int.cast_ring_hom ℚ)) (mv_polynomial.map_injective _ int.cast_injective) _, simp only [teichmuller_mul_aux₁, map_teichmuller_fun, ring_hom.map_mul] end /-- The Teichmüller lift of an element of `R` to `𝕎 R`. The `0`-th coefficient of `teichmuller p r` is `r`, and all others are `0`. This is a monoid homomorphism. -/ noncomputable def teichmuller : R →* 𝕎 R := { to_fun := teichmuller_fun p, map_one' := begin ext ⟨⟩, { rw one_coeff_zero, refl }, { rw one_coeff_eq_of_pos _ _ _ (nat.succ_pos n), refl } end, map_mul' := begin intros x y, rcases counit_surjective R x with ⟨x, rfl⟩, rcases counit_surjective R y with ⟨y, rfl⟩, simp only [← map_teichmuller_fun, ← ring_hom.map_mul, teichmuller_mul_aux₂], end } @[simp] lemma teichmuller_coeff_zero (r : R) : (teichmuller p r).coeff 0 = r := rfl @[simp] lemma teichmuller_coeff_pos (r : R) : ∀ (n : ℕ) (hn : 0 < n), (teichmuller p r).coeff n = 0 | (n+1) _ := rfl. @[simp] lemma teichmuller_zero : teichmuller p (0:R) = 0 := by ext ⟨⟩; { rw zero_coeff, refl } /-- `teichmuller` is a natural transformation. -/ @[simp] lemma map_teichmuller (f : R →+* S) (r : R) : map f (teichmuller p r) = teichmuller p (f r) := map_teichmuller_fun _ _ _ /-- The `n`-th ghost component of `teichmuller p r` is `r ^ p ^ n`. -/ @[simp] lemma ghost_component_teichmuller (r : R) (n : ℕ) : ghost_component n (teichmuller p r) = r ^ p ^ n := ghost_component_teichmuller_fun _ _ _ end witt_vector
bfac65bce1dbea246c90e3ad4e5377a0fd187296
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/real/ereal.lean
0db1cd04d8c9f001eafa46e1016a141c1a69283b
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
19,694
lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import data.real.basic import data.real.ennreal /-! # The extended reals [-∞, ∞]. This file defines `ereal`, the real numbers together with a top and bottom element, referred to as ⊤ and ⊥. It is implemented as `with_top (with_bot ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An ad hoc addition is defined, for which `ereal` is an `add_comm_monoid`, and even an ordered one (if `a ≤ a'` and `b ≤ b'` then `a + b ≤ a' + b'`). Note however that addition is badly behaved at `(⊥, ⊤)` and `(⊤, ⊥)` so this can not be upgraded to a group structure. Our choice is that `⊥ + ⊤ = ⊤ + ⊥ = ⊤`. An ad hoc subtraction is then defined by `x - y = x + (-y)`. It does not have nice properties, but it is sometimes convenient to have. An ad hoc multiplication is defined, for which `ereal` is a `comm_monoid_with_zero`. This does not distribute with addition, as `⊤ = ⊤ - ⊥ = 1*⊤ - 1*⊤ ≠ (1 - 1) * ⊤ = 0 * ⊤ = 0`. `ereal` is a `complete_linear_order`; this is deduced by type class inference from the fact that `with_top (with_bot L)` is a complete linear order if `L` is a conditionally complete linear order. Coercions from `ℝ` and from `ℝ≥0∞` are registered, and their basic properties are proved. The main one is the real coercion, and is usually referred to just as `coe` (lemmas such as `ereal.coe_add` deal with this coercion). The one from `ennreal` is usually called `coe_ennreal` in the `ereal` namespace. ## Tags real, ereal, complete lattice ## TODO abs : ereal → ℝ≥0∞ In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞) and then prove whatever bits of the ordered ring/field axioms still hold. They also do some limits stuff (liminf/limsup etc). See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html -/ open_locale ennreal nnreal /-- ereal : The type `[-∞, ∞]` -/ @[derive [has_top, comm_monoid_with_zero, has_Sup, has_Inf, complete_linear_order, linear_ordered_add_comm_monoid_with_top]] def ereal := with_top (with_bot ℝ) /-- The canonical inclusion froms reals to ereals. Do not use directly: as this is registered as a coercion, use the coercion instead. -/ def real.to_ereal : ℝ → ereal := some ∘ some namespace ereal -- TODO: Provide explicitly, otherwise it is inferred noncomputably from `complete_linear_order` instance : has_bot ereal := ⟨some ⊥⟩ @[simp] lemma bot_lt_top : (⊥ : ereal) < ⊤ := with_top.coe_lt_top _ @[simp] lemma bot_ne_top : (⊥ : ereal) ≠ ⊤ := bot_lt_top.ne instance : has_coe ℝ ereal := ⟨real.to_ereal⟩ @[simp, norm_cast] protected lemma coe_le_coe_iff {x y : ℝ} : (x : ereal) ≤ (y : ereal) ↔ x ≤ y := by { unfold_coes, simp [real.to_ereal] } @[simp, norm_cast] protected lemma coe_lt_coe_iff {x y : ℝ} : (x : ereal) < (y : ereal) ↔ x < y := by { unfold_coes, simp [real.to_ereal] } @[simp, norm_cast] protected lemma coe_eq_coe_iff {x y : ℝ} : (x : ereal) = (y : ereal) ↔ x = y := by { unfold_coes, simp [real.to_ereal, option.some_inj] } /-- The canonical map from nonnegative extended reals to extended reals -/ def _root_.ennreal.to_ereal : ℝ≥0∞ → ereal | ⊤ := ⊤ | (some x) := x.1 instance has_coe_ennreal : has_coe ℝ≥0∞ ereal := ⟨ennreal.to_ereal⟩ instance : has_zero ereal := ⟨(0 : ℝ)⟩ instance : inhabited ereal := ⟨0⟩ /-- A recursor for `ereal` in terms of the coercion. A typical invocation looks like `induction x using ereal.rec`. Note that using `induction` directly will unfold `ereal` to `option` which is undesirable. When working in term mode, note that pattern matching can be used directly. -/ @[elab_as_eliminator] protected def rec {C : ereal → Sort*} (h_bot : C ⊥) (h_real : Π a : ℝ, C a) (h_top : C ⊤) : ∀ a : ereal, C a | ⊥ := h_bot | (a : ℝ) := h_real a | ⊤ := h_top /-! ### Real coercion -/ instance : can_lift ereal ℝ := { coe := coe, cond := λ r, r ≠ ⊤ ∧ r ≠ ⊥, prf := λ x hx, begin induction x using ereal.rec, { simpa using hx }, { simp }, { simpa using hx } end } /-- The map from extended reals to reals sending infinities to zero. -/ def to_real : ereal → ℝ | ⊥ := 0 | ⊤ := 0 | (x : ℝ) := x @[simp] lemma to_real_top : to_real ⊤ = 0 := rfl @[simp] lemma to_real_bot : to_real ⊥ = 0 := rfl @[simp] lemma to_real_zero : to_real 0 = 0 := rfl @[simp] lemma to_real_coe (x : ℝ) : to_real (x : ereal) = x := rfl @[simp] lemma bot_lt_coe (x : ℝ) : (⊥ : ereal) < x := by { apply with_top.coe_lt_coe.2, exact with_bot.bot_lt_coe _ } @[simp] lemma coe_ne_bot (x : ℝ) : (x : ereal) ≠ ⊥ := (bot_lt_coe x).ne' @[simp] lemma bot_ne_coe (x : ℝ) : (⊥ : ereal) ≠ x := (bot_lt_coe x).ne @[simp] lemma coe_lt_top (x : ℝ) : (x : ereal) < ⊤ := with_top.coe_lt_top _ @[simp] lemma coe_ne_top (x : ℝ) : (x : ereal) ≠ ⊤ := (coe_lt_top x).ne @[simp] lemma top_ne_coe (x : ℝ) : (⊤ : ereal) ≠ x := (coe_lt_top x).ne' @[simp] lemma bot_lt_zero : (⊥ : ereal) < 0 := bot_lt_coe 0 @[simp] lemma bot_ne_zero : (⊥ : ereal) ≠ 0 := (coe_ne_bot 0).symm @[simp] lemma zero_ne_bot : (0 : ereal) ≠ ⊥ := coe_ne_bot 0 @[simp] lemma zero_lt_top : (0 : ereal) < ⊤ := coe_lt_top 0 @[simp] lemma zero_ne_top : (0 : ereal) ≠ ⊤ := coe_ne_top 0 @[simp] lemma top_ne_zero : (⊤ : ereal) ≠ 0 := (coe_ne_top 0).symm @[simp, norm_cast] lemma coe_add (x y : ℝ) : ((x + y : ℝ) : ereal) = (x : ereal) + (y : ereal) := rfl @[simp] lemma coe_zero : ((0 : ℝ) : ereal) = 0 := rfl lemma to_real_le_to_real {x y : ereal} (h : x ≤ y) (hx : x ≠ ⊥) (hy : y ≠ ⊤) : x.to_real ≤ y.to_real := begin lift x to ℝ, lift y to ℝ, { simpa using h }, { simp [hy, ((bot_lt_iff_ne_bot.2 hx).trans_le h).ne'] }, { simp [hx, (h.trans_lt (lt_top_iff_ne_top.2 hy)).ne], }, end lemma coe_to_real {x : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) : (x.to_real : ereal) = x := begin induction x using ereal.rec, { simpa using h'x }, { refl }, { simpa using hx }, end lemma le_coe_to_real {x : ereal} (h : x ≠ ⊤) : x ≤ x.to_real := begin by_cases h' : x = ⊥, { simp only [h', bot_le] }, { simp only [le_refl, coe_to_real h h'] }, end lemma coe_to_real_le {x : ereal} (h : x ≠ ⊥) : ↑x.to_real ≤ x := begin by_cases h' : x = ⊤, { simp only [h', le_top] }, { simp only [le_refl, coe_to_real h' h] }, end lemma eq_top_iff_forall_lt (x : ereal) : x = ⊤ ↔ ∀ (y : ℝ), (y : ereal) < x := begin split, { rintro rfl, exact ereal.coe_lt_top }, { contrapose!, intro h, exact ⟨x.to_real, le_coe_to_real h⟩, }, end lemma eq_bot_iff_forall_lt (x : ereal) : x = ⊥ ↔ ∀ (y : ℝ), x < (y : ereal) := begin split, { rintro rfl, exact bot_lt_coe }, { contrapose!, intro h, exact ⟨x.to_real, coe_to_real_le h⟩, }, end /-! ### ennreal coercion -/ @[simp] lemma to_real_coe_ennreal : ∀ {x : ℝ≥0∞}, to_real (x : ereal) = ennreal.to_real x | ⊤ := rfl | (some x) := rfl lemma coe_nnreal_eq_coe_real (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) = (x : ℝ) := rfl @[simp] lemma coe_ennreal_top : ((⊤ : ℝ≥0∞) : ereal) = ⊤ := rfl @[simp] lemma coe_ennreal_eq_top_iff : ∀ {x : ℝ≥0∞}, (x : ereal) = ⊤ ↔ x = ⊤ | ⊤ := by simp | (some x) := by { simp only [ennreal.coe_ne_top, iff_false, ennreal.some_eq_coe], dec_trivial } lemma coe_nnreal_ne_top (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) ≠ ⊤ := dec_trivial @[simp] lemma coe_nnreal_lt_top (x : ℝ≥0) : ((x : ℝ≥0∞) : ereal) < ⊤ := dec_trivial @[simp, norm_cast] lemma coe_ennreal_le_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) ≤ (y : ereal) ↔ x ≤ y | x ⊤ := by simp | ⊤ (some y) := by simp | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] @[simp, norm_cast] lemma coe_ennreal_lt_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) < (y : ereal) ↔ x < y | ⊤ ⊤ := by simp | (some x) ⊤ := by simp | ⊤ (some y) := by simp | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] @[simp, norm_cast] lemma coe_ennreal_eq_coe_ennreal_iff : ∀ {x y : ℝ≥0∞}, (x : ereal) = (y : ereal) ↔ x = y | ⊤ ⊤ := by simp | (some x) ⊤ := by simp | ⊤ (some y) := by simp [(coe_nnreal_lt_top y).ne'] | (some x) (some y) := by simp [coe_nnreal_eq_coe_real] lemma coe_ennreal_nonneg (x : ℝ≥0∞) : (0 : ereal) ≤ x := coe_ennreal_le_coe_ennreal_iff.2 (zero_le x) @[simp] lemma bot_lt_coe_ennreal (x : ℝ≥0∞) : (⊥ : ereal) < x := (bot_lt_coe 0).trans_le (coe_ennreal_nonneg _) @[simp] lemma coe_ennreal_ne_bot (x : ℝ≥0∞) : (x : ereal) ≠ ⊥ := (bot_lt_coe_ennreal x).ne' @[simp, norm_cast] lemma coe_ennreal_add : ∀ (x y : ennreal), ((x + y : ℝ≥0∞) : ereal) = x + y | ⊤ y := rfl | x ⊤ := by simp | (some x) (some y) := rfl @[simp] lemma coe_ennreal_zero : ((0 : ℝ≥0∞) : ereal) = 0 := rfl /-! ### Order -/ lemma exists_rat_btwn_of_lt : Π {a b : ereal} (hab : a < b), ∃ (x : ℚ), a < (x : ℝ) ∧ ((x : ℝ) : ereal) < b | ⊤ b h := (not_top_lt h).elim | (a : ℝ) ⊥ h := (lt_irrefl _ ((bot_lt_coe a).trans h)).elim | (a : ℝ) (b : ℝ) h := by simp [exists_rat_btwn (ereal.coe_lt_coe_iff.1 h)] | (a : ℝ) ⊤ h := let ⟨b, hab⟩ := exists_rat_gt a in ⟨b, by simpa using hab, coe_lt_top _⟩ | ⊥ ⊥ h := (lt_irrefl _ h).elim | ⊥ (a : ℝ) h := let ⟨b, hab⟩ := exists_rat_lt a in ⟨b, bot_lt_coe _, by simpa using hab⟩ | ⊥ ⊤ h := ⟨0, bot_lt_coe _, coe_lt_top _⟩ lemma lt_iff_exists_rat_btwn {a b : ereal} : a < b ↔ ∃ (x : ℚ), a < (x : ℝ) ∧ ((x : ℝ) : ereal) < b := ⟨λ hab, exists_rat_btwn_of_lt hab, λ ⟨x, ax, xb⟩, ax.trans xb⟩ lemma lt_iff_exists_real_btwn {a b : ereal} : a < b ↔ ∃ (x : ℝ), a < x ∧ (x : ereal) < b := ⟨λ hab, let ⟨x, ax, xb⟩ := exists_rat_btwn_of_lt hab in ⟨(x : ℝ), ax, xb⟩, λ ⟨x, ax, xb⟩, ax.trans xb⟩ /-- The set of numbers in `ereal` that are not equal to `±∞` is equivalent to `ℝ`. -/ def ne_top_bot_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ ℝ := { to_fun := λ x, ereal.to_real x, inv_fun := λ x, ⟨x, by simp⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ begin lift x to ℝ, { simp }, { simpa [not_or_distrib, and_comm] using hx } end, right_inv := λ x, by simp } /-! ### Addition -/ @[simp] lemma add_top (x : ereal) : x + ⊤ = ⊤ := add_top _ @[simp] lemma top_add (x : ereal) : ⊤ + x = ⊤ := top_add _ @[simp] lemma bot_add_bot : (⊥ : ereal) + ⊥ = ⊥ := rfl @[simp] lemma bot_add_coe (x : ℝ) : (⊥ : ereal) + x = ⊥ := rfl @[simp] lemma coe_add_bot (x : ℝ) : (x : ereal) + ⊥ = ⊥ := rfl lemma to_real_add : ∀ {x y : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥), to_real (x + y) = to_real x + to_real y | ⊥ y hx h'x hy h'y := (h'x rfl).elim | ⊤ y hx h'x hy h'y := (hx rfl).elim | x ⊤ hx h'x hy h'y := (hy rfl).elim | x ⊥ hx h'x hy h'y := (h'y rfl).elim | (x : ℝ) (y : ℝ) hx h'x hy h'y := by simp [← ereal.coe_add] lemma add_lt_add_right_coe {x y : ereal} (h : x < y) (z : ℝ) : x + z < y + z := begin induction x using ereal.rec; induction y using ereal.rec, { exact (lt_irrefl _ h).elim }, { simp only [bot_lt_coe, bot_add_coe, ← coe_add] }, { simp }, { exact (lt_irrefl _ (h.trans (bot_lt_coe x))).elim }, { norm_cast at h ⊢, exact add_lt_add_right h _ }, { simp only [← coe_add, top_add, coe_lt_top] }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, { exact (lt_irrefl _ (h.trans_le le_top)).elim }, end lemma add_lt_add_of_lt_of_le {x y z t : ereal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x + z < y + t := begin induction z using ereal.rec, { simpa only using hz }, { calc x + z < y + z : add_lt_add_right_coe h _ ... ≤ y + t : add_le_add le_rfl h' }, { exact (ht (top_le_iff.1 h')).elim } end lemma add_lt_add_left_coe {x y : ereal} (h : x < y) (z : ℝ) : (z : ereal) + x < z + y := by simpa [add_comm] using add_lt_add_right_coe h z lemma add_lt_add {x y z t : ereal} (h1 : x < y) (h2 : z < t) : x + z < y + t := begin induction y using ereal.rec, { exact (lt_irrefl _ (bot_le.trans_lt h1)).elim }, { calc x + z ≤ y + z : add_le_add h1.le le_rfl ... < y + t : add_lt_add_left_coe h2 _ }, { simp [lt_top_iff_ne_top, with_top.add_eq_top, h1.ne, (h2.trans_le le_top).ne] } end @[simp] lemma add_eq_top_iff {x y : ereal} : x + y = ⊤ ↔ x = ⊤ ∨ y = ⊤ := begin induction x using ereal.rec; induction y using ereal.rec; simp [← ereal.coe_add], end @[simp] lemma add_lt_top_iff {x y : ereal} : x + y < ⊤ ↔ x < ⊤ ∧ y < ⊤ := by simp [lt_top_iff_ne_top, not_or_distrib] /-! ### Negation -/ /-- negation on `ereal` -/ protected def neg : ereal → ereal | ⊥ := ⊤ | ⊤ := ⊥ | (x : ℝ) := (-x : ℝ) instance : has_neg ereal := ⟨ereal.neg⟩ @[norm_cast] protected lemma neg_def (x : ℝ) : ((-x : ℝ) : ereal) = -x := rfl @[simp] lemma neg_top : - (⊤ : ereal) = ⊥ := rfl @[simp] lemma neg_bot : - (⊥ : ereal) = ⊤ := rfl @[simp] lemma neg_zero : - (0 : ereal) = 0 := by { change ((-0 : ℝ) : ereal) = 0, simp } /-- `- -a = a` on `ereal`. -/ @[simp] protected theorem neg_neg : ∀ (a : ereal), - (- a) = a | ⊥ := rfl | ⊤ := rfl | (a : ℝ) := by { norm_cast, simp [neg_neg a] } theorem neg_inj {a b : ereal} (h : -a = -b) : a = b := by rw [←ereal.neg_neg a, h, ereal.neg_neg b] @[simp] theorem neg_eq_neg_iff (a b : ereal) : - a = - b ↔ a = b := ⟨λ h, neg_inj h, λ h, by rw [h]⟩ @[simp] lemma to_real_neg : ∀ {a : ereal}, to_real (-a) = - to_real a | ⊤ := by simp | ⊥ := by simp | (x : ℝ) := rfl /-- Even though `ereal` is not an additive group, `-a = b ↔ -b = a` still holds -/ theorem neg_eq_iff_neg_eq {a b : ereal} : -a = b ↔ -b = a := ⟨by {intro h, rw ←h, exact ereal.neg_neg a}, by {intro h, rw ←h, exact ereal.neg_neg b}⟩ @[simp] lemma neg_eg_top_iff {x : ereal} : - x = ⊤ ↔ x = ⊥ := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } @[simp] lemma neg_eg_bot_iff {x : ereal} : - x = ⊥ ↔ x = ⊤ := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } @[simp] lemma neg_eg_zero_iff {x : ereal} : - x = 0 ↔ x = 0 := by { rw neg_eq_iff_neg_eq, simp [eq_comm] } /-- if `-a ≤ b` then `-b ≤ a` on `ereal`. -/ protected theorem neg_le_of_neg_le : ∀ {a b : ereal} (h : -a ≤ b), -b ≤ a | ⊥ ⊥ h := h | ⊥ (some b) h := by cases (top_le_iff.1 h) | ⊤ l h := le_top | (a : ℝ) ⊥ h := by cases (le_bot_iff.1 h) | l ⊤ h := bot_le | (a : ℝ) (b : ℝ) h := by { norm_cast at h ⊢, exact neg_le.mp h } /-- `-a ≤ b ↔ -b ≤ a` on `ereal`. -/ protected theorem neg_le {a b : ereal} : -a ≤ b ↔ -b ≤ a := ⟨ereal.neg_le_of_neg_le, ereal.neg_le_of_neg_le⟩ /-- `a ≤ -b → b ≤ -a` on ereal -/ theorem le_neg_of_le_neg {a b : ereal} (h : a ≤ -b) : b ≤ -a := by rwa [←ereal.neg_neg b, ereal.neg_le, ereal.neg_neg] @[simp] lemma neg_le_neg_iff {a b : ereal} : - a ≤ - b ↔ b ≤ a := by conv_lhs { rw [ereal.neg_le, ereal.neg_neg] } @[simp, norm_cast] lemma coe_neg (x : ℝ) : ((- x : ℝ) : ereal) = - (x : ereal) := rfl /-- Negation as an order reversing isomorphism on `ereal`. -/ def neg_order_iso : ereal ≃o (order_dual ereal) := { to_fun := ereal.neg, inv_fun := ereal.neg, left_inv := ereal.neg_neg, right_inv := ereal.neg_neg, map_rel_iff' := λ x y, neg_le_neg_iff } lemma neg_lt_of_neg_lt {a b : ereal} (h : -a < b) : -b < a := begin apply lt_of_le_of_ne (ereal.neg_le_of_neg_le h.le), assume H, rw [← H, ereal.neg_neg] at h, exact lt_irrefl _ h end lemma neg_lt_iff_neg_lt {a b : ereal} : -a < b ↔ -b < a := ⟨λ h, ereal.neg_lt_of_neg_lt h, λ h, ereal.neg_lt_of_neg_lt h⟩ /-! ### Subtraction -/ /-- Subtraction on `ereal`, defined by `x - y = x + (-y)`. Since addition is badly behaved at some points, so is subtraction. There is no standard algebraic typeclass involving subtraction that is registered on `ereal` because of this bad behavior. -/ protected noncomputable def sub (x y : ereal) : ereal := x + (-y) noncomputable instance : has_sub ereal := ⟨ereal.sub⟩ @[simp] lemma top_sub (x : ereal) : ⊤ - x = ⊤ := top_add x @[simp] lemma sub_bot (x : ereal) : x - ⊥ = ⊤ := add_top x @[simp] lemma bot_sub_top : (⊥ : ereal) - ⊤ = ⊥ := rfl @[simp] lemma bot_sub_coe (x : ℝ) : (⊥ : ereal) - x = ⊥ := rfl @[simp] lemma coe_sub_bot (x : ℝ) : (x : ereal) - ⊤ = ⊥ := rfl @[simp] lemma sub_zero (x : ereal) : x - 0 = x := by { change x + (-0) = x, simp } @[simp] lemma zero_sub (x : ereal) : 0 - x = - x := by { change 0 + (-x) = - x, simp } lemma sub_eq_add_neg (x y : ereal) : x - y = x + -y := rfl lemma sub_le_sub {x y z t : ereal} (h : x ≤ y) (h' : t ≤ z) : x - z ≤ y - t := add_le_add h (neg_le_neg_iff.2 h') lemma sub_lt_sub_of_lt_of_le {x y z t : ereal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x - t < y - z := add_lt_add_of_lt_of_le h (neg_le_neg_iff.2 h') (by simp [ht]) (by simp [hz]) lemma coe_real_ereal_eq_coe_to_nnreal_sub_coe_to_nnreal (x : ℝ) : (x : ereal) = real.to_nnreal x - real.to_nnreal (-x) := begin rcases le_or_lt 0 x with h|h, { have : real.to_nnreal x = ⟨x, h⟩, by { ext, simp [h] }, simp only [real.to_nnreal_of_nonpos (neg_nonpos.mpr h), this, sub_zero, ennreal.coe_zero, coe_ennreal_zero, coe_coe], refl }, { have : (x : ereal) = - (- x : ℝ), by simp, conv_lhs { rw this }, have : real.to_nnreal (-x) = ⟨-x, neg_nonneg.mpr h.le⟩, by { ext, simp [neg_nonneg.mpr h.le], }, simp only [real.to_nnreal_of_nonpos h.le, this, zero_sub, neg_eq_neg_iff, coe_neg, ennreal.coe_zero, coe_ennreal_zero, coe_coe], refl } end lemma to_real_sub {x y : ereal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) : to_real (x - y) = to_real x - to_real y := begin rw [ereal.sub_eq_add_neg, to_real_add hx h'x, to_real_neg], { refl }, { simpa using hy }, { simpa using h'y } end /-! ### Multiplication -/ @[simp] lemma coe_one : ((1 : ℝ) : ereal) = 1 := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ((x * y : ℝ) : ereal) = (x : ereal) * (y : ereal) := eq.trans (with_bot.coe_eq_coe.mpr with_bot.coe_mul) with_top.coe_mul @[simp] lemma mul_top (x : ereal) (h : x ≠ 0) : x * ⊤ = ⊤ := with_top.mul_top h @[simp] lemma top_mul (x : ereal) (h : x ≠ 0) : ⊤ * x = ⊤ := with_top.top_mul h @[simp] lemma bot_mul_bot : (⊥ : ereal) * ⊥ = ⊥ := rfl @[simp] lemma bot_mul_coe (x : ℝ) (h : x ≠ 0) : (⊥ : ereal) * x = ⊥ := with_top.coe_mul.symm.trans $ with_bot.coe_eq_coe.mpr $ with_bot.bot_mul $ function.injective.ne (@option.some.inj _) h @[simp] lemma coe_mul_bot (x : ℝ) (h : x ≠ 0) : (x : ereal) * ⊥ = ⊥ := with_top.coe_mul.symm.trans $ with_bot.coe_eq_coe.mpr $ with_bot.mul_bot $ function.injective.ne (@option.some.inj _) h @[simp] lemma to_real_one : to_real 1 = 1 := rfl lemma to_real_mul : ∀ {x y : ereal}, to_real (x * y) = to_real x * to_real y | ⊤ y := by by_cases hy : y = 0; simp [hy] | x ⊤ := by by_cases hx : x = 0; simp [hx] | (x : ℝ) (y : ℝ) := by simp [← ereal.coe_mul] | ⊥ (y : ℝ) := by by_cases hy : y = 0; simp [hy] | (x : ℝ) ⊥ := by by_cases hx : x = 0; simp [hx] | ⊥ ⊥ := by simp end ereal
44c0ab11270f16d07ee629b92292752a7bc962f5
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/aops/2016-USAMO-Problem_4.lean
4a2f04cc746a52b0ef11546e9c315c725aae7f3e
[]
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
458
lean
import data.real.basic import analysis.special_functions.pow /-- Find all functions <math>f:\mathbb{R}\rightarrow \mathbb{R}</math> such that for all real numbers <math>x</math> and <math>y</math>, <cmath>(f(x)+xy)\cdot f(x-3y)+(f(y)+xy)\cdot f(3x-y)=(f(x+y))^2.</cmath> --/ theorem exo (f: real -> real): (forall x y, (f x + x*y) * f(x - 3*y) + (f y + x * y) * f(3*x - y) = (f(x+y)) ^ 2) -> ((forall x, f x = 0) \/ (forall x, f x = x^2)) := sorry
4eda8d988dee83ee4993a7a954874d32b35e5e30
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Util/Trace.lean
5614cb4f97d6b28fd3f0a0a2154b107a86ae60eb
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
5,744
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Message import Lean.MonadEnv universe u namespace Lean open Std (PersistentArray) structure TraceElem where ref : Syntax msg : MessageData deriving Inhabited structure TraceState where enabled : Bool := true traces : PersistentArray TraceElem := {} deriving Inhabited namespace TraceState private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format := traces.size.foldM (fun i r => do let curr ← (traces.get! i).msg.format pure $ if i > 0 then r ++ sep ++ curr else r ++ curr) Format.nil end TraceState class MonadTrace (m : Type → Type) where modifyTraceState : (TraceState → TraceState) → m Unit getTraceState : m TraceState export MonadTrace (getTraceState modifyTraceState) instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where modifyTraceState := fun f => liftM (modifyTraceState f : m _) getTraceState := liftM (getTraceState : m _) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do let traceState ← getTraceState traceState.traces.forM fun m => do let d ← m.msg.format IO.println d def resetTraceState {m} [MonadTrace m] : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOptionAux (opts : Options) : Name → Bool | n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p) | _ => false def checkTraceOption (opts : Options) (cls : Name) : Bool := if opts.isEmpty then false else checkTraceOptionAux opts (`trace ++ cls) private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do let opts ← getOptions pure $ checkTraceOption opts cls @[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do let s ← getTraceState if !s.enabled then pure false else checkTraceOptionM cls @[inline] def enableTracing (b : Bool) : m Bool := do let s ← getTraceState let oldEnabled := s.enabled modifyTraceState fun s => { s with enabled := b } pure oldEnabled @[inline] def getTraces : m (PersistentArray TraceElem) := do let s ← getTraceState pure s.traces @[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit := modifyTraceState fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState fun _ => s private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit := modifyTraces fun traces => if traces.isEmpty then oldTraces else let d := MessageData.tagged (cls ++ `_traceCtx) (MessageData.node (traces.toArray.map fun elem => elem.msg)) oldTraces.push { ref := ref, msg := d } private def getResetTraces : m (PersistentArray TraceElem) := do let oldTraces ← getTraces modifyTraces fun _ => {} pure oldTraces section variable [MonadRef m] [AddMessageContext m] [MonadOptions m] def addTrace (cls : Name) (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg let msg := addTraceOptions msg modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged (cls ++ `_traceMsg) m!"[{cls}] {msg}" } where addTraceOptions : MessageData → MessageData | MessageData.withContext ctx msg => MessageData.withContext { ctx with opts := ctx.opts.setBool `pp.analyze false } msg | msg => msg @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do if (← isTracingEnabledFor cls) then addTrace cls (msg ()) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do if (← isTracingEnabledFor cls) then let msg ← mkMsg addTrace cls msg @[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do let b ← isTracingEnabledFor cls if !b then let old ← enableTracing false try ctx finally enableTracing old else let ref ← getRef let oldCurrTraces ← getResetTraces try ctx finally addNode oldCurrTraces cls ref -- TODO: delete after fix old frontend def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit := Lean.trace cls msg end def registerTraceClass (traceClassName : Name) : IO Unit := registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" } macro "trace[" id:ident "]" s:(interpolatedStr(term) <|> term) : doElem => do let msg ← if s.getKind == interpolatedStrKind then `(m! $s) else `(($s : MessageData)) `(doElem| do let cls := $(quote id.getId.eraseMacroScopes) if (← Lean.isTracingEnabledFor cls) then Lean.addTrace cls $msg) private def withNestedTracesFinalizer [Monad m] [MonadTrace m] (ref : Syntax) (currTraces : PersistentArray TraceElem) : m Unit := do modifyTraces fun traces => if traces.size == 0 then currTraces else if traces.size == 1 && traces[0].msg.isNest then currTraces ++ traces -- No nest of nest else let d := traces.foldl (init := MessageData.nil) fun d elem => if d.isNil then elem.msg else m!"{d}\n{elem.msg}" currTraces.push { ref := ref, msg := MessageData.nestD d } @[inline] def withNestedTraces [Monad m] [MonadFinally m] [MonadTrace m] [MonadRef m] (x : m α) : m α := do let currTraces ← getTraces modifyTraces fun _ => {} let ref ← getRef try x finally withNestedTracesFinalizer ref currTraces end Lean
04d0acc1081809dfb5c6877ab572b85a771ae334
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/analysis/special_functions/exp_log.lean
ad4f56c6f53833f66c9ea5d858f6498495d519f1
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
22,051
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import data.complex.exponential import analysis.complex.basic import analysis.calculus.mean_value /-! # Complex and real exponential, real logarithm ## Main statements This file establishes the basic analytical properties of the complex and real exponential functions (continuity, differentiability, computation of the derivative). It also contains the definition of the real logarithm function (as the inverse of the exponential on `(0, +∞)`, extended to `ℝ` by setting `log (-x) = log x`) and its basic properties (continuity, differentiability, formula for the derivative). The complex logarithm is *not* defined in this file as it relies on trigonometric functions. See instead `trigonometric.lean`. ## Tags exp, log -/ noncomputable theory open finset filter metric asymptotics open_locale classical topological_space namespace complex /-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/ lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x := begin rw has_deriv_at_iff_is_o_nhds_zero, have : (1 : ℕ) < 2 := by norm_num, refine (is_O.of_bound (∥exp x∥) _).trans_is_o (is_o_pow_id this), have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one, apply filter.mem_sets_of_superset this (λz hz, _), simp only [metric.mem_ball, dist_zero_right] at hz, simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow, zero_add, set.mem_set_of_eq], calc ∥exp (x + z) - exp x - z * exp x∥ = ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring } ... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _ ... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _) end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at lemma differentiable_at_exp {x : ℂ} : differentiable_at ℂ exp x := differentiable_exp x @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end complex section variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} lemma has_deriv_at.cexp (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') x := (complex.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.cexp (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.exp (f x)) (complex.exp (f x) * f') s x := (complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.cexp (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.exp (f x)) s x := hf.has_deriv_within_at.cexp.differentiable_within_at @[simp] lemma differentiable_at.cexp (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.exp (f x)) x := hc.has_deriv_at.cexp.differentiable_at lemma differentiable_on.cexp (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.exp (f x)) s := λx h, (hc x h).cexp @[simp] lemma differentiable.cexp (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.exp (f x)) := λx, (hc x).cexp lemma deriv_within_cexp (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.exp (f x)) s x = complex.exp (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cexp.deriv_within hxs @[simp] lemma deriv_cexp (hc : differentiable_at ℂ f x) : deriv (λx, complex.exp (f x)) x = complex.exp (f x) * (deriv f x) := hc.has_deriv_at.cexp.deriv end namespace real variables {x y z : ℝ} lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_exp x) lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at lemma differentiable_at_exp : differentiable_at ℝ exp x := differentiable_exp x @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [function.iterate_succ_apply, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end real section /-! Register lemmas for the derivatives of the composition of `real.exp`, `real.cos`, `real.sin`, `real.cosh` and `real.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! `real.exp`-/ lemma has_deriv_at.exp (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.exp (f x)) (real.exp (f x) * f') x := (real.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.exp (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.exp (f x)) (real.exp (f x) * f') s x := (real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.exp (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.exp (f x)) s x := hf.has_deriv_within_at.exp.differentiable_within_at @[simp] lemma differentiable_at.exp (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.exp (f x)) x := hc.has_deriv_at.exp.differentiable_at lemma differentiable_on.exp (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.exp (f x)) s := λx h, (hc x h).exp @[simp] lemma differentiable.exp (hc : differentiable ℝ f) : differentiable ℝ (λx, real.exp (f x)) := λx, (hc x).exp lemma deriv_within_exp (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.exp (f x)) s x = real.exp (f x) * (deriv_within f s x) := hf.has_deriv_within_at.exp.deriv_within hxs @[simp] lemma deriv_exp (hc : differentiable_at ℝ f x) : deriv (λx, real.exp (f x)) x = real.exp (f x) * (deriv f x) := hc.has_deriv_at.exp.deriv end namespace real variables {x y z : ℝ} lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp, from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp ⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩, match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := this hx1 end /-- The real logarithm function, equal to the inverse of the exponential for `x > 0`, to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to `(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and the derivative of `log` is `1/x` away from `0`. -/ noncomputable def log (x : ℝ) : ℝ := if hx : x ≠ 0 then classical.some (exists_exp_eq_of_pos (abs_pos_iff.mpr hx)) else 0 lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = abs x := by { rw [log, dif_pos hx], exact classical.some_spec (exists_exp_eq_of_pos ((abs_pos_iff.mpr hx))) } lemma exp_log (hx : 0 < x) : exp (log x) = x := by { rw exp_log_eq_abs (ne_of_gt hx), exact abs_of_pos hx } lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x := by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx } @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] @[simp] lemma log_abs (x : ℝ) : log (abs x) = log x := begin by_cases h : x = 0, { simp [h] }, { apply exp_injective, rw [exp_log_eq_abs h, exp_log_eq_abs, abs_abs], simp [h] } end @[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x := by rw [← log_abs x, ← log_abs (-x), abs_neg] lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul] @[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x := begin by_cases hx : x = 0, { simp [hx] }, apply eq_neg_of_add_eq_zero, rw [← log_mul (inv_ne_zero hx) hx, inv_mul_cancel hx, log_one] end lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x := by { rw ← log_one, exact log_lt_log_iff (by norm_num) hx } lemma log_pos (hx : 1 < x) : 0 < log x := (log_pos_iff (lt_trans zero_lt_one hx)).2 hx lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 := begin by_cases x_zero : x = 0, { simp [x_zero] }, { rwa [← log_one, log_le_log (lt_of_le_of_ne hx (ne.symm x_zero))], norm_num } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos (le_of_lt this) hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos.2 x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul (ne_of_gt x.2) (ne_of_gt h.2), simp only [this, log_mul (ne_of_gt x.2) one_ne_zero, log_one], exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_coe), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos.2 x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_coe, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` are provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma has_deriv_at_log_of_pos (hx : 0 < x) : has_deriv_at log x⁻¹ x := have has_deriv_at log (exp $ log x)⁻¹ x, from (has_deriv_at_exp $ log x).of_local_left_inverse (continuous_at_log hx) (ne_of_gt $ exp_pos _) $ eventually.mono (mem_nhds_sets is_open_Ioi hx) @exp_log, by rwa [exp_log hx] at this lemma has_deriv_at_log (hx : x ≠ 0) : has_deriv_at log x⁻¹ x := begin by_cases h : 0 < x, { exact has_deriv_at_log_of_pos h }, push_neg at h, convert ((has_deriv_at_log_of_pos (neg_pos.mpr (lt_of_le_of_ne h hx))) .comp x (has_deriv_at_id x).neg), { ext y, exact (log_neg_eq_log y).symm }, { field_simp [hx] } end end real section log_differentiable open real variables {f : ℝ → ℝ} {x f' : ℝ} {s : set ℝ} lemma has_deriv_within_at.log (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, log (f y)) (f' / (f x)) s x := begin convert (has_deriv_at_log hx).comp_has_deriv_within_at x hf, field_simp end lemma has_deriv_at.log (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, log (f y)) (f' / f x) x := begin rw ← has_deriv_within_at_univ at *, exact hf.log hx end lemma differentiable_within_at.log (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λx, log (f x)) s x := (hf.has_deriv_within_at.log hx).differentiable_within_at @[simp] lemma differentiable_at.log (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λx, log (f x)) x := (hf.has_deriv_at.log hx).differentiable_at lemma differentiable_on.log (hf : differentiable_on ℝ f s) (hx : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λx, log (f x)) s := λx h, (hf x h).log (hx x h) @[simp] lemma differentiable.log (hf : differentiable ℝ f) (hx : ∀ x, f x ≠ 0) : differentiable ℝ (λx, log (f x)) := λx, (hf x).log (hx x) lemma deriv_within_log' (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, log (f x)) s x = (deriv_within f s x) / (f x) := (hf.has_deriv_within_at.log hx).deriv_within hxs @[simp] lemma deriv_log' (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, log (f x)) x = (deriv f x) / (f x) := (hf.has_deriv_at.log hx).deriv end log_differentiable namespace real /-- The real exponential function tends to `+∞` at `+∞`. -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x, { have : ∀ᶠ (x : ℝ) in at_top, 0 ≤ x := mem_at_top 0, filter_upwards [this], exact λx hx, add_one_le_exp_of_nonneg hx }, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0` at +infinity -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm) /-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n, have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos, have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n, { assume x hx, let y := x / (n+1), have y_pos : 0 < y := div_pos hx n_pos, have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc exp y = exp y * 1 : by simp ... ≤ exp y * (exp y / y)^n : begin apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)), apply one_le_div_of_le _ y_pos, apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)), exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one) end ... = exp y * exp (n * y) / y^n : by rw [div_pow, exp_nat_mul, mul_div_assoc] ... = exp ((n + 1) * y) / y^n : by rw [← exp_add, add_mul, one_mul, add_comm] ... = exp x / (x / (n+1))^n : by { dsimp [y], rw mul_div_cancel' _ n_ne_zero } ... = (n+1)^n * (exp x / x^n) : by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm], rwa div_le_iff' (pow_pos n_pos n) }, have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n := mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩, have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top := tendsto_at_top_div (pow_pos n_pos n) (tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)), exact tendsto_at_top_mono' at_top B C end /-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] open_locale big_operators /-- A crude lemma estimating the difference between `log (1-x)` and its Taylor series at `0`, where the main point of the bound is that it tends to `0`. The goal is to deduce the series expansion of the logarithm, in `has_sum_pow_div_log_of_abs_lt_1`. -/ lemma abs_log_sub_add_sum_range_le {x : ℝ} (h : abs x < 1) (n : ℕ) : abs ((∑ i in range n, x^(i+1)/(i+1)) + log (1-x)) ≤ (abs x)^(n+1) / (1 - abs x) := begin /- For the proof, we show that the derivative of the function to be estimated is small, and then apply the mean value inequality. -/ let F : ℝ → ℝ := λ x, ∑ i in range n, x^(i+1)/(i+1) + log (1-x), -- First step: compute the derivative of `F` have A : ∀ y ∈ set.Ioo (-1 : ℝ) 1, deriv F y = - (y^n) / (1 - y), { assume y hy, have : (∑ i in range n, (↑i + 1) * y ^ i / (↑i + 1)) = (∑ i in range n, y ^ i), { congr, ext i, have : (i : ℝ) + 1 ≠ 0 := ne_of_gt (nat.cast_add_one_pos i), field_simp [this, mul_comm] }, field_simp [F, this, ← geom_series_def, geom_sum (ne_of_lt hy.2), sub_ne_zero_of_ne (ne_of_gt hy.2), sub_ne_zero_of_ne (ne_of_lt hy.2)], ring }, -- second step: show that the derivative of `F` is small have B : ∀ y ∈ set.Icc (-abs x) (abs x), abs (deriv F y) ≤ (abs x)^n / (1 - abs x), { assume y hy, have : y ∈ set.Ioo (-(1 : ℝ)) 1 := ⟨lt_of_lt_of_le (neg_lt_neg h) hy.1, lt_of_le_of_lt hy.2 h⟩, calc abs (deriv F y) = abs (-(y^n) / (1 - y)) : by rw [A y this] ... ≤ (abs x)^n / (1 - abs x) : begin have : abs y ≤ abs x := abs_le_of_le_of_neg_le hy.2 (by linarith [hy.1]), have : 0 < 1 - abs x, by linarith, have : 1 - abs x ≤ abs (1 - y) := le_trans (by linarith [hy.2]) (le_abs_self _), simp only [← pow_abs, abs_div, abs_neg], apply_rules [div_le_div, pow_nonneg, abs_nonneg, pow_le_pow_of_le_left] end }, -- third step: apply the mean value inequality have C : ∥F x - F 0∥ ≤ ((abs x)^n / (1 - abs x)) * ∥x - 0∥, { have : ∀ y ∈ set.Icc (- abs x) (abs x), differentiable_at ℝ F y, { assume y hy, have : 1 - y ≠ 0 := sub_ne_zero_of_ne (ne_of_gt (lt_of_le_of_lt hy.2 h)), simp [F, this] }, apply convex.norm_image_sub_le_of_norm_deriv_le this B (convex_Icc _ _) _ _, { simpa using abs_nonneg x }, { simp [le_abs_self x, neg_le.mp (neg_le_abs_self x)] } }, -- fourth step: conclude by massaging the inequality of the third step simpa [F, norm_eq_abs, div_mul_eq_mul_div, pow_succ'] using C end /-- Power series expansion of the logarithm around `1`. -/ theorem has_sum_pow_div_log_of_abs_lt_1 {x : ℝ} (h : abs x < 1) : has_sum (λ (n : ℕ), x ^ (n + 1) / (n + 1)) (-log (1 - x)) := begin rw has_sum_iff_tendsto_nat_of_summable, show tendsto (λ (n : ℕ), ∑ (i : ℕ) in range n, x ^ (i + 1) / (i + 1)) at_top (𝓝 (-log (1 - x))), { rw [tendsto_iff_norm_tendsto_zero], simp only [norm_eq_abs, sub_neg_eq_add], refine squeeze_zero (λ n, abs_nonneg _) (abs_log_sub_add_sum_range_le h) _, suffices : tendsto (λ (t : ℕ), abs x ^ (t + 1) / (1 - abs x)) at_top (𝓝 (abs x * 0 / (1 - abs x))), by simpa, simp only [pow_succ], refine (tendsto_const_nhds.mul _).div_const, exact tendsto_pow_at_top_nhds_0_of_lt_1 (abs_nonneg _) h }, show summable (λ (n : ℕ), x ^ (n + 1) / (n + 1)), { refine summable_of_norm_bounded _ (summable_geometric_of_lt_1 (abs_nonneg _) h) (λ i, _), calc ∥x ^ (i + 1) / (i + 1)∥ = abs x ^ (i+1) / (i+1) : begin have : (0 : ℝ) ≤ i + 1 := le_of_lt (nat.cast_add_one_pos i), rw [norm_eq_abs, abs_div, ← pow_abs, abs_of_nonneg this], end ... ≤ abs x ^ (i+1) / (0 + 1) : begin apply_rules [div_le_div_of_le_left, pow_nonneg, abs_nonneg, add_le_add_right (nat.cast_nonneg i)], norm_num, end ... ≤ abs x ^ i : by simpa [pow_succ'] using mul_le_of_le_one_right (pow_nonneg (abs_nonneg x) i) (le_of_lt h) } end end real
66344dc5fb886c27af698b68a6816673349b1325
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/module/linear_map.lean
bb01d91d493d26193ff6cd40b3d235509c31c184
[ "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
14,630
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 /-! # 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₂ := (map_smul' : ∀ (c : R) x, to_fun (c • x) = c • to_fun x) end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_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₂] 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⟩ variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : (f.to_add_monoid_hom : M → M₂) = f := rfl @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : 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] 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 } 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 /-- Ring of linear endomorphismsms of a module. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- 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 ` ≃ₗ `:25 := 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 mk_apply {to_fun inv_fun map_add map_smul left_inv right_inv a} : (⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) a = to_fun a := rfl -- 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₂) @[simp, norm_cast] theorem coe_coe : ((e : M →ₗ[R] M₂) : M → M₂) = (e : M → M₂) := rfl @[simp] lemma coe_to_equiv : (e.to_equiv : M → M₂) = (e : M → M₂) := rfl @[simp] lemma to_fun_apply {m : M} : e.to_fun m = e m := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := injective_to_equiv (equiv.ext h) end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- 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_apply {m : M₂} : e.inv_fun m = e.symm m := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[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] 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 } 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 end add_comm_monoid end linear_equiv
04820952ef4073b969afdc893c3d49e3ccede9db
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/denoms_clearable.lean
efeba61915ab6332d92668ebd285a0b6ecea7618
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,701
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.erase_lead import data.polynomial.eval /-! # Denominators of evaluation of polynomials at ratios Let `i : R → K` be a homomorphism of semirings. Assume that `K` is commutative. If `a` and `b` are elements of `R` such that `i b ∈ K` is invertible, then for any polynomial `f ∈ polynomial R` the "mathematical" expression `b ^ f.nat_degree * f (a / b) ∈ K` is in the image of the homomorphism `i`. -/ open polynomial finset section denoms_clearable variables {R K : Type*} [semiring R] [comm_semiring K] {i : R →+* K} variables {a b : R} {bi : K} -- TODO: use hypothesis (ub : is_unit (i b)) to work with localizations. /-- `denoms_clearable` formalizes the property that `b ^ N * f (a / b)` does not have denominators, if the inequality `f.nat_degree ≤ N` holds. The definition asserts the existence of an element `D` of `R` and an element `bi = 1 / i b` of `K` such that clearing the denominators of the fraction equals `i D`. -/ def denoms_clearable (a b : R) (N : ℕ) (f : polynomial R) (i : R →+* K) : Prop := ∃ (D : R) (bi : K), bi * i b = 1 ∧ i D = i b ^ N * eval (i a * bi) (f.map i) lemma denoms_clearable_zero (N : ℕ) (a : R) (bu : bi * i b = 1) : denoms_clearable a b N 0 i := ⟨0, bi, bu, by simp only [eval_zero, ring_hom.map_zero, mul_zero, polynomial.map_zero]⟩ lemma denoms_clearable_C_mul_X_pow {N : ℕ} (a : R) (bu : bi * i b = 1) {n : ℕ} (r : R) (nN : n ≤ N) : denoms_clearable a b N (C r * X ^ n) i := begin refine ⟨r * a ^ n * b ^ (N - n), bi, bu, _⟩, rw [C_mul_X_pow_eq_monomial, map_monomial, ← C_mul_X_pow_eq_monomial, eval_mul, eval_pow, eval_C], rw [ring_hom.map_mul, ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_pow, eval_X, mul_comm], rw [← tsub_add_cancel_of_le nN] {occs := occurrences.pos [2]}, rw [pow_add, mul_assoc, mul_comm (i b ^ n), mul_pow, mul_assoc, mul_assoc (i a ^ n), ← mul_pow], rw [bu, one_pow, mul_one], end lemma denoms_clearable.add {N : ℕ} {f g : polynomial R} : denoms_clearable a b N f i → denoms_clearable a b N g i → denoms_clearable a b N (f + g) i := λ ⟨Df, bf, bfu, Hf⟩ ⟨Dg, bg, bgu, Hg⟩, ⟨Df + Dg, bf, bfu, begin rw [ring_hom.map_add, polynomial.map_add, eval_add, mul_add, Hf, Hg], congr, refine @inv_unique K _ (i b) bg bf _ _; rwa mul_comm, end ⟩ lemma denoms_clearable_of_nat_degree_le (N : ℕ) (a : R) (bu : bi * i b = 1) : ∀ (f : polynomial R), f.nat_degree ≤ N → denoms_clearable a b N f i := induction_with_nat_degree_le _ N (denoms_clearable_zero N a bu) (λ N_1 r r0, denoms_clearable_C_mul_X_pow a bu r) (λ f g fg gN df dg, df.add dg) /-- If `i : R → K` is a ring homomorphism, `f` is a polynomial with coefficients in `R`, `a, b` are elements of `R`, with `i b` invertible, then there is a `D ∈ R` such that `b ^ f.nat_degree * f (a / b)` equals `i D`. -/ theorem denoms_clearable_nat_degree (i : R →+* K) (f : polynomial R) (a : R) (bu : bi * i b = 1) : denoms_clearable a b f.nat_degree f i := denoms_clearable_of_nat_degree_le f.nat_degree a bu f le_rfl end denoms_clearable open ring_hom /-- Evaluating a polynomial with integer coefficients at a rational number and clearing denominators, yields a number greater than or equal to one. The target can be any `linear_ordered_field K`. The assumption on `K` could be weakened to `linear_ordered_comm_ring` assuming that the image of the denominator is invertible in `K`. -/ lemma one_le_pow_mul_abs_eval_div {K : Type*} [linear_ordered_field K] {f : polynomial ℤ} {a b : ℤ} (b0 : 0 < b) (fab : eval ((a : K) / b) (f.map (algebra_map ℤ K)) ≠ 0) : (1 : K) ≤ b ^ f.nat_degree * |eval ((a : K) / b) (f.map (algebra_map ℤ K))| := begin obtain ⟨ev, bi, bu, hF⟩ := @denoms_clearable_nat_degree _ _ _ _ b _ (algebra_map ℤ K) f a (by { rw [eq_int_cast, one_div_mul_cancel], rw [int.cast_ne_zero], exact (b0.ne.symm) }), obtain Fa := congr_arg abs hF, rw [eq_one_div_of_mul_eq_one_left bu, eq_int_cast, eq_int_cast, abs_mul] at Fa, rw [abs_of_pos (pow_pos (int.cast_pos.mpr b0) _ : 0 < (b : K) ^ _), one_div, eq_int_cast] at Fa, rw [div_eq_mul_inv, ← Fa, ← int.cast_abs, ← int.cast_one, int.cast_le], refine int.le_of_lt_add_one ((lt_add_iff_pos_left 1).mpr (abs_pos.mpr (λ F0, fab _))), rw [eq_one_div_of_mul_eq_one_left bu, F0, one_div, eq_int_cast, int.cast_zero, zero_eq_mul] at hF, cases hF with hF hF, { exact (not_le.mpr b0 (le_of_eq (int.cast_eq_zero.mp (pow_eq_zero hF)))).elim }, { rwa div_eq_mul_inv } end
63b8fc700320e2aab4dba4801e561d2a77b2b843
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/complex/exponential.lean
be8d429f04724c049ba9abc65d61bb1651cb373f
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
61,457
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.nat.choose.sum import data.complex.basic /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := _root_.abs open is_absolute_value open_locale classical big_operators nat section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l •ℕ ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) •ℕ ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l •ℕ ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - (nat.pred l) •ℕ ε : hi.2 ... = a - l •ℕ ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, simp only [nat.succ_add, sum_range_succ, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, simp only [sub_eq_add_neg] at hi, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) end no_archimedean section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv] {eta := ff}, have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) = λ m, geom_series (abv x) m := rfl, simp only [this, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := by rw [sum_sigma', sum_sigma']; exact sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k = ∑ k in (range m).filter (λ k, n ≤ k), f k := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = abs (∑ n in range (max N M + 1), abv (a n)) : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, ∑ m in range n, abs (z ^ m / m!)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw conj.map_sum, refine sum_congr rfl (λ n hn, _), rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0, conj.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div, conj_bit0, conj.map_one] end @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, pow_two, pow_two] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_square], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_square], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma tanh_mul_I : tanh (x * I) = tan x * I := by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan] lemma cos_mul_I : cos (x * I) = cosh x := by rw ← cosh_mul_I; ring; simp lemma sin_mul_I : sin (x * I) = sinh x * I := have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring, simp }, by simpa only [neg_mul_eq_neg_mul_symm, div_I, neg_neg] using cancel_factors.cancel_factors_eq_div h I_ne_zero lemma tan_mul_I : tan (x * I) = tanh x * I := by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I := by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc] lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I := by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I := by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc] lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I := by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj, mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I, cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← pow_two, ← pow_two] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div] lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel] lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx, by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] } lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, pow_two], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_square'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_square'], ring end lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] } lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] } /-- De Moivre's formula -/ theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end lemma tan_eq_sin_div_cos : tan x = sin x / cos x := by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos] lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simp @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (pow_two_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (pow_two_nonneg _) lemma abs_sin_le_one : abs' (sin x) ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, sin_sq_le_one] lemma abs_cos_le_one : abs' (cos x) ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← pow_two, cos_sq_le_one] lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw ← of_real_inj; simp [cos_two_mul'] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_square x lemma cos_square' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have complex.cos x ≠ 0, from mt (congr_arg re) hx, of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (sqrt (1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sqr hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp [cosh_add_sinh] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw ← of_real_inj; simp [sinh_add_cosh] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq] lemma cosh_square : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_square] lemma sinh_square : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_square] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _), rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_pos (exp_pos _) lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) @[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone @[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt @[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := by rw [← exp_zero, exp_injective.eq_iff] @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ * (n! * n)⁻¹ := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [← geom_series_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev', h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw ← sub_eq_add_neg, show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.factorial_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (pow_two_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : abs' x ≤ 1) {n : ℕ} (hn : 0 < n) : abs' (exp x - ∑ m in range n, x ^ m / m!) ≤ abs' x ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv, mul_inv']; ac_refl theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : abs' x ≤ 1) : abs' (exp x - exp_near m x 0) ≤ abs' x ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : abs' (1 + x / m * a₂ - a₁) ≤ b₁ - abs' x / m * b₂) (h : abs' (exp x - exp_near m x a₂) ≤ abs' x ^ m / m! * b₂) : abs' (exp x - exp_near n x a₁) ≤ abs' x ^ n / n! * b₁ := begin refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv'], ac_refl }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs' x ≤ 1) (e : abs' (1 - a) ≤ b - abs' x / rm * ((rm+1)/rm)) : abs' (exp x - exp_near n x a) ≤ abs' x ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : abs' (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs' 1 ^ m / m! * (b₁ * rm)) : abs' (exp 1 - exp_near n 1 a₁) ≤ abs' 1 ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : abs' (exp x - exp_near 0 x a) ≤ abs' x ^ 0 / 0! * b) : abs' (exp x - a) ≤ b := by simpa using h lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
00fadb069c80fb3dc6c32168512d5e18498cdc2d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/graded_algebra/homogeneous_localization.lean
714d3f8767d65f24d61a5d0ced9eb95598f9de12
[ "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
20,916
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Eric Wieser -/ import ring_theory.localization.at_prime import ring_theory.graded_algebra.basic /-! # Homogeneous Localization ## Notation - `ι` is a commutative monoid; - `R` is a commutative semiring; - `A` is a commutative ring and an `R`-algebra; - `𝒜 : ι → submodule R A` is the grading of `A`; - `x : submonoid A` is a submonoid ## Main definitions and results This file constructs the subring of `Aₓ` where the numerator and denominator have the same grading, i.e. `{a/b ∈ Aₓ | ∃ (i : ι), a ∈ 𝒜ᵢ ∧ b ∈ 𝒜ᵢ}`. * `homogeneous_localization.num_denom_same_deg`: a structure with a numerator and denominator field where they are required to have the same grading. However `num_denom_same_deg 𝒜 x` cannot have a ring structure for many reasons, for example if `c` is a `num_denom_same_deg`, then generally, `c + (-c)` is not necessarily `0` for degree reasons --- `0` is considered to have grade zero (see `deg_zero`) but `c + (-c)` has the same degree as `c`. To circumvent this, we quotient `num_denom_same_deg 𝒜 x` by the kernel of `c ↦ c.num / c.denom`. * `homogeneous_localization.num_denom_same_deg.embedding` : for `x : submonoid A` and any `c : num_denom_same_deg 𝒜 x`, or equivalent a numerator and a denominator of the same degree, we get an element `c.num / c.denom` of `Aₓ`. * `homogeneous_localization`: `num_denom_same_deg 𝒜 x` quotiented by kernel of `embedding 𝒜 x`. * `homogeneous_localization.val`: if `f : homogeneous_localization 𝒜 x`, then `f.val` is an element of `Aₓ`. In another word, one can view `homogeneous_localization 𝒜 x` as a subring of `Aₓ` through `homogeneous_localization.val`. * `homogeneous_localization.num`: if `f : homogeneous_localization 𝒜 x`, then `f.num : A` is the numerator of `f`. * `homogeneous_localization.denom`: if `f : homogeneous_localization 𝒜 x`, then `f.denom : A` is the denominator of `f`. * `homogeneous_localization.deg`: if `f : homogeneous_localization 𝒜 x`, then `f.deg : ι` is the degree of `f` such that `f.num ∈ 𝒜 f.deg` and `f.denom ∈ 𝒜 f.deg` (see `homogeneous_localization.num_mem_deg` and `homogeneous_localization.denom_mem_deg`). * `homogeneous_localization.num_mem_deg`: if `f : homogeneous_localization 𝒜 x`, then `f.num_mem_deg` is a proof that `f.num ∈ 𝒜 f.deg`. * `homogeneous_localization.denom_mem_deg`: if `f : homogeneous_localization 𝒜 x`, then `f.denom_mem_deg` is a proof that `f.denom ∈ 𝒜 f.deg`. * `homogeneous_localization.eq_num_div_denom`: if `f : homogeneous_localization 𝒜 x`, then `f.val : Aₓ` is equal to `f.num / f.denom`. * `homogeneous_localization.local_ring`: `homogeneous_localization 𝒜 x` is a local ring when `x` is the complement of some prime ideals. ## References * [Robin Hartshorne, *Algebraic Geometry*][Har77] -/ noncomputable theory open_locale direct_sum big_operators pointwise open direct_sum set_like variables {ι R A: Type*} variables [add_comm_monoid ι] [decidable_eq ι] variables [comm_ring R] [comm_ring A] [algebra R A] variables (𝒜 : ι → submodule R A) [graded_algebra 𝒜] variables (x : submonoid A) local notation `at ` x := localization x namespace homogeneous_localization section /-- Let `x` be a submonoid of `A`, then `num_denom_same_deg 𝒜 x` is a structure with a numerator and a denominator with same grading such that the denominator is contained in `x`. -/ @[nolint has_nonempty_instance] structure num_denom_same_deg := (deg : ι) (num denom : 𝒜 deg) (denom_mem : (denom : A) ∈ x) end namespace num_denom_same_deg open set_like.graded_monoid submodule variable {𝒜} @[ext] lemma ext {c1 c2 : num_denom_same_deg 𝒜 x} (hdeg : c1.deg = c2.deg) (hnum : (c1.num : A) = c2.num) (hdenom : (c1.denom : A) = c2.denom) : c1 = c2 := begin rcases c1 with ⟨i1, ⟨n1, hn1⟩, ⟨d1, hd1⟩, h1⟩, rcases c2 with ⟨i2, ⟨n2, hn2⟩, ⟨d2, hd2⟩, h2⟩, dsimp only [subtype.coe_mk] at *, simp only, exact ⟨hdeg, by subst hdeg; subst hnum, by subst hdeg; subst hdenom⟩, end instance : has_one (num_denom_same_deg 𝒜 x) := { one := { deg := 0, num := ⟨1, one_mem⟩, denom := ⟨1, one_mem⟩, denom_mem := submonoid.one_mem _ } } @[simp] lemma deg_one : (1 : num_denom_same_deg 𝒜 x).deg = 0 := rfl @[simp] lemma num_one : ((1 : num_denom_same_deg 𝒜 x).num : A) = 1 := rfl @[simp] lemma denom_one : ((1 : num_denom_same_deg 𝒜 x).denom : A) = 1 := rfl instance : has_zero (num_denom_same_deg 𝒜 x) := { zero := ⟨0, 0, ⟨1, one_mem⟩, submonoid.one_mem _⟩ } @[simp] lemma deg_zero : (0 : num_denom_same_deg 𝒜 x).deg = 0 := rfl @[simp] lemma num_zero : (0 : num_denom_same_deg 𝒜 x).num = 0 := rfl @[simp] lemma denom_zero : ((0 : num_denom_same_deg 𝒜 x).denom : A) = 1 := rfl instance : has_mul (num_denom_same_deg 𝒜 x) := { mul := λ p q, { deg := p.deg + q.deg, num := ⟨p.num * q.num, mul_mem p.num.prop q.num.prop⟩, denom := ⟨p.denom * q.denom, mul_mem p.denom.prop q.denom.prop⟩, denom_mem := submonoid.mul_mem _ p.denom_mem q.denom_mem } } @[simp] lemma deg_mul (c1 c2 : num_denom_same_deg 𝒜 x) : (c1 * c2).deg = c1.deg + c2.deg := rfl @[simp] lemma num_mul (c1 c2 : num_denom_same_deg 𝒜 x) : ((c1 * c2).num : A) = c1.num * c2.num := rfl @[simp] lemma denom_mul (c1 c2 : num_denom_same_deg 𝒜 x) : ((c1 * c2).denom : A) = c1.denom * c2.denom := rfl instance : has_add (num_denom_same_deg 𝒜 x) := { add := λ c1 c2, { deg := c1.deg + c2.deg, num := ⟨c1.denom * c2.num + c2.denom * c1.num, add_mem (mul_mem c1.denom.2 c2.num.2) (add_comm c2.deg c1.deg ▸ mul_mem c2.denom.2 c1.num.2)⟩, denom := ⟨c1.denom * c2.denom, mul_mem c1.denom.2 c2.denom.2⟩, denom_mem := submonoid.mul_mem _ c1.denom_mem c2.denom_mem } } @[simp] lemma deg_add (c1 c2 : num_denom_same_deg 𝒜 x) : (c1 + c2).deg = c1.deg + c2.deg := rfl @[simp] lemma num_add (c1 c2 : num_denom_same_deg 𝒜 x) : ((c1 + c2).num : A) = c1.denom * c2.num + c2.denom * c1.num := rfl @[simp] lemma denom_add (c1 c2 : num_denom_same_deg 𝒜 x) : ((c1 + c2).denom : A) = c1.denom * c2.denom := rfl instance : has_neg (num_denom_same_deg 𝒜 x) := { neg := λ c, ⟨c.deg, ⟨-c.num, neg_mem c.num.2⟩, c.denom, c.denom_mem⟩ } @[simp] lemma deg_neg (c : num_denom_same_deg 𝒜 x) : (-c).deg = c.deg := rfl @[simp] lemma num_neg (c : num_denom_same_deg 𝒜 x) : ((-c).num : A) = -c.num := rfl @[simp] lemma denom_neg (c : num_denom_same_deg 𝒜 x) : ((-c).denom : A) = c.denom := rfl instance : comm_monoid (num_denom_same_deg 𝒜 x) := { one := 1, mul := (*), mul_assoc := λ c1 c2 c3, ext _ (add_assoc _ _ _) (mul_assoc _ _ _) (mul_assoc _ _ _), one_mul := λ c, ext _ (zero_add _) (one_mul _) (one_mul _), mul_one := λ c, ext _ (add_zero _) (mul_one _) (mul_one _), mul_comm := λ c1 c2, ext _ (add_comm _ _) (mul_comm _ _) (mul_comm _ _) } instance : has_pow (num_denom_same_deg 𝒜 x) ℕ := { pow := λ c n, ⟨n • c.deg, @graded_monoid.gmonoid.gnpow _ (λ i, ↥(𝒜 i)) _ _ n _ c.num, @graded_monoid.gmonoid.gnpow _ (λ i, ↥(𝒜 i)) _ _ n _ c.denom, begin induction n with n ih, { simpa only [coe_gnpow, pow_zero] using submonoid.one_mem _ }, { simpa only [pow_succ', coe_gnpow] using x.mul_mem ih c.denom_mem, }, end⟩ } @[simp] lemma deg_pow (c : num_denom_same_deg 𝒜 x) (n : ℕ) : (c ^ n).deg = n • c.deg := rfl @[simp] lemma num_pow (c : num_denom_same_deg 𝒜 x) (n : ℕ) : ((c ^ n).num : A) = c.num ^ n := rfl @[simp] lemma denom_pow (c : num_denom_same_deg 𝒜 x) (n : ℕ) : ((c ^ n).denom : A) = c.denom ^ n := rfl section has_smul variables {α : Type*} [has_smul α R] [has_smul α A] [is_scalar_tower α R A] instance : has_smul α (num_denom_same_deg 𝒜 x) := { smul := λ m c, ⟨c.deg, m • c.num, c.denom, c.denom_mem⟩ } @[simp] lemma deg_smul (c : num_denom_same_deg 𝒜 x) (m : α) : (m • c).deg = c.deg := rfl @[simp] lemma num_smul (c : num_denom_same_deg 𝒜 x) (m : α) : ((m • c).num : A) = m • c.num := rfl @[simp] lemma denom_smul (c : num_denom_same_deg 𝒜 x) (m : α) : ((m • c).denom : A) = c.denom := rfl end has_smul variable (𝒜) /-- For `x : prime ideal of A` and any `p : num_denom_same_deg 𝒜 x`, or equivalent a numerator and a denominator of the same degree, we get an element `p.num / p.denom` of `Aₓ`. -/ def embedding (p : num_denom_same_deg 𝒜 x) : at x := localization.mk p.num ⟨p.denom, p.denom_mem⟩ end num_denom_same_deg end homogeneous_localization /-- For `x : prime ideal of A`, `homogeneous_localization 𝒜 x` is `num_denom_same_deg 𝒜 x` modulo the kernel of `embedding 𝒜 x`. This is essentially the subring of `Aₓ` where the numerator and denominator share the same grading. -/ @[nolint has_nonempty_instance] def homogeneous_localization : Type* := quotient (setoid.ker $ homogeneous_localization.num_denom_same_deg.embedding 𝒜 x) namespace homogeneous_localization open homogeneous_localization homogeneous_localization.num_denom_same_deg variables {𝒜} {x} /-- View an element of `homogeneous_localization 𝒜 x` as an element of `Aₓ` by forgetting that the numerator and denominator are of the same grading. -/ def val (y : homogeneous_localization 𝒜 x) : at x := quotient.lift_on' y (num_denom_same_deg.embedding 𝒜 x) $ λ _ _, id @[simp] lemma val_mk' (i : num_denom_same_deg 𝒜 x) : val (quotient.mk' i) = localization.mk i.num ⟨i.denom, i.denom_mem⟩ := rfl variable (x) lemma val_injective : function.injective (@homogeneous_localization.val _ _ _ _ _ _ _ _ 𝒜 _ x) := λ a b, quotient.rec_on_subsingleton₂' a b $ λ a b h, quotient.sound' h instance has_pow : has_pow (homogeneous_localization 𝒜 x) ℕ := { pow := λ z n, (quotient.map' (^ n) (λ c1 c2 (h : localization.mk _ _ = localization.mk _ _), begin change localization.mk _ _ = localization.mk _ _, simp only [num_pow, denom_pow], convert congr_arg (λ z, z ^ n) h; erw localization.mk_pow; refl, end) : homogeneous_localization 𝒜 x → homogeneous_localization 𝒜 x) z } section has_smul variables {α : Type*} [has_smul α R] [has_smul α A] [is_scalar_tower α R A] variables [is_scalar_tower α A A] instance : has_smul α (homogeneous_localization 𝒜 x) := { smul := λ m, quotient.map' ((•) m) (λ c1 c2 (h : localization.mk _ _ = localization.mk _ _), begin change localization.mk _ _ = localization.mk _ _, simp only [num_smul, denom_smul], convert congr_arg (λ z : at x, m • z) h; rw localization.smul_mk; refl, end) } @[simp] lemma smul_val (y : homogeneous_localization 𝒜 x) (n : α) : (n • y).val = n • y.val := begin induction y using quotient.induction_on, unfold homogeneous_localization.val has_smul.smul, simp only [quotient.lift_on₂'_mk, quotient.lift_on'_mk], change localization.mk _ _ = n • localization.mk _ _, dsimp only, rw localization.smul_mk, congr' 1, end end has_smul instance : has_neg (homogeneous_localization 𝒜 x) := { neg := quotient.map' has_neg.neg (λ c1 c2 (h : localization.mk _ _ = localization.mk _ _), begin change localization.mk _ _ = localization.mk _ _, simp only [num_neg, denom_neg, ←localization.neg_mk], exact congr_arg (λ c, -c) h end) } instance : has_add (homogeneous_localization 𝒜 x) := { add := quotient.map₂' (+) (λ c1 c2 (h : localization.mk _ _ = localization.mk _ _) c3 c4 (h' : localization.mk _ _ = localization.mk _ _), begin change localization.mk _ _ = localization.mk _ _, simp only [num_add, denom_add, ←localization.add_mk], convert congr_arg2 (+) h h'; erw [localization.add_mk]; refl end) } instance : has_sub (homogeneous_localization 𝒜 x) := { sub := λ z1 z2, z1 + (-z2) } instance : has_mul (homogeneous_localization 𝒜 x) := { mul := quotient.map₂' (*) (λ c1 c2 (h : localization.mk _ _ = localization.mk _ _) c3 c4 (h' : localization.mk _ _ = localization.mk _ _), begin change localization.mk _ _ = localization.mk _ _, simp only [num_mul, denom_mul], convert congr_arg2 (*) h h'; erw [localization.mk_mul]; refl, end) } instance : has_one (homogeneous_localization 𝒜 x) := { one := quotient.mk' 1 } instance : has_zero (homogeneous_localization 𝒜 x) := { zero := quotient.mk' 0 } lemma zero_eq : (0 : homogeneous_localization 𝒜 x) = quotient.mk' 0 := rfl lemma one_eq : (1 : homogeneous_localization 𝒜 x) = quotient.mk' 1 := rfl variable {x} lemma zero_val : (0 : homogeneous_localization 𝒜 x).val = 0 := localization.mk_zero _ lemma one_val : (1 : homogeneous_localization 𝒜 x).val = 1 := localization.mk_one @[simp] lemma add_val (y1 y2 : homogeneous_localization 𝒜 x) : (y1 + y2).val = y1.val + y2.val := begin induction y1 using quotient.induction_on, induction y2 using quotient.induction_on, unfold homogeneous_localization.val has_add.add, simp only [quotient.lift_on₂'_mk, quotient.lift_on'_mk], change localization.mk _ _ = localization.mk _ _ + localization.mk _ _, dsimp only, rw [localization.add_mk], refl end @[simp] lemma mul_val (y1 y2 : homogeneous_localization 𝒜 x) : (y1 * y2).val = y1.val * y2.val := begin induction y1 using quotient.induction_on, induction y2 using quotient.induction_on, unfold homogeneous_localization.val has_mul.mul, simp only [quotient.lift_on₂'_mk, quotient.lift_on'_mk], change localization.mk _ _ = localization.mk _ _ * localization.mk _ _, dsimp only, rw [localization.mk_mul], refl, end @[simp] lemma neg_val (y : homogeneous_localization 𝒜 x) : (-y).val = -y.val := begin induction y using quotient.induction_on, unfold homogeneous_localization.val has_neg.neg, simp only [quotient.lift_on₂'_mk, quotient.lift_on'_mk], change localization.mk _ _ = - localization.mk _ _, dsimp only, rw [localization.neg_mk], refl, end @[simp] lemma sub_val (y1 y2 : homogeneous_localization 𝒜 x) : (y1 - y2).val = y1.val - y2.val := by rw [show y1 - y2 = y1 + (-y2), from rfl, add_val, neg_val]; refl @[simp] lemma pow_val (y : homogeneous_localization 𝒜 x) (n : ℕ) : (y ^ n).val = y.val ^ n := begin induction y using quotient.induction_on, unfold homogeneous_localization.val has_pow.pow, simp only [quotient.lift_on₂'_mk, quotient.lift_on'_mk], change localization.mk _ _ = (localization.mk _ _) ^ n, rw localization.mk_pow, dsimp only, congr' 1, end instance : has_nat_cast (homogeneous_localization 𝒜 x) := ⟨nat.unary_cast⟩ instance : has_int_cast (homogeneous_localization 𝒜 x) := ⟨int.cast_def⟩ @[simp] lemma nat_cast_val (n : ℕ) : (n : homogeneous_localization 𝒜 x).val = n := show val (nat.unary_cast n) = _, by induction n; simp [nat.unary_cast, zero_val, one_val, *] @[simp] lemma int_cast_val (n : ℤ) : (n : homogeneous_localization 𝒜 x).val = n := show val (int.cast_def n) = _, by cases n; simp [int.cast_def, zero_val, one_val, *] instance homogenous_localization_comm_ring : comm_ring (homogeneous_localization 𝒜 x) := (homogeneous_localization.val_injective x).comm_ring _ zero_val one_val add_val mul_val neg_val sub_val (λ z n, smul_val x z n) (λ z n, smul_val x z n) pow_val nat_cast_val int_cast_val instance homogeneous_localization_algebra : algebra (homogeneous_localization 𝒜 x) (localization x) := { smul := λ p q, p.val * q, to_fun := val, map_one' := one_val, map_mul' := mul_val, map_zero' := zero_val, map_add' := add_val, commutes' := λ p q, mul_comm _ _, smul_def' := λ p q, rfl } end homogeneous_localization namespace homogeneous_localization open homogeneous_localization homogeneous_localization.num_denom_same_deg variables {𝒜} {x} /-- numerator of an element in `homogeneous_localization x`-/ def num (f : homogeneous_localization 𝒜 x) : A := (quotient.out' f).num /-- denominator of an element in `homogeneous_localization x`-/ def denom (f : homogeneous_localization 𝒜 x) : A := (quotient.out' f).denom /-- For an element in `homogeneous_localization x`, degree is the natural number `i` such that `𝒜 i` contains both numerator and denominator. -/ def deg (f : homogeneous_localization 𝒜 x) : ι := (quotient.out' f).deg lemma denom_mem (f : homogeneous_localization 𝒜 x) : f.denom ∈ x := (quotient.out' f).denom_mem lemma num_mem_deg (f : homogeneous_localization 𝒜 x) : f.num ∈ 𝒜 f.deg := (quotient.out' f).num.2 lemma denom_mem_deg (f : homogeneous_localization 𝒜 x) : f.denom ∈ 𝒜 f.deg := (quotient.out' f).denom.2 lemma eq_num_div_denom (f : homogeneous_localization 𝒜 x) : f.val = localization.mk f.num ⟨f.denom, f.denom_mem⟩ := begin have := (quotient.out_eq' f), apply_fun homogeneous_localization.val at this, rw ← this, unfold homogeneous_localization.val, simp only [quotient.lift_on'_mk'], refl, end lemma ext_iff_val (f g : homogeneous_localization 𝒜 x) : f = g ↔ f.val = g.val := { mp := λ h, h ▸ rfl, mpr := λ h, begin induction f using quotient.induction_on, induction g using quotient.induction_on, rw quotient.eq, unfold homogeneous_localization.val at h, simpa only [quotient.lift_on'_mk] using h, end } section variables (𝒜) (𝔭 : ideal A) [ideal.is_prime 𝔭] /--Localizing a ring homogeneously at a prime ideal-/ abbreviation at_prime := homogeneous_localization 𝒜 𝔭.prime_compl lemma is_unit_iff_is_unit_val (f : homogeneous_localization.at_prime 𝒜 𝔭) : is_unit f.val ↔ is_unit f := ⟨λ h1, begin rcases h1 with ⟨⟨a, b, eq0, eq1⟩, (eq2 : a = f.val)⟩, rw eq2 at eq0 eq1, clear' a eq2, induction b using localization.induction_on with data, rcases data with ⟨a, ⟨b, hb⟩⟩, dsimp only at eq0 eq1, have b_f_denom_not_mem : b * f.denom ∈ 𝔭.prime_compl := λ r, or.elim (ideal.is_prime.mem_or_mem infer_instance r) (λ r2, hb r2) (λ r2, f.denom_mem r2), rw [f.eq_num_div_denom, localization.mk_mul, show (⟨b, hb⟩ : 𝔭.prime_compl) * ⟨f.denom, _⟩ = ⟨b * f.denom, _⟩, from rfl, show (1 : localization.at_prime 𝔭) = localization.mk 1 1, by erw localization.mk_self 1, localization.mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨c, hc⟩, eq1⟩, simp only [← subtype.val_eq_coe] at eq1, change a * f.num * 1 * c = _ at eq1, simp only [one_mul, mul_one] at eq1, have mem1 : a * f.num * c ∈ 𝔭.prime_compl := eq1.symm ▸ λ r, or.elim (ideal.is_prime.mem_or_mem infer_instance r) (by tauto)(by tauto), have mem2 : f.num ∉ 𝔭, { contrapose! mem1, erw [not_not], exact ideal.mul_mem_right _ _ (ideal.mul_mem_left _ _ mem1), }, refine ⟨⟨f, quotient.mk' ⟨f.deg, ⟨f.denom, f.denom_mem_deg⟩, ⟨f.num, f.num_mem_deg⟩, mem2⟩, _, _⟩, rfl⟩; simp only [ext_iff_val, mul_val, val_mk', ← subtype.val_eq_coe, f.eq_num_div_denom, localization.mk_mul, one_val]; convert localization.mk_self _; simpa only [mul_comm] end, λ ⟨⟨_, b, eq1, eq2⟩, rfl⟩, begin simp only [ext_iff_val, mul_val, one_val] at eq1 eq2, exact ⟨⟨f.val, b.val, eq1, eq2⟩, rfl⟩ end⟩ instance : nontrivial (homogeneous_localization.at_prime 𝒜 𝔭) := ⟨⟨0, 1, λ r, by simpa [ext_iff_val, zero_val, one_val, zero_ne_one] using r⟩⟩ instance : local_ring (homogeneous_localization.at_prime 𝒜 𝔭) := local_ring.of_is_unit_or_is_unit_one_sub_self $ λ a, begin simp only [← is_unit_iff_is_unit_val, sub_val, one_val], induction a using quotient.induction_on', simp only [homogeneous_localization.val_mk', ← subtype.val_eq_coe], by_cases mem1 : a.num.1 ∈ 𝔭, { right, have : a.denom.1 - a.num.1 ∈ 𝔭.prime_compl := λ h, a.denom_mem ((sub_add_cancel a.denom.val a.num.val) ▸ ideal.add_mem _ h mem1 : a.denom.1 ∈ 𝔭), apply is_unit_of_mul_eq_one _ (localization.mk a.denom.1 ⟨a.denom.1 - a.num.1, this⟩), simp only [sub_mul, localization.mk_mul, one_mul, localization.sub_mk, ← subtype.val_eq_coe, submonoid.coe_mul], convert localization.mk_self _, simp only [← subtype.val_eq_coe, submonoid.coe_mul], ring, }, { left, change _ ∈ 𝔭.prime_compl at mem1, apply is_unit_of_mul_eq_one _ (localization.mk a.denom.1 ⟨a.num.1, mem1⟩), rw [localization.mk_mul], convert localization.mk_self _, simpa only [mul_comm], }, end end section variables (𝒜) (f : A) /--Localising away from powers of `f` homogeneously.-/ abbreviation away := homogeneous_localization 𝒜 (submonoid.powers f) end end homogeneous_localization
97bee1c55b3bbaed085fac6f9884dfa1929a84bc
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/linear_algebra/eigenspace.lean
88fc813fcb92ddb48085b702ad76f38d6f2a1467
[ "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
24,179
lean
/- Copyright (c) 2020 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import field_theory.algebraic_closure import linear_algebra.finsupp import linear_algebra.matrix /-! # Eigenvectors and eigenvalues This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties without choosing a basis and without using matrices. An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue. There is no consensus in the literature whether `0` is an eigenvector. Our definition of `has_eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we write `x ∈ f.eigenspace μ`. A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`, the scalar `μ` is called a generalized eigenvalue. ## References * [Sheldon Axler, *Linear Algebra Done Right*][axler2015] * https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors ## Tags eigenspace, eigenvector, eigenvalue, eigen -/ universes u v w namespace module namespace End open vector_space principal_ideal_ring polynomial finite_dimensional variables {K R : Type v} {V M : Type w} [comm_ring R] [add_comm_group M] [module R M] [field K] [add_comm_group V] [vector_space K V] /-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x` such that `f x = μ • x`. (Def 5.36 of [axler2015])-/ def eigenspace (f : End R M) (μ : R) : submodule R M := (f - algebra_map R (End R M) μ).ker /-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/ def has_eigenvector (f : End R M) (μ : R) (x : M) : Prop := x ≠ 0 ∧ x ∈ eigenspace f μ /-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x` such that `f x = μ • x`. (Def 5.5 of [axler2015]) -/ def has_eigenvalue (f : End R M) (a : R) : Prop := eigenspace f a ≠ ⊥ lemma mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x := by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply, sub_eq_zero] lemma eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) : eigenspace f (a / b) = (b • f - algebra_map K (End K V) a).ker := calc eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { rw [div_eq_mul_inv, mul_comm] } ... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl ... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul ... = (f - b⁻¹ • algebra_map K (End K V) a).ker : rfl ... = (b • (f - b⁻¹ • algebra_map K (End K V) a)).ker : by rw linear_map.ker_smul _ b hb ... = (b • f - algebra_map K (End K V) a).ker : by rw [smul_sub, smul_inv_smul' hb] lemma eigenspace_aeval_polynomial_degree_1 (f : End K V) (q : polynomial K) (hq : degree q = 1) : eigenspace f (- q.coeff 0 / q.leading_coeff) = (aeval f q).ker := calc eigenspace f (- q.coeff 0 / q.leading_coeff) = (q.leading_coeff • f - algebra_map K (End K V) (- q.coeff 0)).ker : by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq } ... = (aeval f (C q.leading_coeff * X + C (q.coeff 0))).ker : by { rw [C_mul', aeval_def], simpa [algebra_map, algebra.to_ring_hom], } ... = (aeval f q).ker : by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm } lemma ker_aeval_ring_hom'_unit_polynomial (f : End K V) (c : units (polynomial K)) : (aeval f (c : polynomial K)).ker = ⊥ := begin rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c), simp only [aeval_def, eval₂_C], apply ker_algebra_map_End, apply coeff_coe_units_zero_ne_zero c end theorem aeval_apply_of_has_eigenvector {f : End K V} {p : polynomial K} {μ : K} {x : V} (h : f.has_eigenvector μ x) : aeval f p x = (p.eval μ) • x := begin apply p.induction_on, { intro a, simp [module.algebra_map_End_apply] }, { intros p q hp hq, simp [hp, hq, add_smul] }, { intros n a hna, rw [mul_comm, pow_succ, mul_assoc, alg_hom.map_mul, linear_map.mul_apply, mul_comm, hna], simp [algebra_map_End_apply, mem_eigenspace_iff.1 h.2, smul_smul, mul_comm] } end section minpoly theorem is_root_of_has_eigenvalue {f : End K V} {μ : K} (h : f.has_eigenvalue μ) : (minpoly K f).is_root μ := begin rcases (submodule.ne_bot_iff _).1 h with ⟨w, ⟨H, ne0⟩⟩, refine or.resolve_right (smul_eq_zero.1 _) ne0, simp [← aeval_apply_of_has_eigenvector ⟨ne0, H⟩, minpoly.aeval K f], end variables [finite_dimensional K V] (f : End K V) protected theorem is_integral : is_integral K f := is_integral_of_noetherian (by apply_instance) f variables {f} {μ : K} theorem has_eigenvalue_of_is_root (h : (minpoly K f).is_root μ) : f.has_eigenvalue μ := begin cases dvd_iff_is_root.2 h with p hp, rw [has_eigenvalue, eigenspace], intro con, cases (linear_map.is_unit_iff _).2 con with u hu, have p_ne_0 : p ≠ 0, { intro con, apply minpoly.ne_zero f.is_integral, rw [hp, con, mul_zero] }, have h_deg := minpoly.degree_le_of_ne_zero K f p_ne_0 _, { rw [hp, degree_mul, degree_X_sub_C, polynomial.degree_eq_nat_degree p_ne_0] at h_deg, norm_cast at h_deg, linarith, }, { have h_aeval := minpoly.aeval K f, revert h_aeval, simp [hp, ← hu] }, end theorem has_eigenvalue_iff_is_root : f.has_eigenvalue μ ↔ (minpoly K f).is_root μ := ⟨is_root_of_has_eigenvalue, has_eigenvalue_of_is_root⟩ end minpoly /-- Every linear operator on a vector space over an algebraically closed field has an eigenvalue. (Lemma 5.21 of [axler2015]) -/ lemma exists_eigenvalue [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) : ∃ (c : K), f.has_eigenvalue c := begin classical, -- Choose a nonzero vector `v`. obtain ⟨v, hv⟩ : ∃ v : V, v ≠ 0 := exists_ne (0 : V), -- The infinitely many vectors v, f v, f (f v), ... cannot be linearly independent -- because the vector space is finite dimensional. have h_lin_dep : ¬ linear_independent K (λ n : ℕ, (f ^ n) v), { apply not_linear_independent_of_infinite, }, -- Therefore, there must be a nonzero polynomial `p` such that `p(f) v = 0`. obtain ⟨p, ⟨h_mon, h_eval_p⟩⟩ := f.is_integral, have h_eval_p_not_unit : aeval f p ∉ is_unit.submonoid (End K V), { rw [is_unit.mem_submonoid_iff, linear_map.is_unit_iff, linear_map.ker_eq_bot'], intro h, apply hv (h v _), rw [aeval_def, h_eval_p, linear_map.zero_apply] }, -- Hence, there must be a factor `q` of `p` such that `q(f)` is not invertible. obtain ⟨q, hq_factor, hq_nonunit⟩ : ∃ q, q ∈ factors p ∧ ¬ is_unit (aeval f q), { simp only [←not_imp, (is_unit.mem_submonoid_iff _).symm], apply not_forall.1 (λ h, h_eval_p_not_unit (ring_hom_mem_submonoid_of_factors_subset_of_units_subset (eval₂_ring_hom' (algebra_map _ _) f _) (is_unit.submonoid (End K V)) p h_mon.ne_zero h _)), simp only [is_unit.mem_submonoid_iff, linear_map.is_unit_iff], apply ker_aeval_ring_hom'_unit_polynomial }, -- Since the field is algebraically closed, `q` has degree 1. have h_deg_q : q.degree = 1 := is_alg_closed.degree_eq_one_of_irreducible _ (ne_zero_of_mem_factors h_mon.ne_zero hq_factor) ((factors_spec p h_mon.ne_zero).1 q hq_factor), -- Then the kernel of `q(f)` is an eigenspace. have h_eigenspace: eigenspace f (-q.coeff 0 / q.leading_coeff) = (aeval f q).ker, from eigenspace_aeval_polynomial_degree_1 f q h_deg_q, -- Since `q(f)` is not invertible, the kernel is not `⊥`, and thus there exists an eigenvalue. show ∃ (c : K), f.has_eigenvalue c, { use -q.coeff 0 / q.leading_coeff, rw [has_eigenvalue, h_eigenspace], intro h_eval_ker, exact hq_nonunit ((linear_map.is_unit_iff (aeval f q)).2 h_eval_ker) } end /-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly independent. (Lemma 5.10 of [axler2015]) We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each eigenvalue in the image of `xs`. -/ lemma eigenvectors_linear_independent (f : End K V) (μs : set K) (xs : μs → V) (h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) : linear_independent K xs := begin classical, -- We need to show that if a linear combination `l` of the eigenvectors `xs` is `0`, then all -- its coefficients are zero. suffices : ∀ l, finsupp.total μs V K xs l = 0 → l = 0, { rw linear_independent_iff, apply this }, intros l hl, -- We apply induction on the finite set of eigenvalues whose eigenvectors have nonzero -- coefficients, i.e. on the support of `l`. induction h_l_support : l.support using finset.induction with μ₀ l_support' hμ₀ ih generalizing l, -- If the support is empty, all coefficients are zero and we are done. { exact finsupp.support_eq_empty.1 h_l_support }, -- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new -- linear combination `l'` to apply the induction hypothesis on later. The linear combination `l'` -- is derived from `l` by multiplying the coefficient of the eigenvector with eigenvalue `μ` -- by `μ - μ₀`. -- To get started, we define `l'` as a function `l'_f : μs → K` with potentially infinite support. { let l'_f : μs → K := (λ μ : μs, (↑μ - ↑μ₀) * l μ), -- The support of `l'_f` is the support of `l` without `μ₀`. have h_l_support' : ∀ (μ : μs), μ ∈ l_support' ↔ l'_f μ ≠ 0 , { intro μ, suffices : μ ∈ l_support' → μ ≠ μ₀, { simp [l'_f, ← finsupp.not_mem_support_iff, h_l_support, sub_eq_zero, ←subtype.ext_iff], tauto }, rintro hμ rfl, contradiction }, -- Now we can define `l'_f` as an actual linear combination `l'` because we know that the -- support is finite. let l' : μs →₀ K := { to_fun := l'_f, support := l_support', mem_support_to_fun := h_l_support' }, -- The linear combination `l'` over `xs` adds up to `0`. have total_l' : finsupp.total μs V K xs l' = 0, { let g := f - algebra_map K (End K V) μ₀, have h_gμ₀: g (l μ₀ • xs μ₀) = 0, by rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).2, algebra_map_End_apply, sub_self, smul_zero], have h_useless_filter : finset.filter (λ (a : μs), l'_f a ≠ 0) l_support' = l_support', { rw finset.filter_congr _, { apply finset.filter_true }, { apply_instance }, exact λ μ hμ, (iff_true _).mpr ((h_l_support' μ).1 hμ) }, have bodies_eq : ∀ (μ : μs), l'_f μ • xs μ = g (l μ • xs μ), { intro μ, dsimp only [g, l'_f], rw [linear_map.map_smul, linear_map.sub_apply, mem_eigenspace_iff.1 (h_eigenvec _).2, algebra_map_End_apply, ←sub_smul, smul_smul, mul_comm] }, rw [←linear_map.map_zero g, ←hl, finsupp.total_apply, finsupp.total_apply, finsupp.sum, finsupp.sum, linear_map.map_sum, h_l_support, finset.sum_insert hμ₀, h_gμ₀, zero_add], refine finset.sum_congr rfl (λ μ _, _), apply bodies_eq }, -- Therefore, by the induction hypothesis, all coefficients in `l'` are zero. have l'_eq_0 : l' = 0 := ih l' total_l' rfl, -- By the defintion of `l'`, this means that `(μ - μ₀) * l μ = 0` for all `μ`. have h_mul_eq_0 : ∀ μ : μs, (↑μ - ↑μ₀) * l μ = 0, { intro μ, calc (↑μ - ↑μ₀) * l μ = l' μ : rfl ... = 0 : by { rw [l'_eq_0], refl } }, -- Thus, the coefficients in `l` for all `μ ≠ μ₀` are `0`. have h_lμ_eq_0 : ∀ μ : μs, μ ≠ μ₀ → l μ = 0, { intros μ hμ, apply or_iff_not_imp_left.1 (mul_eq_zero.1 (h_mul_eq_0 μ)), rwa [sub_eq_zero, ←subtype.ext_iff] }, -- So if we sum over all these coefficients, we obtain `0`. have h_sum_l_support'_eq_0 : finset.sum l_support' (λ (μ : ↥μs), l μ • xs μ) = 0, { rw ←finset.sum_const_zero, apply finset.sum_congr rfl, intros μ hμ, rw h_lμ_eq_0, apply zero_smul, intro h, rw h at hμ, contradiction }, -- The only potentially nonzero coefficient in `l` is the one corresponding to `μ₀`. But since -- the overall sum is `0` by assumption, this coefficient must also be `0`. have : l μ₀ = 0, { rw [finsupp.total_apply, finsupp.sum, h_l_support, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl, by_contra h, exact (h_eigenvec μ₀).1 ((smul_eq_zero.1 hl).resolve_left h) }, -- Thus, all coefficients in `l` are `0`. show l = 0, { ext μ, by_cases h_cases : μ = μ₀, { rw h_cases, assumption }, exact h_lμ_eq_0 μ h_cases } } end /-- The generalized eigenspace for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the kernel of `(f - μ • id) ^ k`. (Def 8.10 of [axler2015])-/ def generalized_eigenspace (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).ker /-- A nonzero element of a generalized eigenspace is a generalized eigenvector. (Def 8.9 of [axler2015])-/ def has_generalized_eigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop := x ≠ 0 ∧ x ∈ generalized_eigenspace f μ k /-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there are generalized eigenvectors for `f`, `k`, and `μ`. -/ def has_generalized_eigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop := generalized_eigenspace f μ k ≠ ⊥ /-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the range of `(f - μ • id) ^ k`. -/ def generalized_eigenrange (f : End R M) (μ : R) (k : ℕ) : submodule R M := ((f - algebra_map R (End R M) μ) ^ k).range /-- The exponent of a generalized eigenvalue is never 0. -/ lemma exp_ne_zero_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ} (h : f.has_generalized_eigenvalue μ k) : k ≠ 0 := begin rintro rfl, exact h linear_map.ker_id end /-- A generalized eigenspace for some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/ lemma generalized_eigenspace_mono {f : End K V} {μ : K} {k : ℕ} {m : ℕ} (hm : k ≤ m) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ m := begin simp only [generalized_eigenspace, ←pow_sub_mul_pow _ hm], exact linear_map.ker_le_ker_comp ((f - algebra_map K (End K V) μ) ^ k) ((f - algebra_map K (End K V) μ) ^ (m - k)) end /-- A generalized eigenvalue for some exponent `k` is also a generalized eigenvalue for exponents larger than `k`. -/ lemma has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le {f : End K V} {μ : K} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.has_generalized_eigenvalue μ k) : f.has_generalized_eigenvalue μ m := begin unfold has_generalized_eigenvalue at *, contrapose! hk, rw [←le_bot_iff, ←hk], exact generalized_eigenspace_mono hm end /-- The eigenspace is a subspace of the generalized eigenspace. -/ lemma eigenspace_le_generalized_eigenspace {f : End K V} {μ : K} {k : ℕ} (hk : 0 < k) : f.eigenspace μ ≤ f.generalized_eigenspace μ k := generalized_eigenspace_mono (nat.succ_le_of_lt hk) /-- All eigenvalues are generalized eigenvalues. -/ lemma has_generalized_eigenvalue_of_has_eigenvalue {f : End K V} {μ : K} {k : ℕ} (hk : 0 < k) (hμ : f.has_eigenvalue μ) : f.has_generalized_eigenvalue μ k := begin apply has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le hk, rwa [has_generalized_eigenvalue, generalized_eigenspace, pow_one] end /-- Every generalized eigenvector is a generalized eigenvector for exponent `findim K V`. (Lemma 8.11 of [axler2015]) -/ lemma generalized_eigenspace_le_generalized_eigenspace_findim [finite_dimensional K V] (f : End K V) (μ : K) (k : ℕ) : f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ (findim K V) := ker_pow_le_ker_pow_findim _ _ /-- Generalized eigenspaces for exponents at least `findim K V` are equal to each other. -/ lemma generalized_eigenspace_eq_generalized_eigenspace_findim_of_le [finite_dimensional K V] (f : End K V) (μ : K) {k : ℕ} (hk : findim K V ≤ k) : f.generalized_eigenspace μ k = f.generalized_eigenspace μ (findim K V) := ker_pow_eq_ker_pow_findim_of_le hk /-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/ lemma generalized_eigenspace_restrict (f : End K V) (p : submodule K V) (k : ℕ) (μ : K) (hfp : ∀ (x : V), x ∈ p → f x ∈ p) : generalized_eigenspace (linear_map.restrict f hfp) μ k = submodule.comap p.subtype (f.generalized_eigenspace μ k) := begin rw [generalized_eigenspace, generalized_eigenspace, ←linear_map.ker_comp], induction k with k ih, { rw [pow_zero,pow_zero], convert linear_map.ker_id, apply submodule.ker_subtype }, { erw [pow_succ', pow_succ', linear_map.ker_comp, ih, ←linear_map.ker_comp, linear_map.comp_assoc], } end /-- Generalized eigenrange and generalized eigenspace for exponent `findim K V` are disjoint. -/ lemma generalized_eigenvec_disjoint_range_ker [finite_dimensional K V] (f : End K V) (μ : K) : disjoint (f.generalized_eigenrange μ (findim K V)) (f.generalized_eigenspace μ (findim K V)) := begin have h := calc submodule.comap ((f - algebra_map _ _ μ) ^ findim K V) (f.generalized_eigenspace μ (findim K V)) = ((f - algebra_map _ _ μ) ^ findim K V * (f - algebra_map K (End K V) μ) ^ findim K V).ker : by { rw [generalized_eigenspace, ←linear_map.ker_comp], refl } ... = f.generalized_eigenspace μ (findim K V + findim K V) : by { rw ←pow_add, refl } ... = f.generalized_eigenspace μ (findim K V) : by { rw generalized_eigenspace_eq_generalized_eigenspace_findim_of_le, linarith }, rw [disjoint, generalized_eigenrange, linear_map.range, submodule.map_inf_eq_map_inf_comap, top_inf_eq, h], apply submodule.map_comap_le end /-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/ lemma pos_findim_generalized_eigenspace_of_has_eigenvalue [finite_dimensional K V] {f : End K V} {k : ℕ} {μ : K} (hx : f.has_eigenvalue μ) (hk : 0 < k): 0 < findim K (f.generalized_eigenspace μ k) := calc 0 = findim K (⊥ : submodule K V) : by rw findim_bot ... < findim K (f.eigenspace μ) : submodule.findim_lt_findim_of_lt (bot_lt_iff_ne_bot.2 hx) ... ≤ findim K (f.generalized_eigenspace μ k) : submodule.findim_mono (generalized_eigenspace_mono (nat.succ_le_of_lt hk)) /-- A linear map maps a generalized eigenrange into itself. -/ lemma map_generalized_eigenrange_le {f : End K V} {μ : K} {n : ℕ} : submodule.map f (f.generalized_eigenrange μ n) ≤ f.generalized_eigenrange μ n := calc submodule.map f (f.generalized_eigenrange μ n) = (f * ((f - algebra_map _ _ μ) ^ n)).range : (linear_map.range_comp _ _).symm ... = (((f - algebra_map _ _ μ) ^ n) * f).range : by rw algebra.mul_sub_algebra_map_pow_commutes ... = submodule.map ((f - algebra_map _ _ μ) ^ n) f.range : linear_map.range_comp _ _ ... ≤ f.generalized_eigenrange μ n : linear_map.map_le_range /-- The generalized eigenvectors span the entire vector space (Lemma 8.21 of [axler2015]). -/ lemma supr_generalized_eigenspace_eq_top [is_alg_closed K] [finite_dimensional K V] (f : End K V) : (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤ := begin tactic.unfreeze_local_instances, -- We prove the claim by strong induction on the dimension of the vector space. induction h_dim : findim K V using nat.strong_induction_on with n ih generalizing V, cases n, -- If the vector space is 0-dimensional, the result is trivial. { rw ←top_le_iff, simp only [findim_eq_zero.1 (eq.trans findim_top h_dim), bot_le] }, -- Otherwise the vector space is nontrivial. { haveI : nontrivial V := findim_pos_iff.1 (by { rw h_dim, apply nat.zero_lt_succ }), -- Hence, `f` has an eigenvalue `μ₀`. obtain ⟨μ₀, hμ₀⟩ : ∃ μ₀, f.has_eigenvalue μ₀ := exists_eigenvalue f, -- We define `ES` to be the generalized eigenspace let ES := f.generalized_eigenspace μ₀ (findim K V), -- and `ER` to be the generalized eigenrange. let ER := f.generalized_eigenrange μ₀ (findim K V), -- `f` maps `ER` into itself. have h_f_ER : ∀ (x : V), x ∈ ER → f x ∈ ER, from λ x hx, map_generalized_eigenrange_le (submodule.mem_map_of_mem hx), -- Therefore, we can define the restriction `f'` of `f` to `ER`. let f' : End K ER := f.restrict h_f_ER, -- The dimension of `ES` is positive have h_dim_ES_pos : 0 < findim K ES, { dsimp only [ES], rw h_dim, apply pos_findim_generalized_eigenspace_of_has_eigenvalue hμ₀ (nat.zero_lt_succ n) }, -- and the dimensions of `ES` and `ER` add up to `findim K V`. have h_dim_add : findim K ER + findim K ES = findim K V, { apply linear_map.findim_range_add_findim_ker }, -- Therefore the dimension `ER` mus be smaller than `findim K V`. have h_dim_ER : findim K ER < n.succ, by linarith, -- This allows us to apply the induction hypothesis on `ER`: have ih_ER : (⨆ (μ : K) (k : ℕ), f'.generalized_eigenspace μ k) = ⊤, from ih (findim K ER) h_dim_ER f' rfl, -- The induction hypothesis gives us a statement about subspaces of `ER`. We can transfer this -- to a statement about subspaces of `V` via `submodule.subtype`: have ih_ER' : (⨆ (μ : K) (k : ℕ), (f'.generalized_eigenspace μ k).map ER.subtype) = ER, by simp only [(submodule.map_supr _ _).symm, ih_ER, submodule.map_subtype_top ER], -- Moreover, every generalized eigenspace of `f'` is contained in the corresponding generalized -- eigenspace of `f`. have hff' : ∀ μ k, (f'.generalized_eigenspace μ k).map ER.subtype ≤ f.generalized_eigenspace μ k, { intros, rw generalized_eigenspace_restrict, apply submodule.map_comap_le }, -- It follows that `ER` is contained in the span of all generalized eigenvectors. have hER : ER ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, { rw ← ih_ER', apply supr_le_supr _, exact λ μ, supr_le_supr (λ k, hff' μ k), }, -- `ES` is contained in this span by definition. have hES : ES ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k, from le_trans (le_supr (λ k, f.generalized_eigenspace μ₀ k) (findim K V)) (le_supr (λ (μ : K), ⨆ (k : ℕ), f.generalized_eigenspace μ k) μ₀), -- Moreover, we know that `ER` and `ES` are disjoint. have h_disjoint : disjoint ER ES, from generalized_eigenvec_disjoint_range_ker f μ₀, -- Since the dimensions of `ER` and `ES` add up to the dimension of `V`, it follows that the -- span of all generalized eigenvectors is all of `V`. show (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤, { rw [←top_le_iff, ←submodule.eq_top_of_disjoint ER ES h_dim_add h_disjoint], apply sup_le hER hES } } end end End end module variables {K V : Type*} [field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] protected lemma linear_map.is_integral (f : V →ₗ[K] V) : is_integral K f := module.End.is_integral f
12a9d43f9bec043b57975334eccd60efc1ccf14e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/rw_set2.lean
d23b4c089a7a2e0c600ae5d74bf2b70f68bc3472
[ "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
200
lean
open nat constant f : nat → nat constant g : nat → nat axiom foo : ∀ x, x > 0 → f x = 0 ∧ g x = 1 axiom bla : ∀ x, g x = f x + 1 attribute foo [simp] attribute bla [simp] print [simp]
35122cae7256741e4254fe1fc5df4f8b62f7ab4c
66a6486e19b71391cc438afee5f081a4257564ec
/logic.hlean
86c4388cdba5d19c38dbe4bba2f97d0beaa54d62
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
1,505
hlean
/- Copyright (c) 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import types.trunc open funext eq trunc is_trunc prod sum --reserve prefix `¬`:40 --reserve prefix `~`:40 --reserve infixr ` ∧ `:35 --reserve infixr ` /\ `:35 --reserve infixr ` \/ `:30 --reserve infixr ` ∨ `:30 --reserve infix ` <-> `:20 --reserve infix ` ↔ `:20 namespace logic section open trunc_index definition propext {p q : Prop} (h : p ↔ q) : p = q := tua (equiv_of_iff_of_is_prop h) end definition false : Prop := trunctype.mk (lift empty) _ definition false.elim {A : Type} (h : false) : A := lift.rec empty.elim h definition true : Prop := trunctype.mk (lift unit) _ definition true.intro : true := lift.up unit.star definition trivial : true := lift.up unit.star definition and (p q : Prop) : Prop := tprod p q infixr ` ∧ ` := and infixr ` /\ ` := and definition and.intro {p q : Prop} (h₁ : p) (h₂ : q) : and p q := prod.mk h₁ h₂ definition and.left {p q : Prop} (h : p ∧ q) : p := prod.pr1 h definition and.right {p q : Prop} (h : p ∧ q) : q := prod.pr2 h definition not (p : Prop) : Prop := trunctype.mk (p → empty) _ definition or.inl := @or.intro_left definition or.inr := @or.intro_right definition or.elim {A B C : Type} [is_prop C] (h₀ : A ∨ B) (h₁ : (A → C)) (h₂ : B → C) : C := begin apply trunc.elim_on h₀, intro h₃, apply sum.elim h₃ h₁ h₂ end end logic
2a1f95e8a71b688c03369107270076ef5487e949
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/decomposition/signed_hahn.lean
ad73c36d99140e76786976325f85751d59b96cf9
[ "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
21,735
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.vector_measure import order.symm_diff /-! # Hahn decomposition This file proves the Hahn decomposition theorem (signed version). The Hahn decomposition theorem states that, given a signed measure `s`, there exist complementary, measurable sets `i` and `j`, such that `i` is positive and `j` is negative with respect to `s`; that is, `s` restricted on `i` is non-negative and `s` restricted on `j` is non-positive. The Hahn decomposition theorem leads to many other results in measure theory, most notably, the Jordan decomposition theorem, the Lebesgue decomposition theorem and the Radon-Nikodym theorem. ## Main results * `measure_theory.signed_measure.exists_is_compl_positive_negative` : the Hahn decomposition theorem. * `measure_theory.signed_measure.exists_subset_restrict_nonpos` : A measurable set of negative measure contains a negative subset. ## Notation We use the notations `0 ≤[i] s` and `s ≤[i] 0` to denote the usual definitions of a set `i` being positive/negative with respect to the signed measure `s`. ## Tags Hahn decomposition theorem -/ noncomputable theory open_locale classical big_operators nnreal ennreal measure_theory variables {α β : Type*} [measurable_space α] variables {M : Type*} [add_comm_monoid M] [topological_space M] [ordered_add_comm_monoid M] namespace measure_theory namespace signed_measure open filter vector_measure variables {s : signed_measure α} {i j : set α} section exists_subset_restrict_nonpos /-! ### exists_subset_restrict_nonpos In this section we will prove that a set `i` whose measure is negative contains a negative subset `j` with respect to the signed measure `s` (i.e. `s ≤[j] 0`), whose measure is negative. This lemma is used to prove the Hahn decomposition theorem. To prove this lemma, we will construct a sequence of measurable sets $(A_n)_{n \in \mathbb{N}}$, such that, for all $n$, $s(A_{n + 1})$ is close to maximal among subsets of $i \setminus \bigcup_{k \le n} A_k$. This sequence of sets does not necessarily exist. However, if this sequence terminates; that is, there does not exists any sets satisfying the property, the last $A_n$ will be a negative subset of negative measure, hence proving our claim. In the case that the sequence does not terminate, it is easy to see that $i \setminus \bigcup_{k = 0}^\infty A_k$ is the required negative set. To implement this in Lean, we define several auxilary definitions. - given the sets `i` and the natural number `n`, `exists_one_div_lt s i n` is the property that there exists a measurable set `k ⊆ i` such that `1 / (n + 1) < s k`. - given the sets `i` and that `i` is not negative, `find_exists_one_div_lt s i` is the least natural number `n` such that `exists_one_div_lt s i n`. - given the sets `i` and that `i` is not negative, `some_exists_one_div_lt` chooses the set `k` from `exists_one_div_lt s i (find_exists_one_div_lt s i)`. - lastly, given the set `i`, `restrict_nonpos_seq s i` is the sequence of sets defined inductively where `restrict_nonpos_seq s i 0 = some_exists_one_div_lt s (i \ ∅)` and `restrict_nonpos_seq s i (n + 1) = some_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq k)`. This definition represents the sequence $(A_n)$ in the proof as described above. With these definitions, we are able consider the case where the sequence terminates separately, allowing us to prove `exists_subset_restrict_nonpos`. -/ /-- Given the set `i` and the natural number `n`, `exists_one_div_lt s i j` is the property that there exists a measurable set `k ⊆ i` such that `1 / (n + 1) < s k`. -/ private def exists_one_div_lt (s : signed_measure α) (i : set α) (n : ℕ) : Prop := ∃ k : set α, k ⊆ i ∧ measurable_set k ∧ (1 / (n + 1) : ℝ) < s k private lemma exists_nat_one_div_lt_measure_of_not_negative (hi : ¬ s ≤[i] 0) : ∃ (n : ℕ), exists_one_div_lt s i n := let ⟨k, hj₁, hj₂, hj⟩ := exists_pos_measure_of_not_restrict_le_zero s hi in let ⟨n, hn⟩ := exists_nat_one_div_lt hj in ⟨n, k, hj₂, hj₁, hn⟩ /-- Given the set `i`, if `i` is not negative, `find_exists_one_div_lt s i` is the least natural number `n` such that `exists_one_div_lt s i n`, otherwise, it returns 0. -/ private def find_exists_one_div_lt (s : signed_measure α) (i : set α) : ℕ := if hi : ¬ s ≤[i] 0 then nat.find (exists_nat_one_div_lt_measure_of_not_negative hi) else 0 private lemma find_exists_one_div_lt_spec (hi : ¬ s ≤[i] 0) : exists_one_div_lt s i (find_exists_one_div_lt s i) := begin rw [find_exists_one_div_lt, dif_pos hi], convert nat.find_spec _, end private lemma find_exists_one_div_lt_min (hi : ¬ s ≤[i] 0) {m : ℕ} (hm : m < find_exists_one_div_lt s i) : ¬ exists_one_div_lt s i m := begin rw [find_exists_one_div_lt, dif_pos hi] at hm, exact nat.find_min _ hm end /-- Given the set `i`, if `i` is not negative, `some_exists_one_div_lt` chooses the set `k` from `exists_one_div_lt s i (find_exists_one_div_lt s i)`, otherwise, it returns the empty set. -/ private def some_exists_one_div_lt (s : signed_measure α) (i : set α) : set α := if hi : ¬ s ≤[i] 0 then classical.some (find_exists_one_div_lt_spec hi) else ∅ private lemma some_exists_one_div_lt_spec (hi : ¬ s ≤[i] 0) : (some_exists_one_div_lt s i) ⊆ i ∧ measurable_set (some_exists_one_div_lt s i) ∧ (1 / (find_exists_one_div_lt s i + 1) : ℝ) < s (some_exists_one_div_lt s i) := begin rw [some_exists_one_div_lt, dif_pos hi], exact classical.some_spec (find_exists_one_div_lt_spec hi), end private lemma some_exists_one_div_lt_subset : some_exists_one_div_lt s i ⊆ i := begin by_cases hi : ¬ s ≤[i] 0, { exact let ⟨h, _⟩ := some_exists_one_div_lt_spec hi in h }, { rw [some_exists_one_div_lt, dif_neg hi], exact set.empty_subset _ }, end private lemma some_exists_one_div_lt_subset' : some_exists_one_div_lt s (i \ j) ⊆ i := set.subset.trans some_exists_one_div_lt_subset (set.diff_subset _ _) private lemma some_exists_one_div_lt_measurable_set : measurable_set (some_exists_one_div_lt s i) := begin by_cases hi : ¬ s ≤[i] 0, { exact let ⟨_, h, _⟩ := some_exists_one_div_lt_spec hi in h }, { rw [some_exists_one_div_lt, dif_neg hi], exact measurable_set.empty } end private lemma some_exists_one_div_lt_lt (hi : ¬ s ≤[i] 0) : (1 / (find_exists_one_div_lt s i + 1) : ℝ) < s (some_exists_one_div_lt s i) := let ⟨_, _, h⟩ := some_exists_one_div_lt_spec hi in h /-- Given the set `i`, `restrict_nonpos_seq s i` is the sequence of sets defined inductively where `restrict_nonpos_seq s i 0 = some_exists_one_div_lt s (i \ ∅)` and `restrict_nonpos_seq s i (n + 1) = some_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq k)`. For each `n : ℕ`,`s (restrict_nonpos_seq s i n)` is close to maximal among all subsets of `i \ ⋃ k ≤ n, restrict_nonpos_seq s i k`. -/ private def restrict_nonpos_seq (s : signed_measure α) (i : set α) : ℕ → set α | 0 := some_exists_one_div_lt s (i \ ∅) -- I used `i \ ∅` instead of `i` to simplify some proofs | (n + 1) := some_exists_one_div_lt s (i \ ⋃ k ≤ n, have k < n + 1 := nat.lt_succ_iff.mpr H, restrict_nonpos_seq k) private lemma restrict_nonpos_seq_succ (n : ℕ) : restrict_nonpos_seq s i n.succ = some_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq s i k) := by rw restrict_nonpos_seq private lemma restrict_nonpos_seq_subset (n : ℕ) : restrict_nonpos_seq s i n ⊆ i := begin cases n; { rw restrict_nonpos_seq, exact some_exists_one_div_lt_subset' } end private lemma restrict_nonpos_seq_lt (n : ℕ) (hn : ¬ s ≤[i \ ⋃ k ≤ n, restrict_nonpos_seq s i k] 0) : (1 / (find_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq s i k) + 1) : ℝ) < s (restrict_nonpos_seq s i n.succ) := begin rw restrict_nonpos_seq_succ, apply some_exists_one_div_lt_lt hn, end private lemma measure_of_restrict_nonpos_seq (hi₂ : ¬ s ≤[i] 0) (n : ℕ) (hn : ¬ s ≤[i \ ⋃ k < n, restrict_nonpos_seq s i k] 0) : 0 < s (restrict_nonpos_seq s i n) := begin cases n, { rw restrict_nonpos_seq, rw ← @set.diff_empty _ i at hi₂, rcases some_exists_one_div_lt_spec hi₂ with ⟨_, _, h⟩, exact (lt_trans nat.one_div_pos_of_nat h) }, { rw restrict_nonpos_seq_succ, have h₁ : ¬ s ≤[i \ ⋃ (k : ℕ) (H : k ≤ n), restrict_nonpos_seq s i k] 0, { refine mt (restrict_le_zero_subset _ _ (by simp [nat.lt_succ_iff])) hn, convert measurable_of_not_restrict_le_zero _ hn, exact funext (λ x, by rw nat.lt_succ_iff) }, rcases some_exists_one_div_lt_spec h₁ with ⟨_, _, h⟩, exact (lt_trans nat.one_div_pos_of_nat h) } end private lemma restrict_nonpos_seq_measurable_set (n : ℕ) : measurable_set (restrict_nonpos_seq s i n) := begin cases n; { rw restrict_nonpos_seq, exact some_exists_one_div_lt_measurable_set }, end private lemma restrict_nonpos_seq_disjoint' {n m : ℕ} (h : n < m) : restrict_nonpos_seq s i n ∩ restrict_nonpos_seq s i m = ∅ := begin rw set.eq_empty_iff_forall_not_mem, rintro x ⟨hx₁, hx₂⟩, cases m, { linarith }, { rw restrict_nonpos_seq at hx₂, exact (some_exists_one_div_lt_subset hx₂).2 (set.mem_Union.2 ⟨n, set.mem_Union.2 ⟨nat.lt_succ_iff.mp h, hx₁⟩⟩) } end private lemma restrict_nonpos_seq_disjoint : pairwise (disjoint on (restrict_nonpos_seq s i)) := begin intros n m h, rcases lt_or_gt_of_ne h with (h | h), { intro x, rw [set.inf_eq_inter, restrict_nonpos_seq_disjoint' h], exact id }, { intro x, rw [set.inf_eq_inter, set.inter_comm, restrict_nonpos_seq_disjoint' h], exact id } end private lemma exists_subset_restrict_nonpos' (hi₁ : measurable_set i) (hi₂ : s i < 0) (hn : ¬ ∀ n : ℕ, ¬ s ≤[i \ ⋃ l < n, restrict_nonpos_seq s i l] 0) : ∃ j : set α, measurable_set j ∧ j ⊆ i ∧ s ≤[j] 0 ∧ s j < 0 := begin by_cases s ≤[i] 0, { exact ⟨i, hi₁, set.subset.refl _, h, hi₂⟩ }, push_neg at hn, set k := nat.find hn with hk₁, have hk₂ : s ≤[i \ ⋃ l < k, restrict_nonpos_seq s i l] 0 := nat.find_spec hn, have hmeas : measurable_set (⋃ (l : ℕ) (H : l < k), restrict_nonpos_seq s i l) := (measurable_set.Union $ λ _, measurable_set.Union_Prop (λ _, restrict_nonpos_seq_measurable_set _)), refine ⟨i \ ⋃ l < k, restrict_nonpos_seq s i l, hi₁.diff hmeas, set.diff_subset _ _, hk₂, _⟩, rw [of_diff hmeas hi₁, s.of_disjoint_Union_nat], { have h₁ : ∀ l < k, 0 ≤ s (restrict_nonpos_seq s i l), { intros l hl, refine le_of_lt (measure_of_restrict_nonpos_seq h _ _), refine mt (restrict_le_zero_subset _ (hi₁.diff _) (set.subset.refl _)) (nat.find_min hn hl), exact (measurable_set.Union $ λ _, measurable_set.Union_Prop (λ _, restrict_nonpos_seq_measurable_set _)) }, suffices : 0 ≤ ∑' (l : ℕ), s (⋃ (H : l < k), restrict_nonpos_seq s i l), { rw sub_neg, exact lt_of_lt_of_le hi₂ this }, refine tsum_nonneg _, intro l, by_cases l < k, { convert h₁ _ h, ext x, rw [set.mem_Union, exists_prop, and_iff_right_iff_imp], exact λ _, h }, { convert le_of_eq s.empty.symm, ext, simp only [exists_prop, set.mem_empty_eq, set.mem_Union, not_and, iff_false], exact λ h', false.elim (h h') } }, { intro, exact measurable_set.Union_Prop (λ _, restrict_nonpos_seq_measurable_set _) }, { intros a b hab x hx, simp only [exists_prop, set.mem_Union, set.mem_inter_eq, set.inf_eq_inter] at hx, exact let ⟨⟨_, hx₁⟩, _, hx₂⟩ := hx in restrict_nonpos_seq_disjoint a b hab ⟨hx₁, hx₂⟩ }, { apply set.Union_subset, intros a x, simp only [and_imp, exists_prop, set.mem_Union], intros _ hx, exact restrict_nonpos_seq_subset _ hx }, { apply_instance } end /-- A measurable set of negative measure has a negative subset of negative measure. -/ theorem exists_subset_restrict_nonpos (hi : s i < 0) : ∃ j : set α, measurable_set j ∧ j ⊆ i ∧ s ≤[j] 0 ∧ s j < 0 := begin have hi₁ : measurable_set i := classical.by_contradiction (λ h, ne_of_lt hi $ s.not_measurable h), by_cases s ≤[i] 0, { exact ⟨i, hi₁, set.subset.refl _, h, hi⟩ }, by_cases hn : ∀ n : ℕ, ¬ s ≤[i \ ⋃ l < n, restrict_nonpos_seq s i l] 0, swap, { exact exists_subset_restrict_nonpos' hi₁ hi hn }, set A := i \ ⋃ l, restrict_nonpos_seq s i l with hA, set bdd : ℕ → ℕ := λ n, find_exists_one_div_lt s (i \ ⋃ k ≤ n, restrict_nonpos_seq s i k) with hbdd, have hn' : ∀ n : ℕ, ¬ s ≤[i \ ⋃ l ≤ n, restrict_nonpos_seq s i l] 0, { intro n, convert hn (n + 1); { ext l, simp only [exists_prop, set.mem_Union, and.congr_left_iff], exact λ _, nat.lt_succ_iff.symm } }, have h₁ : s i = s A + ∑' l, s (restrict_nonpos_seq s i l), { rw [hA, ← s.of_disjoint_Union_nat, add_comm, of_add_of_diff], exact measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _), exacts [hi₁, set.Union_subset (λ _, restrict_nonpos_seq_subset _), λ _, restrict_nonpos_seq_measurable_set _, restrict_nonpos_seq_disjoint] }, have h₂ : s A ≤ s i, { rw h₁, apply le_add_of_nonneg_right, exact tsum_nonneg (λ n, le_of_lt (measure_of_restrict_nonpos_seq h _ (hn n))) }, have h₃' : summable (λ n, (1 / (bdd n + 1) : ℝ)), { have : summable (λ l, s (restrict_nonpos_seq s i l)) := has_sum.summable (s.m_Union (λ _, restrict_nonpos_seq_measurable_set _) restrict_nonpos_seq_disjoint), refine summable_of_nonneg_of_le (λ n, _) (λ n, _) (summable.comp_injective this nat.succ_injective), { exact le_of_lt nat.one_div_pos_of_nat }, { exact le_of_lt (restrict_nonpos_seq_lt n (hn' n)) } }, have h₃ : tendsto (λ n, (bdd n : ℝ) + 1) at_top at_top, { simp only [one_div] at h₃', exact summable.tendsto_top_of_pos h₃' (λ n, nat.cast_add_one_pos (bdd n)) }, have h₄ : tendsto (λ n, (bdd n : ℝ)) at_top at_top, { convert at_top.tendsto_at_top_add_const_right (-1) h₃, simp }, have A_meas : measurable_set A := hi₁.diff (measurable_set.Union (λ _, restrict_nonpos_seq_measurable_set _)), refine ⟨A, A_meas, set.diff_subset _ _, _, h₂.trans_lt hi⟩, by_contra hnn, rw restrict_le_restrict_iff _ _ A_meas at hnn, push_neg at hnn, obtain ⟨E, hE₁, hE₂, hE₃⟩ := hnn, have : ∃ k, 1 ≤ bdd k ∧ 1 / (bdd k : ℝ) < s E, { rw tendsto_at_top_at_top at h₄, obtain ⟨k, hk⟩ := h₄ (max (1 / s E + 1) 1), refine ⟨k, _, _⟩, { have hle := le_of_max_le_right (hk k le_rfl), norm_cast at hle, exact hle }, { have : 1 / s E < bdd k, { linarith [le_of_max_le_left (hk k le_rfl)] {restrict_type := ℝ} }, rw one_div at this ⊢, rwa inv_lt (lt_trans (inv_pos.2 hE₃) this) hE₃ } }, obtain ⟨k, hk₁, hk₂⟩ := this, have hA' : A ⊆ i \ ⋃ l ≤ k, restrict_nonpos_seq s i l, { apply set.diff_subset_diff_right, intro x, simp only [set.mem_Union], rintro ⟨n, _, hn₂⟩, exact ⟨n, hn₂⟩ }, refine find_exists_one_div_lt_min (hn' k) (buffer.lt_aux_2 hk₁) ⟨E, set.subset.trans hE₂ hA', hE₁, _⟩, convert hk₂, norm_cast, exact tsub_add_cancel_of_le hk₁ end end exists_subset_restrict_nonpos /-- The set of measures of the set of measurable negative sets. -/ def measure_of_negatives (s : signed_measure α) : set ℝ := s '' { B | measurable_set B ∧ s ≤[B] 0 } lemma zero_mem_measure_of_negatives : (0 : ℝ) ∈ s.measure_of_negatives := ⟨∅, ⟨measurable_set.empty, le_restrict_empty _ _⟩, s.empty⟩ lemma bdd_below_measure_of_negatives : bdd_below s.measure_of_negatives := begin simp_rw [bdd_below, set.nonempty, mem_lower_bounds], by_contra' h, have h' : ∀ n : ℕ, ∃ y : ℝ, y ∈ s.measure_of_negatives ∧ y < -n := λ n, h (-n), choose f hf using h', have hf' : ∀ n : ℕ, ∃ B, measurable_set B ∧ s ≤[B] 0 ∧ s B < -n, { intro n, rcases hf n with ⟨⟨B, ⟨hB₁, hBr⟩, hB₂⟩, hlt⟩, exact ⟨B, hB₁, hBr, hB₂.symm ▸ hlt⟩ }, choose B hmeas hr h_lt using hf', set A := ⋃ n, B n with hA, have hfalse : ∀ n : ℕ, s A ≤ -n, { intro n, refine le_trans _ (le_of_lt (h_lt _)), rw [hA, ← set.diff_union_of_subset (set.subset_Union _ n), of_union (disjoint.comm.1 set.disjoint_diff) _ (hmeas n)], { refine add_le_of_nonpos_left _, have : s ≤[A] 0 := restrict_le_restrict_Union _ _ hmeas hr, refine nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (set.diff_subset _ _) this), exact measurable_set.Union hmeas }, { apply_instance }, { exact (measurable_set.Union hmeas).diff (hmeas n) } }, rcases exists_nat_gt (-(s A)) with ⟨n, hn⟩, exact lt_irrefl _ ((neg_lt.1 hn).trans_le (hfalse n)), end /-- Alternative formulation of `measure_theory.signed_measure.exists_is_compl_positive_negative` (the Hahn decomposition theorem) using set complements. -/ lemma exists_compl_positive_negative (s : signed_measure α) : ∃ i : set α, measurable_set i ∧ 0 ≤[i] s ∧ s ≤[iᶜ] 0 := begin obtain ⟨f, _, hf₂, hf₁⟩ := exists_seq_tendsto_Inf ⟨0, @zero_mem_measure_of_negatives _ _ s⟩ bdd_below_measure_of_negatives, choose B hB using hf₁, have hB₁ : ∀ n, measurable_set (B n) := λ n, (hB n).1.1, have hB₂ : ∀ n, s ≤[B n] 0 := λ n, (hB n).1.2, set A := ⋃ n, B n with hA, have hA₁ : measurable_set A := measurable_set.Union hB₁, have hA₂ : s ≤[A] 0 := restrict_le_restrict_Union _ _ hB₁ hB₂, have hA₃ : s A = Inf s.measure_of_negatives, { apply le_antisymm, { refine le_of_tendsto_of_tendsto tendsto_const_nhds hf₂ (eventually_of_forall (λ n, _)), rw [← (hB n).2, hA, ← set.diff_union_of_subset (set.subset_Union _ n), of_union (disjoint.comm.1 set.disjoint_diff) _ (hB₁ n)], { refine add_le_of_nonpos_left _, have : s ≤[A] 0 := restrict_le_restrict_Union _ _ hB₁ (λ m, let ⟨_, h⟩ := (hB m).1 in h), refine nonpos_of_restrict_le_zero _ (restrict_le_zero_subset _ _ (set.diff_subset _ _) this), exact measurable_set.Union hB₁ }, { apply_instance }, { exact (measurable_set.Union hB₁).diff (hB₁ n) } }, { exact cInf_le bdd_below_measure_of_negatives ⟨A, ⟨hA₁, hA₂⟩, rfl⟩ } }, refine ⟨Aᶜ, hA₁.compl, _, (compl_compl A).symm ▸ hA₂⟩, rw restrict_le_restrict_iff _ _ hA₁.compl, intros C hC hC₁, by_contra' hC₂, rcases exists_subset_restrict_nonpos hC₂ with ⟨D, hD₁, hD, hD₂, hD₃⟩, have : s (A ∪ D) < Inf s.measure_of_negatives, { rw [← hA₃, of_union (set.disjoint_of_subset_right (set.subset.trans hD hC₁) disjoint_compl_right) hA₁ hD₁], linarith, apply_instance }, refine not_le.2 this _, refine cInf_le bdd_below_measure_of_negatives ⟨A ∪ D, ⟨_, _⟩, rfl⟩, { exact hA₁.union hD₁ }, { exact restrict_le_restrict_union _ _ hA₁ hA₂ hD₁ hD₂ }, end /-- **The Hahn decomposition thoerem**: Given a signed measure `s`, there exist complement measurable sets `i` and `j` such that `i` is positive, `j` is negative. -/ theorem exists_is_compl_positive_negative (s : signed_measure α) : ∃ i j : set α, measurable_set i ∧ 0 ≤[i] s ∧ measurable_set j ∧ s ≤[j] 0 ∧ is_compl i j := let ⟨i, hi₁, hi₂, hi₃⟩ := exists_compl_positive_negative s in ⟨i, iᶜ, hi₁, hi₂, hi₁.compl, hi₃, is_compl_compl⟩ /-- The symmetric difference of two Hahn decompositions has measure zero. -/ lemma of_symm_diff_compl_positive_negative {s : signed_measure α} {i j : set α} (hi : measurable_set i) (hj : measurable_set j) (hi' : 0 ≤[i] s ∧ s ≤[iᶜ] 0) (hj' : 0 ≤[j] s ∧ s ≤[jᶜ] 0) : s (i Δ j) = 0 ∧ s (iᶜ Δ jᶜ) = 0 := begin rw [restrict_le_restrict_iff s 0, restrict_le_restrict_iff 0 s] at hi' hj', split, { rw [symm_diff_def, set.diff_eq_compl_inter, set.diff_eq_compl_inter, set.sup_eq_union, of_union, le_antisymm (hi'.2 (hi.compl.inter hj) (set.inter_subset_left _ _)) (hj'.1 (hi.compl.inter hj) (set.inter_subset_right _ _)), le_antisymm (hj'.2 (hj.compl.inter hi) (set.inter_subset_left _ _)) (hi'.1 (hj.compl.inter hi) (set.inter_subset_right _ _)), zero_apply, zero_apply, zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_left _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) (disjoint.comm.1 (is_compl.disjoint is_compl_compl))) }, { exact hj.compl.inter hi }, { exact hi.compl.inter hj } }, { rw [symm_diff_def, set.diff_eq_compl_inter, set.diff_eq_compl_inter, compl_compl, compl_compl, set.sup_eq_union, of_union, le_antisymm (hi'.2 (hj.inter hi.compl) (set.inter_subset_right _ _)) (hj'.1 (hj.inter hi.compl) (set.inter_subset_left _ _)), le_antisymm (hj'.2 (hi.inter hj.compl) (set.inter_subset_right _ _)) (hi'.1 (hi.inter hj.compl) (set.inter_subset_left _ _)), zero_apply, zero_apply, zero_add], { exact set.disjoint_of_subset_left (set.inter_subset_left _ _) (set.disjoint_of_subset_right (set.inter_subset_right _ _) (is_compl.disjoint is_compl_compl)) }, { exact hj.inter hi.compl }, { exact hi.inter hj.compl } }, all_goals { measurability }, end end signed_measure end measure_theory
909867121165348840cb42142f3de8d0f8579005
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/wr/proofs/ki.lean
bfe6eff73fecb44c08ca4539e05e3de8d9a4a525
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
12,117
lean
import hilbert.wr.ki namespace clfrags namespace hilbert namespace wr namespace ki theorem ki₁₀ {a b c : Prop} (h₁ : a) (h₂ : c) : ki a b c := have h₃ : ki a c (ki a b c), from ki₂ h₁, show ki a b c, from ki₁ h₂ h₃ theorem ki'₃ {a b c d : Prop} (h₁ : a) : ki a (ki a b (ki a c d)) (ki a (ki a b c) (ki a b d)) := have h₂ : ki a a a, from ki₁₀ h₁ h₁, have h₃ : ki a a (ki a (ki a b (ki a c d)) (ki a (ki a b c) (ki a b d))), from ki₃ h₂, show ki a (ki a b (ki a c d)) (ki a (ki a b c) (ki a b d)), from ki₁ h₁ h₃ theorem ki'₄ {a b c : Prop} (h₁ : a) : ki a (ki a (ki a c b) c) c := have h₂ : ki a a a, from ki₁₀ h₁ h₁, have h₃ : ki a a (ki a (ki a (ki a c b) c) c), from ki₄ h₂, show ki a (ki a (ki a c b) c) c, from ki₁ h₁ h₃ theorem ki₀ {a b c : Prop} (h₁ : ki a b c) : a := let r := ki a b c in have h₂ : r, from h₁, have h₃ : ki r r (ki a b c), from ki₁₀ h₂ h₂, have h₄ : ki r r a, from ki₈ h₃, show a, from ki₁ h₂ h₄ theorem ki₁₁ {a b : Prop} (h₁ : a) : ki a b b := have h₂ : ki a (ki a b (ki a a b)) (ki a (ki a b a) (ki a b b)), from ki'₃ h₁, have h₃ : ki a b (ki a a b), from ki₂ h₁, have h₄ : ki a (ki a b a) (ki a b b), from ki₁ h₃ h₂, have h₅ : ki a b a, from ki₁₀ h₁ h₁, show ki a b b, from ki₁ h₅ h₄ theorem ki₁₂ {a b c d : Prop} (h₁ : ki a b (ki a c d)) : ki a c (ki a b d) := have h₂ : a, from ki₀ h₁, have h₃ : ki a (ki a b (ki a c d)) (ki a (ki a b c) (ki a b d)), from ki'₃ h₂, have h₄ : ki a (ki a b c) (ki a b d), from ki₁ h₁ h₃, have h₅ : ki a c (ki a (ki a b c) (ki a b d)), from ki₁₀ h₂ h₄, let r := ki a b d, q := ki a b c in have h₆ : ki a (ki a c (ki a q r)) (ki a (ki a c q) (ki a c r)), from ki'₃ h₂, have h₇ : ki a (ki a c q) (ki a c r), from ki₁ h₅ h₆, have h₈ : ki a c q, from ki₂ h₂, have h₉ : ki a c r, from ki₁ h₈ h₇, show ki a c (ki a b d), from h₉ theorem ki₁₃ {a b c : Prop} (h₁ : ki a b (ki a b c)) : ki a b c := have h₂ : a, from ki₀ h₁, have h₃ : ki a (ki a b (ki a b c)) (ki a (ki a b b) (ki a b c)), from ki'₃ h₂, have h₄ : ki a (ki a b b) (ki a b c), from ki₁ h₁ h₃, have h₅ : ki a b b, from ki₁₁ h₂, show ki a b c, from ki₁ h₅ h₄ theorem ki₁₄ {a b c d : Prop} (h₁ : ki a b d) : ki a (ki b b c) d := have h₂ : a, from ki₀ h₁, have h₃ : ki a c (ki a b d), from ki₁₀ h₂ h₁, have h₄ : ki a b (ki a c d), from ki₁₂ h₃, show ki a (ki b b c) d, from ki₅ h₄ theorem ki₁₅ {a b c d : Prop} (h₁ : ki a b d) : ki a (ki c c b) d := have h₂ : a, from ki₀ h₁, have h₃ : ki a c (ki a b d), from ki₁₀ h₂ h₁, show ki a (ki c c b) d, from ki₅ h₃ theorem ki₁₆ {a b c d : Prop} (h₁ : ki a b c) (h₂ : ki a c d) : ki a b d := have h₃ : a, from ki₀ h₁, have h₄ : ki a (ki a b (ki a c d)) (ki a (ki a b c) (ki a b d)), from ki'₃ h₃, have h₅ : ki a b (ki a c d), from ki₁₀ h₃ h₂, have h₆ : ki a (ki a b c) (ki a b d), from ki₁ h₅ h₄, show ki a b d, from ki₁ h₁ h₆ theorem ki₁_ki {a b c d e : Prop} (h₁ : ki d e b) (h₂ : ki d e (ki a b c)) : ki d e c := have h₃ : ki d e (ki d b c), from ki₉ h₂, have h₄ : ki d b (ki d e c), from ki₁₂ h₃, have h₅ : ki d e (ki d e c), from ki₁₆ h₁ h₄, show ki d e c, from ki₁₃ h₅ theorem ki₂_ki {a b c d e : Prop} (h₁ : ki d e a) : ki d e (ki a b (ki a c b)) := have h₂ : d, from ki₀ h₁, have h₃ : ki d b (ki d c b), from ki₂ h₂, have h₄ : ki d (ki e e b) (ki d c b), from ki₁₅ h₃, have h₅ : ki d (ki e e b) a, from ki₁₄ h₁, have h₆ : ki d (ki e e b) (ki a c b), from ki₇ h₅ h₄, have h₇ : ki d e (ki d b (ki a c b)), from ki₆ h₆, show ki d e (ki a b (ki a c b)), from ki₇ h₁ h₇ theorem ki₁₀_ki {a b c d e : Prop} (h₁ : ki d e a) (h₂ : ki d e c) : ki d e (ki a b c) := have h₃ : ki d e (ki a c (ki a b c)), from ki₂_ki h₁, show ki d e (ki a b c), from ki₁_ki h₂ h₃ theorem ki₁₂_ki {a b c d e f : Prop} (h₁ : ki e f (ki a b (ki a c d))) : ki e f (ki a c (ki a b d)) := have h₂ : ki e f a, from ki₈ h₁, have h₃ : ki e f (ki a (ki a b (ki a c d)) (ki a (ki a b c) (ki a b d))), from ki₃ h₂, have h₄ : ki e f (ki a (ki a b c) (ki a b d)), from ki₁_ki h₁ h₃, have h₅ : ki e f (ki a c (ki a (ki a b c) (ki a b d))), from ki₁₀_ki h₂ h₄, let r := ki a b d, q := ki a b c in have h₆ : ki e f (ki a (ki a c (ki a q r)) (ki a (ki a c q) (ki a c r))), from ki₃ h₂, have h₇ : ki e f (ki a (ki a c q) (ki a c r)), from ki₁_ki h₅ h₆, have h₈ : ki e f (ki a c q), from ki₂_ki h₂, have h₉ : ki e f (ki a c r), from ki₁_ki h₈ h₇, show ki e f (ki a c (ki a b d)), from h₉ theorem ki₃_ki {a b c d e f g h : Prop} (h₁ : ki g h (ki b f a)) : ki g h (ki b f (ki a (ki a c (ki a d e)) (ki a (ki a c d) (ki a c e)))) := have h₂ : ki g h (ki g f a), from ki₉ h₁, have h₃ : ki g (ki h h f) a, from ki₅ h₂, have h₄ : ki g (ki h h f) (ki a (ki a c (ki a d e)) (ki a (ki a c d) (ki a c e))), from ki₃ h₃, have h₅ : ki g h (ki g f (ki a (ki a c (ki a d e)) (ki a (ki a c d) (ki a c e)))), from ki₆ h₄, have h₆ : ki g h b, from ki₈ h₁, show ki g h (ki b f (ki a (ki a c (ki a d e)) (ki a (ki a c d) (ki a c e)))), from ki₇ h₆ h₅ theorem ki₄_ki {a b c d e f g : Prop} (h₁ : ki f g (ki b e a)) : ki f g (ki b e (ki a (ki a (ki a c d) c) c)) := have h₂ : ki f g (ki f e a), from ki₉ h₁, have h₃ : ki f (ki g g e) a, from ki₅ h₂, have h₄ : ki f (ki g g e) (ki a (ki a (ki a c d) c) c), from ki₄ h₃, have h₅ : ki f g (ki f e (ki a (ki a (ki a c d) c) c)), from ki₆ h₄, have h₆ : ki f g b, from ki₈ h₁, show ki f g (ki b e (ki a (ki a (ki a c d) c) c)), from ki₇ h₆ h₅ theorem ki₅_ki {a b c d e f : Prop} (h₁ : ki e f (ki a b (ki a c d))) : ki e f (ki a (ki b b c) d) := have h₂ : ki e f (ki e b (ki a c d)), from ki₉ h₁, have h₃ : ki e b (ki e f (ki a c d)), from ki₁₂ h₂, have h₄ : ki e (ki b b f) (ki a c d), from ki₅ h₃, have h₅ : ki e (ki b b f) (ki e c d), from ki₉ h₄, have h₆ : ki e b (ki e f (ki e c d)), from ki₆ h₅, have h₇ : ki e b (ki e c (ki e f d)), from ki₁₂_ki h₆, have h₈ : ki e (ki b b c) (ki e f d), from ki₅ h₇, have h₉ : ki e f (ki e (ki b b c) d), from ki₁₂ h₈, have h₁₀ : ki e f a, from ki₈ h₁, show ki e f (ki a (ki b b c) d), from ki₇ h₁₀ h₉ theorem ki₆_ki {a b c d e f : Prop} (h₁ : ki e f (ki a (ki b b c) d)) : ki e f (ki a b (ki a c d)) := have h₂ : ki e f (ki e (ki b b c) d), from ki₉ h₁, have h₃ : ki e (ki b b c) (ki e f d), from ki₁₂ h₂, have h₄ : ki e b (ki e c (ki e f d)), from ki₆ h₃, have h₅ : ki e b (ki e f (ki e c d)), from ki₁₂_ki h₄, have h₆ : ki e f (ki e b (ki e c d)), from ki₁₂ h₅, have h₇ : ki e (ki f f b) (ki e c d), from ki₅ h₆, have h₈ : ki e f a, from ki₈ h₁, have h₉ : ki e (ki f f b) a, from ki₁₄ h₈, have h₁₀ : ki e (ki f f b) (ki a c d), from ki₇ h₉ h₇, have h₁₁ : ki e f (ki e b (ki a c d)), from ki₆ h₁₀, show ki e f (ki a b (ki a c d)), from ki₇ h₈ h₁₁ theorem ki₇_ki {a b c d e f g : Prop} (h₁ : ki f g (ki a e b)) (h₂ : ki f g (ki a e (ki a c d))) : ki f g (ki a e (ki b c d)) := have h₃ : ki f g (ki f e b), from ki₉ h₁, have h₄ : ki f (ki g g e) b, from ki₅ h₃, have h₅ : ki f g a, from ki₈ h₁, have h₆ : ki f g (ki f e (ki a c d)), from ki₉ h₂, have h₇ : ki f (ki g g e) (ki a c d), from ki₅ h₆, have h₈ : ki f (ki g g e) (ki f c d), from ki₉ h₇, have h₉ : ki f (ki g g e) (ki b c d), from ki₇ h₄ h₈, have h₁₀ : ki f g (ki f e (ki b c d)), from ki₆ h₉, show ki f g (ki a e (ki b c d)), from ki₇ h₅ h₁₀ theorem ki₈_ki {a b c d e f g : Prop} (h₁ : ki f g (ki a e (ki b c d))) : ki f g (ki a e b) := have h₂ : ki f g (ki f e (ki b c d)), from ki₉ h₁, have h₃ : ki f (ki g g e) (ki b c d), from ki₅ h₂, have h₄ : ki f (ki g g e) b, from ki₈ h₃, have h₅ : ki f g (ki f e b), from ki₆ h₄, have h₆ : ki f g a, from ki₈ h₁, show ki f g (ki a e b), from ki₇ h₆ h₅ theorem ki₉_ki {a b c d e f g : Prop} (h₁ : ki f g (ki a e (ki b c d))) : ki f g (ki a e (ki a c d)) := have h₂ : ki f g a, from ki₈ h₁, have h₃ : ki f g (ki f e (ki b c d)), from ki₉ h₁, have h₄ : ki f (ki g g e) (ki b c d), from ki₅ h₃, have h₅ : ki f (ki g g e) (ki f c d), from ki₉ h₄, have h₆ : ki f (ki g g e) a, from ki₁₄ h₂, have h₇ : ki f (ki g g e) (ki a c d), from ki₇ h₆ h₅, have h₈ : ki f g (ki f e (ki a c d)), from ki₆ h₇, show ki f g (ki a e (ki a c d)), from ki₇ h₂ h₈ end ki end wr end hilbert end clfrags
771feab4541fc8789dad292261ce59e9c300e4f1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/ac_rfl.lean
86dc762d301ccd952b5f3e3f7ccb103c89a9b2f6
[ "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
4,710
lean
open Lean instance : IsAssociative (α := Nat) HAdd.hAdd := ⟨Nat.add_assoc⟩ instance : IsCommutative (α := Nat) HAdd.hAdd := ⟨Nat.add_comm⟩ instance : IsNeutral HAdd.hAdd 0 := ⟨Nat.zero_add, Nat.add_zero⟩ instance : IsAssociative (α := Nat) HMul.hMul := ⟨Nat.mul_assoc⟩ instance : IsCommutative (α := Nat) HMul.hMul := ⟨Nat.mul_comm⟩ instance : IsNeutral HMul.hMul 1 := ⟨Nat.one_mul, Nat.mul_one⟩ @[simp] theorem succ_le_succ_iff {x y : Nat} : x.succ ≤ y.succ ↔ x ≤ y := ⟨Nat.le_of_succ_le_succ, Nat.succ_le_succ⟩ @[simp] theorem add_le_add_right_iff {x y z : Nat} : x + z ≤ y + z ↔ x ≤ y := by induction z <;> simp_all [Nat.add_succ] set_option linter.unusedVariables false in theorem le_ext : ∀ {x y : Nat} (h : ∀ z, z ≤ x ↔ z ≤ y), x = y | 0, 0, _ => rfl | x+1, y+1, h => congrArg (· + 1) <| le_ext fun z => have := h (z + 1); by simp_all | 0, y+1, h => have := h 1; by simp_all | x+1, 0, h => have := h 1; by simp_all theorem le_or_le : ∀ (a b : Nat), a ≤ b ∨ b ≤ a | x+1, y+1 => by simp [le_or_le x y] | 0, 0 | x+1, 0 | 0, y+1 => by simp theorem le_of_not_le {a b : Nat} (h : ¬ a ≤ b) : b ≤ a := match le_or_le a b with | .inl ab => (h ab).rec | .inr ba => ba @[simp] theorem le_max_iff {x y z : Nat} : x ≤ max y z ↔ x ≤ y ∨ x ≤ z := by simp only [Nat.max_def] split · exact Iff.intro .inr fun | .inl xy => Nat.le_trans ‹_› ‹_› | .inr xz => ‹_› · exact Iff.intro .inl fun | .inl xy => ‹_› | .inr xz => Nat.le_trans ‹_› (le_of_not_le ‹_›) theorem or_assoc : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := by by_cases p <;> by_cases q <;> by_cases r <;> simp_all theorem or_comm : p ∨ q ↔ q ∨ p := by by_cases p <;> by_cases q <;> simp_all theorem max_assoc (n m k : Nat) : max (max n m) k = max n (max m k) := le_ext (by simp [or_assoc]) theorem max_comm (n m : Nat) : max n m = max m n := le_ext (by simp [or_comm]) theorem max_idem (n : Nat) : max n n = n := le_ext (by simp) theorem Nat.zero_max (n : Nat) : max 0 n = n := by simp [Nat.max_def] theorem Nat.max_zero (n : Nat) : max n 0 = n := by rw [max_comm, Nat.zero_max] instance : IsAssociative (α := Nat) max := ⟨max_assoc⟩ instance : IsCommutative (α := Nat) max := ⟨max_comm⟩ instance : IsIdempotent (α := Nat) max := ⟨max_idem⟩ instance : IsNeutral max 0 := ⟨Nat.zero_max, Nat.max_zero⟩ instance : IsAssociative And := ⟨λ p q r => propext ⟨λ ⟨⟨hp, hq⟩, hr⟩ => ⟨hp, hq, hr⟩, λ ⟨hp, hq, hr⟩ => ⟨⟨hp, hq⟩, hr⟩⟩⟩ instance : IsCommutative And := ⟨λ p q => propext ⟨λ ⟨hp, hq⟩ => ⟨hq, hp⟩, λ ⟨hq, hp⟩ => ⟨hp, hq⟩⟩⟩ instance : IsIdempotent And := ⟨λ p => propext ⟨λ ⟨hp, _⟩ => hp, λ hp => ⟨hp, hp⟩⟩⟩ instance : IsNeutral And True := ⟨λ p => propext ⟨λ ⟨_, hp⟩ => hp, λ hp => ⟨True.intro, hp⟩⟩, λ p => propext ⟨λ ⟨hp, _⟩ => hp, λ hp => ⟨hp, True.intro⟩⟩⟩ instance : IsAssociative Or := ⟨by simp [or_assoc]⟩ instance : IsCommutative Or := ⟨λ p q => propext ⟨λ hpq => hpq.elim Or.inr Or.inl, λ hqp => hqp.elim Or.inr Or.inl⟩⟩ instance : IsIdempotent Or := ⟨λ p => propext ⟨λ hp => hp.elim id id, Or.inl⟩⟩ instance : IsNeutral Or False := ⟨λ p => propext ⟨λ hfp => hfp.elim False.elim id, Or.inr⟩, λ p => propext ⟨λ hpf => hpf.elim id False.elim, Or.inl⟩⟩ example (x y z : Nat) : x + y + 0 + z = z + (x + y) := by ac_rfl example (x y z : Nat) : (x + y) * (0 + z) = (x + y) * z:= by ac_rfl example (x y z : Nat) : (x + y) * (0 + z) = 1 * z * (y + 0 + x) := by ac_rfl theorem ex₁ (x y z : Nat) : max (0 + (max x (max z (max (0 + 0) ((max 1 0) + 0 + 0) * y)))) y = max (max x y) z := by ac_rfl #print ex₁ example (x y : Nat) : 1 + 0 + 0 = 0 + 1 := by ac_rfl example (x y : Nat) : (x + y = 42) = (y + x = 42) := by ac_rfl example (x y : Nat) (P : Prop) : (x + y = 42 → P) = (y + x = 42 → P) := by ac_rfl inductive Vector (α : Type u) : Nat → Type u where | nil : Vector α 0 | cons : α → Vector α n → Vector α (n+1) def f (n : Nat) (xs : Vector α n) := xs -- Repro: Dependent types trigger incorrect proofs theorem ex₂ (n m : Nat) (xs : Vector α (n+m)) (ys : Vector α (m+n)) : (f (n+m) xs, f (m+n) ys, n+m) = (f (n+m) xs, f (m+n) ys, m+n) := by ac_rfl -- Repro: Binders also trigger invalid proofs theorem ex₃ (n : Nat) : (fun x => n + x) = (fun x => x + n) := by ac_rfl #print ex₃ -- Repro: the Prop universe doesn't work example (p q : Prop) : (p ∨ p ∨ q ∧ True) = (q ∨ p) := by ac_rfl -- Repro: missing withContext example : ∀ x : Nat, x = x := by intro x; ac_rfl
dda5da44e125c8c7b1268cfb992ee6874cce7766
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/group_power/basic.lean
131142b61217ccf432ae7c23218d819b6017b34d
[ "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
22,816
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.ordered_ring import deprecated.group /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. This module contains the definitions of `monoid.pow` and `group.pow` and their additive counterparts `nsmul` and `gsmul`, along with a few lemmas. Further lemmas can be found in `algebra.group_power.lemmas`. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer numbers, respectively. ## Implementation details We adopt the convention that `0^0 = 1`. This module provides the instance `has_pow ℕ ℕ` (via `monoid.has_pow`) and is imported by `data.nat.basic`, so it has to live low in the import hierarchy. Not all of its imports are needed yet; the intent is to move more lemmas here from `.lemmas` so that they are available in `data.nat.basic`, and the imports will be required then. -/ 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₂} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M | 0 := 1 | (n+1) := a * monoid.pow n /-- The scalar multiplication in an additive monoid. `n •ℕ a = a+a+...+a` n times. -/ def nsmul [has_add A] [has_zero A] (n : ℕ) (a : A) : A := @monoid.pow (multiplicative A) _ _ a n infix ` •ℕ `:70 := nsmul instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩ @[simp] lemma monoid.pow_eq_has_pow [monoid M] (a : M) (n : ℕ) : monoid.pow a n = a^n := rfl /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ namespace semiconj_by variables [monoid M] @[simp] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := nat.rec_on n (one_right a) $ λ n ihn, h.mul_right ihn end semiconj_by namespace commute variables [monoid M] {a b : M} @[simp] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) := (commute.refl a).pow_pow m n end commute section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl @[simp] theorem zero_nsmul (a : A) : 0 •ℕ a = 0 := rfl theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_nsmul (a : A) (n : ℕ) : (n+1) •ℕ a = a + n •ℕ a := rfl theorem pow_two (a : M) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_nsmul (a : A) : 2 •ℕ a = a + a := @pow_two (multiplicative A) _ a theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n theorem nsmul_add_comm' : ∀ (a : A) (n : ℕ), n •ℕ a + a = a + n •ℕ a := @pow_mul_comm' (multiplicative A) _ theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_nsmul' (a : A) (n : ℕ) : (n+1) •ℕ a = n •ℕ a + a := @pow_succ' (multiplicative A) _ _ _ theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [nat.add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', nat.add_assoc]] theorem add_nsmul : ∀ (a : A) (m n : ℕ), (m + n) •ℕ a = m •ℕ a + n •ℕ a := @pow_add (multiplicative A) _ @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 := by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw nat.mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [nat.mul_comm, pow_mul] theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) := @pow_mul' (multiplicative A) _ a m n theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_comm, nat.sub_add_cancel h] theorem nsmul_add_sub_nsmul (a : A) {m n : ℕ} (h : m ≤ n) : (m •ℕ a) + ((n - m) •ℕ a) = n •ℕ a := @pow_mul_pow_sub (multiplicative A) _ _ _ _ h theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, nat.sub_add_cancel h] theorem sub_nsmul_nsmul_add (a : A) {m n : ℕ} (h : m ≤ n) : ((n - m) •ℕ a) + (m •ℕ a) = n •ℕ a := @pow_sub_mul_pow (multiplicative A) _ _ _ _ h theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a := @pow_mul_comm (multiplicative A) _ theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := f.to_multiplicative.map_pow a n theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := (add_monoid_hom.of f).map_nsmul a n lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n theorem pow_bit0' (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n := by rw [pow_bit0, (commute.refl a).mul_pow] theorem bit0_nsmul' (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ (a + a) := @pow_bit0' (multiplicative A) _ _ _ theorem pow_bit1' (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a := by rw [bit1, pow_succ', pow_bit0'] theorem bit1_nsmul' : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ (a + a) + a := @pow_bit1' (multiplicative A) _ @[simp] theorem neg_pow_bit0 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit0 n) = a ^ (bit0 n) := by rw [pow_bit0', neg_mul_neg, pow_bit0'] @[simp] theorem neg_pow_bit1 [ring R] (a : R) (n : ℕ) : (- a) ^ (bit1 n) = - a ^ (bit1 n) := by simp only [bit1, pow_succ, neg_pow_bit0, neg_mul_eq_neg_mul] end monoid /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) := { map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ } lemma dvd_pow {x y : M} : ∀ {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0), x ∣ y^n | 0 hxy hn := (hn rfl).elim | (n+1) hxy hn := by { rw [pow_succ], exact dvd_mul_of_dvd_left hxy _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : G) : ℤ → G | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ /-- The scalar multiplication by integers on an additive group. This extends `nsmul` to negative integers with the definition `(-n) •ℤ a = -(n •ℕ a)`. -/ def gsmul (n : ℤ) (a : A) : A := @gpow (multiplicative A) _ a n instance group.has_pow : has_pow G ℤ := ⟨gpow⟩ infix ` •ℤ `:70 := gsmul @[simp] lemma group.gpow_eq_has_pow (a : G) (n : ℤ) : gpow a n = a ^ n := rfl section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a := @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) := @pow_inv_comm (multiplicative A) _ end nat @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a @[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, gpow_one, gpow_neg] @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := h.mul_pow n | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_comm, nat.sub_add_cancel h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n) lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel] lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← pow_two_sub_pow_two a b, sub_eq_zero] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[simp] lemma pow_eq_zero_iff [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨pow_eq_zero, _⟩, rintros rfl, exact zero_pow hn, end @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h lemma pow_abs [linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma abs_neg_one_pow [linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] section add_monoid variable [ordered_add_comm_monoid A] theorem nsmul_nonneg {a : A} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a | 0 := le_refl _ | (n+1) := add_nonneg H (nsmul_nonneg n) lemma nsmul_pos {a : A} (ha : 0 < a) {k : ℕ} (hk : 0 < k) : 0 < k •ℕ a := begin rcases nat.exists_eq_succ_of_ne_zero (ne_of_gt hk) with ⟨l, rfl⟩, clear hk, induction l with l IH, { simpa using ha }, { exact add_pos ha IH } end theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm ... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _ ... = m •ℕ a : by rw [← hk, add_nsmul] lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b | 0 := by simp | (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _) end add_monoid section add_group variable [ordered_add_comm_group A] theorem gsmul_nonneg {a : A} (H : 0 ≤ a) {n : ℤ} (hn : 0 ≤ n) : 0 ≤ n •ℤ a := begin lift n to ℕ using hn, apply nsmul_nonneg H end end add_group section cancel_add_monoid variable [ordered_cancel_add_comm_monoid A] theorem nsmul_lt_nsmul {a : A} {n m : ℕ} (ha : 0 < a) (h : n < m) : n •ℕ a < m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in begin have succ_swap : n.succ + k = n + k.succ := nat.succ_add n k, calc n •ℕ a = (n •ℕ a : A) + (0 : A) : (add_zero _).symm ... < n •ℕ a + (k.succ •ℕ a : A) : add_lt_add_left (nsmul_pos ha (nat.succ_pos k)) _ ... = m •ℕ a : by rw [← hk, succ_swap, add_nsmul] end end cancel_add_monoid section comm_semiring variables [comm_semiring R] lemma min_pow_dvd_add {n m : ℕ} {a b c : R} (ha : c ^ n ∣ a) (hb : c ^ m ∣ b) : c ^ (min n m) ∣ a + b := begin replace ha := dvd.trans (pow_dvd_pow c (min_le_left n m)) ha, replace hb := dvd.trans (pow_dvd_pow c (min_le_right n m)) hb, exact dvd_add ha hb end end comm_semiring namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := by { nontriviality, exact canonically_ordered_semiring.zero_lt_one } | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] @[simp] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := by { nontriviality, exact zero_lt_one } | (n+1) := mul_pos H (pow_pos _) @[simp] theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin nontriviality, have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 := by { rw pow_two, exact mul_self_nonneg _ } theorem pow_two_pos_of_ne_zero [linear_ordered_ring R] (a : R) (h : a ≠ 0) : 0 < a ^ 2 := begin nontriviality, exact lt_of_le_of_ne (pow_two_nonneg a) (pow_ne_zero 2 h).symm end @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl @[simp] lemma semiconj_by.gpow_right [group G] {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := h.pow_right n | -[1+n] := (h.pow_right n.succ).inv_right namespace commute variables [group G] {a b : G} @[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.gpow_right m @[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.gpow_right m).symm lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n variables (a) (m n : ℕ) @[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n @[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n @[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n end commute
f64c31a4cc214d586aae2574c4ee98867f9e65c8
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/matchtac.lean
ca8d2a49ae7f2bc4dd5760219081f6c60fdc4495
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,174
lean
new_frontend theorem tst1 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by { match h:xs with | [] => exact h₂ h | z::zs => { apply h₁ z zs; assumption } } theorem tst2 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by { match h:xs with | [] => ?nilCase | z::zs => ?consCase; case consCase exact h₁ z zs h; case nilCase exact h₂ h; } def tst3 {α β γ : Type} (h : α × β × γ) : β × α × γ := by { match h with | (a, b, c) => exact (b, a, c) } theorem tst4 {α : Type} {p : Prop} (xs : List α) (h₁ : (a : α) → (as : List α) → xs = a :: as → p) (h₂ : xs = [] → p) : p := by { match h:xs with | [] => _ | z::zs => _; case match_2 exact h₁ z zs h; exact h₂ h } theorem tst5 {p q r} (h : p ∨ q ∨ r) : r ∨ q ∨ p:= by { match h with | Or.inl h => exact Or.inr (Or.inr h) | Or.inr (Or.inl h) => ?c1 | Or.inr (Or.inr h) => ?c2; case c2 { apply Or.inl; assumption }; { apply Or.inr; apply Or.inl; assumption } }
9b5d6730c6f93f4f9bcbae9af2d29cb3499e8d9d
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/limits/shapes/kernels.lean
dde8d7e139e4b0efdbcf7d06a1a366b76a9b52c3
[ "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,060
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.zero /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.) The basic definitions are * `kernel : (X ⟶ Y) → C` * `kernel.ι : kernel f ⟶ X` * `kernel.condition : kernel.ι f ≫ f = 0` and * `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, we prove * `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.eq_zero_of_epi_kernel`: if `kernel.ι f` is an epimorphism, then `f = 0` * `kernel.of_mono`: the kernel of a monomorphism is the zero object * `kernel.lift_mono`: the lift of a monomorphism `k : W ⟶ X` such that `k ≫ f = 0` is still a monomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism * `kernel.ι_of_zero`: `kernel.ι (0 : X ⟶ Y)` is an isomorphism and the corresponding dual statements. ## Future work * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u u' open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables [has_zero_morphisms C] /-- A morphism `f` has a kernel if the functor `parallel_pair f 0` has a limit. -/ abbreviation has_kernel {X Y : C} (f : X ⟶ Y) : Prop := has_limit (parallel_pair f 0) /-- A morphism `f` has a cokernel if the functor `parallel_pair f 0` has a colimit. -/ abbreviation has_cokernel {X Y : C} (f : X ⟶ Y) : Prop := has_colimit (parallel_pair f 0) variables {X Y : C} (f : X ⟶ Y) section /-- A kernel fork is just a fork where the second morphism is a zero morphism. -/ abbreviation kernel_fork := fork f 0 variables {f} @[simp, reassoc] lemma kernel_fork.condition (s : kernel_fork f) : fork.ι s ≫ f = 0 := by erw [fork.condition, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.app_one (s : kernel_fork f) : s.π.app one = 0 := by rw [←fork.app_zero_left, kernel_fork.condition] /-- A morphism `ι` satisfying `ι ≫ f = 0` determines a kernel fork over `f`. -/ abbreviation kernel_fork.of_ι {Z : C} (ι : Z ⟶ X) (w : ι ≫ f = 0) : kernel_fork f := fork.of_ι ι $ by rw [w, has_zero_morphisms.comp_zero] @[simp] lemma kernel_fork.ι_of_ι {X Y P : C} (f : X ⟶ Y) (ι : P ⟶ X) (w : ι ≫ f = 0) : fork.ι (kernel_fork.of_ι ι w) = ι := rfl section local attribute [tidy] tactic.case_bash /-- Every kernel fork `s` is isomorphic (actually, equal) to `fork.of_ι (fork.ι s) _`. -/ def iso_of_ι (s : fork f 0) : s ≅ fork.of_ι (fork.ι s) (fork.condition s) := cones.ext (iso.refl _) $ by tidy /-- If `ι = ι'`, then `fork.of_ι ι _` and `fork.of_ι ι' _` are isomorphic. -/ def of_ι_congr {P : C} {ι ι' : P ⟶ X} {w : ι ≫ f = 0} (h : ι = ι') : kernel_fork.of_ι ι w ≅ kernel_fork.of_ι ι' (by rw [←h, w]) := cones.ext (iso.refl _) $ by tidy /-- If `F` is an equivalence, then applying `F` to a diagram indexing a (co)kernel of `f` yields the diagram indexing the (co)kernel of `F.map f`. -/ def comp_nat_iso {D : Type u'} [category.{v} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] : parallel_pair f 0 ⋙ F ≅ parallel_pair (F.map f) 0 := nat_iso.of_components (λ j, match j with | zero := iso.refl _ | one := iso.refl _ end) $ by tidy end /-- If `s` is a limit kernel fork and `k : W ⟶ X` satisfies ``k ≫ f = 0`, then there is some `l : W ⟶ s.X` such that `l ≫ fork.ι s = k`. -/ def kernel_fork.is_limit.lift' {s : kernel_fork f} (hs : is_limit s) {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ s.X // l ≫ fork.ι s = k} := ⟨hs.lift $ kernel_fork.of_ι _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a kernel fork is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : kernel_fork f) (lift : Π (s : kernel_fork f), s.X ⟶ t.X) (fac : ∀ (s : kernel_fork f), lift s ≫ t.ι = s.ι) (uniq : ∀ (s : kernel_fork f) (m : s.X ⟶ t.X) (w : m ≫ t.ι = s.ι), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, by { cases j, { exact fac s, }, { simp, }, }, uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.zero), } /-- This is a more convenient formulation to show that a `kernel_fork` constructed using `kernel_fork.of_ι` is a limit cone. -/ def is_limit.of_ι {W : C} (g : W ⟶ X) (eq : g ≫ f = 0) (lift : Π {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), W' ⟶ W) (fac : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0), lift g' eq' ≫ g = g') (uniq : ∀ {W' : C} (g' : W' ⟶ X) (eq' : g' ≫ f = 0) (m : W' ⟶ W) (w : m ≫ g = g'), m = lift g' eq') : is_limit (kernel_fork.of_ι g eq) := is_limit_aux _ (λ s, lift s.ι s.condition) (λ s, fac s.ι s.condition) (λ s, uniq s.ι s.condition) end section variables [has_kernel f] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0 @[simp] lemma equalizer_as_kernel : equalizer.ι f 0 = kernel.ι f := rfl @[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 := kernel_fork.condition _ /-- Given any morphism `k : W ⟶ X` satisfying `k ≫ f = 0`, `k` factors through `kernel.ι f` via `kernel.lift : W ⟶ kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f := limit.lift (parallel_pair f 0) (kernel_fork.of_ι k h) @[simp, reassoc] lemma kernel.lift_ι {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : kernel.lift f k h ≫ kernel.ι f = k := limit.lift_π _ _ @[simp] lemma kernel.lift_zero {W : C} {h} : kernel.lift f (0 : W ⟶ X) h = 0 := by { ext, simp, } instance kernel.lift_mono {W : C} (k : W ⟶ X) (h : k ≫ f = 0) [mono k] : mono (kernel.lift f k h) := ⟨λ Z g g' w, begin replace w := w =≫ kernel.ι f, simp only [category.assoc, kernel.lift_ι] at w, exact (cancel_mono k).1 w, end⟩ /-- Any morphism `k : W ⟶ X` satisfying `k ≫ f = 0` induces a morphism `l : W ⟶ kernel f` such that `l ≫ kernel.ι f = k`. -/ def kernel.lift' {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : {l : W ⟶ kernel f // l ≫ kernel.ι f = k} := ⟨kernel.lift f k h, kernel.lift_ι _ _ _⟩ /-- Every kernel of the zero morphism is an isomorphism -/ instance kernel.ι_zero_is_iso : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ lemma eq_zero_of_epi_kernel [epi (kernel.ι f)] : f = 0 := (cancel_epi (kernel.ι f)).1 (by simp) /-- The kernel of a zero morphism is isomorphic to the source. -/ def kernel_zero_iso_source : kernel (0 : X ⟶ Y) ≅ X := equalizer.iso_source_of_self 0 @[simp] lemma kernel_zero_iso_source_hom : kernel_zero_iso_source.hom = kernel.ι (0 : X ⟶ Y) := rfl @[simp] lemma kernel_zero_iso_source_inv : kernel_zero_iso_source.inv = kernel.lift (0 : X ⟶ Y) (𝟙 X) (by simp) := rfl /-- If two morphisms are known to be equal, then their kernels are isomorphic. -/ def kernel_iso_of_eq {f g : X ⟶ Y} [has_kernel f] [has_kernel g] (h : f = g) : kernel f ≅ kernel g := has_limit.iso_of_nat_iso (by simp[h]) @[simp] lemma kernel_iso_of_eq_refl {h : f = f} : kernel_iso_of_eq h = iso.refl (kernel f) := by { ext, simp [kernel_iso_of_eq], } @[simp] lemma kernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_kernel f] [has_kernel g] [has_kernel h] (w₁ : f = g) (w₂ : g = h) : kernel_iso_of_eq w₁ ≪≫ kernel_iso_of_eq w₂ = kernel_iso_of_eq (w₁.trans w₂) := by { unfreezingI { induction w₁, induction w₂, }, ext, simp [kernel_iso_of_eq], } variables {f} lemma kernel_not_epi_of_nonzero (w : f ≠ 0) : ¬epi (kernel.ι f) := λ I, by exactI w (eq_zero_of_epi_kernel f) lemma kernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (kernel.ι f)) → false := λ I, kernel_not_epi_of_nonzero w $ by { resetI, apply_instance } /-- When `g` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `f`. -/ def kernel_comp_is_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [has_kernel f] [is_iso g] : kernel (f ≫ g) ≅ kernel f := { hom := kernel.lift _ (kernel.ι _) (by { rw [←cancel_mono g], simp, }), inv := kernel.lift _ (kernel.ι _) (by simp), } @[simp] lemma kernel_comp_is_iso_hom_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [has_kernel f] [is_iso g] : (kernel_comp_is_iso f g).hom ≫ kernel.ι f = kernel.ι (f ≫ g) := by simp [kernel_comp_is_iso] @[simp] lemma kernel_comp_is_iso_inv_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [has_kernel f] [is_iso g] : (kernel_comp_is_iso f g).inv ≫ kernel.ι (f ≫ g) = kernel.ι f := by simp [kernel_comp_is_iso] /-- When `f` is an isomorphism, the kernel of `f ≫ g` is isomorphic to the kernel of `g`. -/ def kernel_is_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : kernel (f ≫ g) ≅ kernel g := { hom := kernel.lift _ (kernel.ι _ ≫ f) (by simp), inv := kernel.lift _ (kernel.ι _ ≫ inv f) (by simp), } @[simp] lemma kernel_is_iso_comp_hom_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : (kernel_is_iso_comp f g).hom ≫ kernel.ι g = kernel.ι (f ≫ g) ≫ f := by simp [kernel_is_iso_comp] @[simp] lemma kernel_is_iso_comp_inv_comp_kernel_ι {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_kernel (f ≫ g)] [is_iso f] [has_kernel g] : (kernel_is_iso_comp f g).inv ≫ kernel.ι (f ≫ g) = kernel.ι g ≫ (inv f) := by simp [kernel_is_iso_comp] end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_cone : cone (parallel_pair f 0) := { X := 0, π := { app := λ j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) := fork.is_limit.mk _ (λ s, 0) (λ s, by { erw zero_comp, convert (zero_of_comp_mono f _).symm, exact kernel_fork.condition _ }) (λ _ _ _, zero_of_to_zero _) /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_kernel f] [mono f] : kernel f ≅ 0 := functor.map_iso (cones.forget _) $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ι_of_mono [has_kernel f] [mono f] : kernel.ι f = 0 := zero_of_source_iso_zero _ (kernel.of_mono f) end has_zero_object section transport /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then any kernel of `f` is a kernel of `l`.-/ def is_kernel.of_comp_iso {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) {s : kernel_fork f} (hs : is_limit s) : is_limit (kernel_fork.of_ι (fork.ι s) $ show fork.ι s ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := fork.is_limit.mk _ (λ s, hs.lift $ kernel_fork.of_ι (fork.ι s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply fork.is_limit.hom_ext hs, simpa using h walking_parallel_pair.zero }) /-- If `i` is an isomorphism such that `l ≫ i.hom = f`, then the kernel of `f` is a kernel of `l`.-/ def kernel.of_comp_iso [has_kernel f] {Z : C} (l : X ⟶ Z) (i : Z ≅ Y) (h : l ≫ i.hom = f) : is_limit (kernel_fork.of_ι (kernel.ι f) $ show kernel.ι f ≫ l = 0, by simp [←i.comp_inv_eq.2 h.symm]) := is_kernel.of_comp_iso f l i h $ limit.is_limit _ /-- If `s` is any limit kernel cone over `f` and if `i` is an isomorphism such that `i.hom ≫ s.ι = l`, then `l` is a kernel of `f`. -/ def is_kernel.iso_kernel {Z : C} (l : Z ⟶ X) {s : kernel_fork f} (hs : is_limit s) (i : Z ≅ s.X) (h : i.hom ≫ fork.ι s = l) : is_limit (kernel_fork.of_ι l $ show l ≫ f = 0, by simp [←h]) := is_limit.of_iso_limit hs $ cones.ext i.symm $ λ j, by { cases j, { exact (iso.eq_inv_comp i).2 h }, { simp } } /-- If `i` is an isomorphism such that `i.hom ≫ kernel.ι f = l`, then `l` is a kernel of `f`. -/ def kernel.iso_kernel [has_kernel f] {Z : C} (l : Z ⟶ X) (i : Z ≅ kernel f) (h : i.hom ≫ kernel.ι f = l) : is_limit (kernel_fork.of_ι l $ by simp [←h]) := is_kernel.iso_kernel f l (limit.is_limit _) i h end transport section variables (X Y) /-- The kernel morphism of a zero morphism is an isomorphism -/ def kernel.ι_of_zero : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ end section /-- A cokernel cofork is just a cofork where the second morphism is a zero morphism. -/ abbreviation cokernel_cofork := cofork f 0 variables {f} @[simp, reassoc] lemma cokernel_cofork.condition (s : cokernel_cofork f) : f ≫ cofork.π s = 0 := by rw [cofork.condition, zero_comp] @[simp] lemma cokernel_cofork.app_zero (s : cokernel_cofork f) : s.ι.app zero = 0 := by rw [←cofork.left_app_one, cokernel_cofork.condition] /-- A morphism `π` satisfying `f ≫ π = 0` determines a cokernel cofork on `f`. -/ abbreviation cokernel_cofork.of_π {Z : C} (π : Y ⟶ Z) (w : f ≫ π = 0) : cokernel_cofork f := cofork.of_π π $ by rw [w, zero_comp] @[simp] lemma cokernel_cofork.π_of_π {X Y P : C} (f : X ⟶ Y) (π : Y ⟶ P) (w : f ≫ π = 0) : cofork.π (cokernel_cofork.of_π π w) = π := rfl /-- Every cokernel cofork `s` is isomorphic (actually, equal) to `cofork.of_π (cofork.π s) _`. -/ def iso_of_π (s : cofork f 0) : s ≅ cofork.of_π (cofork.π s) (cofork.condition s) := cocones.ext (iso.refl _) $ λ j, by cases j; tidy /-- If `π = π'`, then `cokernel_cofork.of_π π _` and `cokernel_cofork.of_π π' _` are isomorphic. -/ def of_π_congr {P : C} {π π' : Y ⟶ P} {w : f ≫ π = 0} (h : π = π') : cokernel_cofork.of_π π w ≅ cokernel_cofork.of_π π' (by rw [←h, w]) := cocones.ext (iso.refl _) $ λ j, by cases j; tidy /-- If `s` is a colimit cokernel cofork, then every `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : s.X ⟶ W` such that `cofork.π s ≫ l = k`. -/ def cokernel_cofork.is_colimit.desc' {s : cokernel_cofork f} (hs : is_colimit s) {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : s.X ⟶ W // cofork.π s ≫ l = k} := ⟨hs.desc $ cokernel_cofork.of_π _ h, hs.fac _ _⟩ /-- This is a slightly more convenient method to verify that a cokernel cofork is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : cokernel_cofork f) (desc : Π (s : cokernel_cofork f), t.X ⟶ s.X) (fac : ∀ (s : cokernel_cofork f), t.π ≫ desc s = s.π) (uniq : ∀ (s : cokernel_cofork f) (m : t.X ⟶ s.X) (w : t.π ≫ m = s.π), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, by { cases j, { simp, }, { exact fac s, }, }, uniq' := λ s m w, uniq s m (w limits.walking_parallel_pair.one), } /-- This is a more convenient formulation to show that a `cokernel_cofork` constructed using `cokernel_cofork.of_π` is a limit cone. -/ def is_colimit.of_π {Z : C} (g : Y ⟶ Z) (eq : f ≫ g = 0) (desc : Π {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), Z ⟶ Z') (fac : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0), g ≫ desc g' eq' = g') (uniq : ∀ {Z' : C} (g' : Y ⟶ Z') (eq' : f ≫ g' = 0) (m : Z ⟶ Z') (w : g ≫ m = g'), m = desc g' eq') : is_colimit (cokernel_cofork.of_π g eq) := is_colimit_aux _ (λ s, desc s.π s.condition) (λ s, fac s.π s.condition) (λ s, uniq s.π s.condition) end section variables [has_cokernel f] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0 @[simp] lemma coequalizer_as_cokernel : coequalizer.π f 0 = cokernel.π f := rfl @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 := cokernel_cofork.condition _ /-- Given any morphism `k : Y ⟶ W` such that `f ≫ k = 0`, `k` factors through `cokernel.π f` via `cokernel.desc : cokernel f ⟶ W`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W := colimit.desc (parallel_pair f 0) (cokernel_cofork.of_π k h) @[simp, reassoc] lemma cokernel.π_desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel.π f ≫ cokernel.desc f k h = k := colimit.ι_desc _ _ @[simp] lemma cokernel.desc_zero {W : C} {h} : cokernel.desc f (0 : Y ⟶ W) h = 0 := by { ext, simp, } instance cokernel.desc_epi {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) [epi k] : epi (cokernel.desc f k h) := ⟨λ Z g g' w, begin replace w := cokernel.π f ≫= w, simp only [cokernel.π_desc_assoc] at w, exact (cancel_epi k).1 w, end⟩ /-- Any morphism `k : Y ⟶ W` satisfying `f ≫ k = 0` induces `l : cokernel f ⟶ W` such that `cokernel.π f ≫ l = k`. -/ def cokernel.desc' {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : {l : cokernel f ⟶ W // cokernel.π f ≫ l = k} := ⟨cokernel.desc f k h, cokernel.π_desc _ _ _⟩ /-- The cokernel of the zero morphism is an isomorphism -/ instance cokernel.π_zero_is_iso : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ lemma eq_zero_of_mono_cokernel [mono (cokernel.π f)] : f = 0 := (cancel_mono (cokernel.π f)).1 (by simp) /-- The cokernel of a zero morphism is isomorphic to the target. -/ def cokernel_zero_iso_target : cokernel (0 : X ⟶ Y) ≅ Y := coequalizer.iso_target_of_self 0 @[simp] lemma cokernel_zero_iso_target_hom : cokernel_zero_iso_target.hom = cokernel.desc (0 : X ⟶ Y) (𝟙 Y) (by simp) := rfl @[simp] lemma cokernel_zero_iso_target_inv : cokernel_zero_iso_target.inv = cokernel.π (0 : X ⟶ Y) := rfl /-- If two morphisms are known to be equal, then their cokernels are isomorphic. -/ def cokernel_iso_of_eq {f g : X ⟶ Y} [has_cokernel f] [has_cokernel g] (h : f = g) : cokernel f ≅ cokernel g := has_colimit.iso_of_nat_iso (by simp[h]) @[simp] lemma cokernel_iso_of_eq_refl {h : f = f} : cokernel_iso_of_eq h = iso.refl (cokernel f) := by { ext, simp [cokernel_iso_of_eq], } @[simp] lemma cokernel_iso_of_eq_trans {f g h : X ⟶ Y} [has_cokernel f] [has_cokernel g] [has_cokernel h] (w₁ : f = g) (w₂ : g = h) : cokernel_iso_of_eq w₁ ≪≫ cokernel_iso_of_eq w₂ = cokernel_iso_of_eq (w₁.trans w₂) := by { unfreezingI { induction w₁, induction w₂, }, ext, simp [cokernel_iso_of_eq], } variables {f} lemma cokernel_not_mono_of_nonzero (w : f ≠ 0) : ¬mono (cokernel.π f) := λ I, by exactI w (eq_zero_of_mono_cokernel f) lemma cokernel_not_iso_of_nonzero (w : f ≠ 0) : (is_iso (cokernel.π f)) → false := λ I, cokernel_not_mono_of_nonzero w $ by { resetI, apply_instance } /-- When `g` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `f`. -/ def cokernel_comp_is_iso {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel (f ≫ g) ≅ cokernel f := { hom := cokernel.desc _ (inv g ≫ cokernel.π f) (by simp), inv := cokernel.desc _ (g ≫ cokernel.π (f ≫ g)) (by rw [←category.assoc, cokernel.condition]), } @[simp] lemma cokernel_π_comp_cokernel_comp_is_iso_hom {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel.π (f ≫ g) ≫ (cokernel_comp_is_iso f g).hom = inv g ≫ cokernel.π f := by simp [cokernel_comp_is_iso] @[simp] lemma cokernel_π_comp_cokernel_comp_is_iso_inv {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [has_cokernel f] [is_iso g] : cokernel.π f ≫ (cokernel_comp_is_iso f g).inv = g ≫ cokernel.π (f ≫ g) := by simp [cokernel_comp_is_iso] /-- When `f` is an isomorphism, the cokernel of `f ≫ g` is isomorphic to the cokernel of `g`. -/ def cokernel_is_iso_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] : cokernel (f ≫ g) ≅ cokernel g := { hom := cokernel.desc _ (cokernel.π g) (by simp), inv := cokernel.desc _ (cokernel.π (f ≫ g)) (by { rw [←cancel_epi f, ←category.assoc], simp, }), } @[simp] lemma cokernel_π_comp_cokernel_is_iso_comp_hom {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] : cokernel.π (f ≫ g) ≫ (cokernel_is_iso_comp f g).hom = cokernel.π g := by simp [cokernel_is_iso_comp] @[simp] lemma cokernel_π_comp_cokernel_is_iso_comp_inv {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_cokernel (f ≫ g)] [is_iso f] [has_cokernel g] : cokernel.π g ≫ (cokernel_is_iso_comp f g).inv = cokernel.π (f ≫ g) := by simp [cokernel_is_iso_comp] end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cocone : cocone (parallel_pair f 0) := { X := 0, ι := { app := λ j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) := cofork.is_colimit.mk _ (λ s, 0) (λ s, by { erw zero_comp, convert (zero_of_epi_comp f _).symm, exact cokernel_cofork.condition _ }) (λ _ _ _, zero_of_from_zero _) /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_cokernel f] [epi f] : cokernel f ≅ 0 := functor.map_iso (cocones.forget _) $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism of an epimorphism is a zero morphism -/ lemma cokernel.π_of_epi [has_cokernel f] [epi f] : cokernel.π f = 0 := zero_of_target_iso_zero _ (cokernel.of_epi f) end has_zero_object section has_image /-- The cokernel of the image inclusion of a morphism `f` is isomorphic to the cokernel of `f`. (This result requires that the factorisation through the image is an epimorphism. This holds in any category with equalizers.) -/ @[simps] def cokernel_image_ι {X Y : C} (f : X ⟶ Y) [has_image f] [has_cokernel (image.ι f)] [has_cokernel f] [epi (factor_thru_image f)] : cokernel (image.ι f) ≅ cokernel f := { hom := cokernel.desc _ (cokernel.π f) begin have w := cokernel.condition f, conv at w { to_lhs, congr, rw ←image.fac f, }, rw [←has_zero_morphisms.comp_zero (limits.factor_thru_image f), category.assoc, cancel_epi] at w, exact w, end, inv := cokernel.desc _ (cokernel.π _) begin conv { to_lhs, congr, rw ←image.fac f, }, rw [category.assoc, cokernel.condition, has_zero_morphisms.comp_zero], end, } end has_image section variables (X Y) /-- The cokernel of a zero morphism is an isomorphism -/ def cokernel.π_of_zero : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ end section has_zero_object variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ instance kernel.of_cokernel_of_epi [has_cokernel f] [has_kernel (cokernel.π f)] [epi f] : is_iso (kernel.ι (cokernel.π f)) := equalizer.ι_of_eq $ cokernel.π_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ instance cokernel.of_kernel_of_mono [has_kernel f] [has_cokernel (kernel.ι f)] [mono f] : is_iso (cokernel.π (kernel.ι f)) := coequalizer.π_of_eq $ kernel.ι_of_mono f end has_zero_object section transport /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then any cokernel of `f` is a cokernel of `l`. -/ def is_cokernel.of_iso_comp {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) {s : cokernel_cofork f} (hs : is_colimit s) : is_colimit (cokernel_cofork.of_π (cofork.π s) $ show l ≫ cofork.π s = 0, by simp [i.eq_inv_comp.2 h]) := cofork.is_colimit.mk _ (λ s, hs.desc $ cokernel_cofork.of_π (cofork.π s) $ by simp [←h]) (λ s, by simp) (λ s m h, by { apply cofork.is_colimit.hom_ext hs, simpa using h walking_parallel_pair.one }) /-- If `i` is an isomorphism such that `i.hom ≫ l = f`, then the cokernel of `f` is a cokernel of `l`. -/ def cokernel.of_iso_comp [has_cokernel f] {Z : C} (l : Z ⟶ Y) (i : X ≅ Z) (h : i.hom ≫ l = f) : is_colimit (cokernel_cofork.of_π (cokernel.π f) $ show l ≫ cokernel.π f = 0, by simp [i.eq_inv_comp.2 h]) := is_cokernel.of_iso_comp f l i h $ colimit.is_colimit _ /-- If `s` is any colimit cokernel cocone over `f` and `i` is an isomorphism such that `s.π ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def is_cokernel.cokernel_iso {Z : C} (l : Y ⟶ Z) {s : cokernel_cofork f} (hs : is_colimit s) (i : s.X ≅ Z) (h : cofork.π s ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ show f ≫ l = 0, by simp [←h]) := is_colimit.of_iso_colimit hs $ cocones.ext i $ λ j, by { cases j, { simp }, { exact h } } /-- If `i` is an isomorphism such that `cokernel.π f ≫ i.hom = l`, then `l` is a cokernel of `f`. -/ def cokernel.cokernel_iso [has_cokernel f] {Z : C} (l : Y ⟶ Z) (i : cokernel f ≅ Z) (h : cokernel.π f ≫ i.hom = l) : is_colimit (cokernel_cofork.of_π l $ by simp [←h]) := is_cokernel.cokernel_iso f l (colimit.is_colimit _) i h end transport end category_theory.limits namespace category_theory.limits variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] /-- `has_kernels` represents the existence of kernels for every morphism. -/ class has_kernels : Prop := (has_limit : Π {X Y : C} (f : X ⟶ Y), has_kernel f) /-- `has_cokernels` represents the existence of cokernels for every morphism. -/ class has_cokernels : Prop := (has_colimit : Π {X Y : C} (f : X ⟶ Y), has_cokernel f) attribute [instance, priority 100] has_kernels.has_limit has_cokernels.has_colimit @[priority 100] instance has_kernels_of_has_equalizers [has_equalizers C] : has_kernels C := { has_limit := by apply_instance } @[priority 100] instance has_cokernels_of_has_coequalizers [has_coequalizers C] : has_cokernels C := { has_colimit := by apply_instance } end category_theory.limits
ff6af8f7a389243026383b472ed9e14acdb5d14f
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/algebra/big_operators.lean
4ac1818eff8bec7226dfda1400386f39dedd9789
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
27,659
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 Some big operators for lists and finite sets. -/ import data.list.basic data.list.perm data.finset import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive finset.sum] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1 @[to_additive finset.sum_eq_fold] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive finset.sum_empty] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive finset.sum_insert] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive finset.sum_singleton] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive finset.sum_const_zero] prod_const_one @[simp, to_additive finset.sum_image] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[congr, to_additive finset.sum_congr] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive finset.sum_union_inter] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive finset.sum_union] lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, h]; exact (mul_one _).symm @[to_additive finset.sum_sdiff] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h] @[to_additive finset.sum_bind] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅, from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have t x ∩ finset.bind s t = ∅, from eq_empty_of_forall_not_mem $ assume a, by rw [mem_inter, mem_bind]; rintro ⟨h₁, y, hys, hy₂⟩; exact eq_empty_iff_forall_not_mem.1 (hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) (assume h, hxs (h.symm ▸ hys))) _ (mem_inter_of_mem h₁ hy₂), by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive finset.sum_product] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind (λ x hx y hy h, eq_empty_of_forall_not_mem _)], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [mem_inter, mem_image], rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩, apply h, cc end @[to_additive finset.sum_sigma] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_image]; rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive finset.sum_image'] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine disjoint_iff_inter_eq_empty.1 (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive finset.sum_add_distrib] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive finset.sum_comm] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] @[to_additive finset.sum_hom] lemma prod_hom [comm_monoid γ] (g : β → γ) (h₁ : g 1 = 1) (h₂ : ∀x y, g (x * y) = g x * g y) : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw [h₁]; refl) (fold_hom h₂) @[to_additive finset.sum_hom_rel] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive finset.sum_subset] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive finset.sum_eq_single] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive finset.sum_attach] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive finset.sum_bij] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (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.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[to_additive finset.sum_bij_ne_zero] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive finset.exists_ne_zero_of_sum_ne_zero] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive finset.sum_range_succ] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive finset.sum_involution] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive finset.sum_eq_zero] lemma prod_eq_one [comm_monoid β] {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive finset.sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive finset.sum_const] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive finset.sum_range_succ'] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _ nat.cast_zero nat.cast_add).symm section comm_group variables [comm_group β] @[simp, to_additive finset.sum_neg_distrib] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv one_inv mul_inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → t x ∩ t y = ∅) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := begin refine (finset.sum_hom (gsmul z) _ _).symm, exact gsmul_zero _, assume x y, exact gsmul_add _ _ _ end end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section ordered_cancel_comm_monoid variables [decidable_eq α] [ordered_cancel_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_le_zero (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) end ordered_cancel_comm_monoid section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b) (zero_mul b) (assume a c, add_mul a c b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x) (mul_zero b) (assume a c, mul_add b a c)).symm end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, image (pi.cons s a x) (pi s t) ∩ image (pi.cons s a y) (pi s t) = ∅, { assume x hx y hy h, apply eq_empty_of_forall_not_mem, simp only [mem_inter, mem_image], rintro p₁ ⟨⟨p₂, hp, eq⟩, ⟨p₃, hp₃, rfl⟩⟩, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum' : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum' (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum' h) lemma sum_le_zero' (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum' h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ zero_le_sum' $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (zero_le_sum' this), forall_mem_insert, ih this] lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] [@decidable_rel β (≤)] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_le_zero' $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section discrete_linear_ordered_field variables [discrete_linear_ordered_field α] [decidable_eq β] lemma abs_sum_le_sum_abs {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := finset.induction_on s (le_of_eq abs_zero) $ assume a s has ih, calc abs (sum (insert a s) f) ≤ abs (f a) + abs (sum s f) : by rw sum_insert has; exact abs_add_le_abs_add_abs _ _ ... ≤ abs (f a) + s.sum (λa, abs (f a)) : add_le_add (le_refl _) ih ... ≤ sum (insert a s) (λ (a : β), abs (f a)) : by rw sum_insert has end discrete_linear_ordered_field @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*, - range_succ] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp * end finset section group open list variables [group α] [group β] @[to_additive is_add_group_hom.sum] theorem is_group_hom.prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_group_hom.mul f, is_group_hom.one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.one f, simp only [prod_cons, is_group_anti_hom.mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.multiset_sum] lemma is_group_hom.multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.prod f l] @[to_additive is_add_group_hom.finset_sum] lemma is_group_hom.finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := ⟨assume a b, by simp only [λc, is_group_hom.mul (f c), finset.prod_mul_distrib]⟩ attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
ec159a026a87c0fb9a6ec04b388d7051ec95985d
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level7.lean
a28137add97ab54b2dca0fe95c10641ec6b11177
[ "Apache-2.0" ]
permissive
agusakov/mathematics_in_lean_game
76e455a688a8826b05160c16c0490b9e3d39f071
ad45fd42148f2203b973537adec7e8a48677ba2a
refs/heads/master
1,666,147,402,274
1,592,119,137,000
1,592,119,137,000
272,111,226
0
0
null
null
null
null
UTF-8
Lean
false
false
1,586
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- #Calculating ## Level 7: Hypotheses In the Lean editor mode, when a cursor is in the middle of a tactic proof, Lean reports on the current *proof state*. A typical proof state in Lean might look as follows: ```1 goal x y : ℕ, h₁ : prime x, h₂ : ¬even x, h₃ : y > x ⊢ y ≥ 4``` The lines before the one that begins with `⊢` denote the *context*: they are the objects and assumptions currently at play. In this example, these include two objects, `x` and `y`, each a natural number. They also include three assumptions, labelled `h₁`, `h₂`, and `h₃`. In Lean, everything in a context is labelled with an identifier. You can type these subscripted labels as `h\1`, `h\2`, and `h\3`, but any legal identifiers would do: you can use `h1`, `h2`, `h3` instead, or `foo`, `bar`, and `baz`. The last line represents the *goal*, that is, the fact to be proved. Sometimes people use *target* for the fact to be proved, and *goal* for the combination of the context and the target. In practice, the intended meaning is usually clear. You an also use `rw` with facts from the local context. -/ /- Lemma : no-side-bar For all natural numbers $a$, we have $$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$ -/ lemma example7 (a b c d e f : ℝ) (h : a * b = c * d) (h' : e = f) : a * (b * e) = c * (d * f) := begin [maths_in_lean_game] rw h', rw ←mul_assoc, rw h, rw mul_assoc end end calculating -- hide
21d2d59fcd7c403e68d08597a7ff84f3364c7251
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/ring_theory/ideal/operations.lean
68651882e6796d3f63bba2e17502d5e01e651b1a
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,990
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.nat.choose.sum import data.equiv.ring import algebra.algebra.operations import ring_theory.ideal.basic /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩ /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) variables {M' : Type w} [add_comm_group M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end /-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/ def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := begin refine quotient.lift (⨅ i, f i) _ _, { convert @@pi.ring_hom (λ i, quotient (f i)) (λ i, ring.to_semiring) ring.to_semiring (λ i, quotient.mk (f i)) }, { intros r hr, rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) } end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder section mul_and_radical variables {R : Type u} {ι : Type*} [comm_ring R] variables {I J K L: ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, ideal.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, ideal.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span,} lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton],} theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right hri, J.mul_mem_left hsj⟩ theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := begin classical, refine s.induction_on _ _, { rw [finset.prod_empty, finset.inf_empty], exact le_top }, intros a s has ih, rw [finset.prod_insert has, finset.inf_insert], exact le_trans mul_le_inf (inf_le_inf (le_refl _) ih) end theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma mul_eq_bot {R : Type*} [integral_domain R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right $ I.mul_mem_left $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right hyni) (λ hmc, I.mul_mem_right $ I.mul_mem_right $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, show (r * s)^n ∈ I, from (mul_pow r s n).symm ▸ I.mul_mem_left hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right hrm, (pow_add r m n).symm ▸ J.mul_mem_left hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right hpm) (m.add_mem (m.mul_mem_left hfm) (m.mul_mem_left hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_integral_domain {R : Type u} [integral_domain R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_map_top, submodule.map_id] variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : radical_mul _ _ ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.2 $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne: s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := suffices s.prod f ≤ P → ∃ i ∈ s, f i ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans prod_le_inf $ le_trans (finset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := hne.bex, obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ s = insert b t, from ⟨s.erase b, s.not_mem_erase b, (finset.insert_erase hb).symm⟩, revert hbt, refine t.induction_on _ _, { simp only [finset.not_mem_empty, insert_emptyc_eq, exists_prop, finset.prod_singleton, imp_self, exists_eq_left, not_false_iff, finset.mem_singleton] }, intros a s has ih hbs h, have : a ∉ insert b s, { contrapose! has, apply finset.mem_of_mem_insert_of_ne has, rintro rfl, contradiction }, rw [finset.insert.comm, finset.prod_insert this, hp.mul_le] at h, rw finset.insert.comm, cases h, { exact ⟨a, finset.mem_insert_self a _, h⟩ }, obtain ⟨i, hi, ih⟩ : ∃ i ∈ insert b s, f i ≤ P := ih (mt finset.mem_insert_of_mem hbs) h, exact ⟨i, finset.mem_insert_of_mem hi, ih⟩ end theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_bUnion_iff at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, submodule.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, tactic.unfreeze_local_instances, by_cases has : a ∈ s, { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩, by_cases hbt : b ∈ t, { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { subst hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem {x} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK theorem is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem hri) (mem_map_of_mem hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem (mul_mem_mul hri hsj)) variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [comm_ring T] {I : ideal T} (f : R →+* S) (g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [comm_ring T] {I : ideal R} (f : R →+* S) (g : S →+*T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := congr_fun (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := congr_fun (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.left, λ x y h, H.right (show f x * f y ∈ K, by rwa [mem_comap, ring_hom.map_mul] at h)⟩ @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem hrni⟩ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem hx.left)⟩ theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨comap_mono, λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨λ h, ne_top h, λ J hJ, _⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.right (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨comap_ne_top _ H.left, λ J hJ, _⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.right (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end end surjective lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end section injective variables (hf : function.injective f) include hf open function lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective section bijective variables (hf : function.bijective f) include hf open function /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.left _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective end map_and_comap section is_primary variables {R : Type u} [comm_ring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.2 hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} [comm_ring R] section comm_ring variables [comm_ring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = is_add_group_hom.ker f := rfl lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by rw [submodule.ext'_iff, ker_eq]; exact is_add_group_hom.injective_iff_trivial_ker f lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by rw [submodule.ext'_iff, ker_eq]; exact is_add_group_hom.trivial_ker_iff_eq_zero f /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using f.injective end comm_ring /-- The kernel of a homomorphism to an integral domain is a prime ideal.-/ lemma ker_is_prime [integral_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ end ring_hom namespace ideal variables {R : Type*} {S : Type*} [comm_ring R] [comm_ring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.left (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← ring_hom.map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)), ring }, exact (H.right this).imp (λ h, ha ▸ mem_map_of_mem h) (λ h, hb ▸ mem_map_of_mem h) } end theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] : is_prime (map (f : R →+* S) I) := map_is_prime_of_surjective f.surjective $ by simp theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal I.quotient).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) ⊥ quotient.mk_surjective hI, λ hI, @bot_is_maximal _ (@quotient.field _ _ I hI) ⟩ section quotient_algebra /-- The ring hom `R/J →+* S/I` induced by a ring hom `f : R →+* S` with `J ≤ f⁻¹(I)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : I.quotient →+* J.quotient := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ /-- If we take `J = I.comap f` then `quotient_map` is injective -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := begin refine (quotient_map I f le_rfl).injective_iff.2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw quotient_map_mk at ha, rwa quotient.eq_zero_iff_mem at ha ⊢ end /-- Commutativity of a square is preserved when taking quotients by an ideal -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end variables {I : ideal R} {J: ideal S} [algebra R S] @[priority 100] instance quotient_algebra : algebra (J.comap (algebra_map R S)).quotient J.quotient := (quotient_map J (algebra_map R S) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective : function.injective (algebra_map (J.comap (algebra_map R S)).quotient J.quotient) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- It is even a semialgebra. But those aren't in mathlib yet. instance semimodule_submodule : semimodule (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] variables (f : A →+* B) /-- `lift_of_surjective f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : A →+* B` is surjective (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ noncomputable def lift_of_surjective (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (classical.some (hf b)), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact classical.some_spec (hf 1) end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [classical.some_spec (hf _)], end, .. add_monoid_hom.lift_of_surjective f.to_add_monoid_hom hf g.to_add_monoid_hom hg } @[simp] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_surjective hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_surjective_comp_apply hf g.to_add_monoid_hom hg a @[simp] lemma lift_of_surjective_comp (hf : function.surjective f) (g : A →+* C) (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] } lemma eq_lift_of_surjective (hf : function.surjective f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (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 ring_hom
59289b71972ecc92a2562f47fa30fa29ec88f572
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/noetherian.lean
6a50ee41f4c9abee2ea950740e7645ec45364795
[ "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
33,925
lean
/- Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import data.multiset.finset_ops import group_theory.finiteness import linear_algebra.linear_independent import order.compactly_generated import order.order_iso_nat import ring_theory.ideal.operations /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. (Note that we do not assume yet that our rings are commutative, so perhaps this should be called "left Noetherian". To avoid cumbersome names once we specialize to the commutative case, we don't make this explicit in the declaration names.) ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators pointwise namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩ lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) : P.fg ↔ P.to_add_subgroup.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩ lemma fg_iff_exists_fin_generating_family {N : submodule R M} : N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N := begin rw fg_def, split, { rintros ⟨S, Sfin, hS⟩, obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding, exact ⟨n, f, hS⟩, }, { rintros ⟨n, s, hs⟩, refine ⟨range s, finite_range s, hs⟩ }, end /-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV) -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_span {s : set M} (hs : finite s) : fg (span R s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_span_singleton (x : M) : fg (R ∙ x) := fg_span (finite_singleton x) theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map_injective (f : M →ₗ[R] P) (hf : function.injective f) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, hf h, submodule.map_injective_of_injective hf $ by { rw [f.map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := fg_of_fg_map_injective f (linear_map.ker_eq_bot.1 hf) hfn lemma fg_top (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map_injective N.subtype subtype.val_injective $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end /-- The image of a finitely generated ideal is finitely generated. This is the `ideal` version of `submodule.fg_map`. -/ lemma map_fg_of_fg {R S : Type*} [semiring R] [semiring S] (I : ideal R) (h : I.fg) (f : R →+* S) : (I.map f).fg := begin classical, obtain ⟨s, hs : ideal.span ↑s = _⟩ := h, refine ⟨s.image f, (_ : ideal.span _ = _)⟩, rw [finset.coe_image, ←ideal.map_span, hs], end /-- The kernel of the composition of two linear maps is finitely generated if both kernels are and the first morphism is surjective. -/ lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin rw linear_map.ker_comp, apply fg_of_fg_map_of_fg_inf_ker f, { rwa [submodule.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] }, { rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono bot_le)] } end lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S] [add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M) (hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg := begin obtain ⟨X, rfl⟩ := hfin, use X, exact submodule.span_eq_restrict_scalars R S M X h end lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] (f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin letI : algebra R S := ring_hom.to_algebra f, letI : algebra R A := ring_hom.to_algebra (g.comp f), letI : algebra S A := ring_hom.to_algebra g, letI : is_scalar_tower R S A := is_scalar_tower.of_algebra_map_eq (λ _, rfl), let f₁ := algebra.linear_map R S, let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map, exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur end /-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [semiring R] [add_comm_monoid M] [add_comm_monoid P] variables [module R M] [module R P] open is_noetherian include R /-- An R-module is Noetherian iff all its submodules are finitely-generated. -/ lemma is_noetherian_def : is_noetherian R M ↔ ∀ (s : submodule R M), s.fg := ⟨λ h, h.noetherian, is_noetherian.mk⟩ theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := begin refine ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, submodule.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, _⟩⟩, have f := (submodule.equiv_map_of_injective N.subtype subtype.val_injective s).symm, have h₁ := h (s.map N.subtype) (submodule.map_subtype_le N s), have h₂ : (⊤ : submodule R (s.map N.subtype)).map (↑f : _ →ₗ[R] s) = ⊤ := by simp, have h₃ := @submodule.fg_map _ _ _ _ _ _ _ _ (↑f : _ →ₗ[R] s) _ ((submodule.fg_top _).2 h₁), exact (submodule.fg_top _).1 (h₂ ▸ h₃), end theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ lemma is_noetherian_of_le {s t : submodule R M} [ht : is_noetherian R t] (h : s ≤ t) : is_noetherian R s := is_noetherian_submodule.mpr (λ s' hs', is_noetherian_submodule.mp ht _ (le_trans hs' h)) variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from submodule.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_top_iff : is_noetherian R (⊤ : submodule R M) ↔ is_noetherian R M := begin unfreezingI { split; assume h }, { exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) }, { exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl).symm }, end lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : function.injective f) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : function.injective f) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N end section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R lemma is_noetherian_of_ker_bot [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f $ linear_map.ker_eq_bot.mp hf).symm lemma fg_of_ker_bot [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_ker_bot f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, submodule.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i), { let coe_e := equiv.subtype_univ_equiv finset.mem_univ, letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ, exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ _ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), fconstructor, { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], } } end /-- A version of `is_noetherian_pi` for non-dependent functions. We need this instance because sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to prove that `ι → ℝ` is finite dimensional over `ℝ`). -/ instance is_noetherian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι] [is_noetherian R M] : is_noetherian R (ι → M) := is_noetherian_pi end open is_noetherian submodule function section universe w variables {R M P : Type*} {N : Type w} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] [add_comm_monoid P] [module R P] theorem is_noetherian_iff_well_founded : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := begin rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3, exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩, end variables (R M) lemma well_founded_submodule_gt (R M) [semiring R] [add_comm_monoid M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp variables {R M} /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_noetherian : (∀ (f : ℕ →ₘ submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt end section universe w variables {R M P : Type*} {N : Type w} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M)).elim' _), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- If the first and final modules in a short exact sequence are noetherian, then the middle module is also noetherian. -/ theorem is_noetherian_of_range_eq_ker [is_noetherian R M] [is_noetherian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf : function.injective f) (hg : function.surjective g) (h : f.range = g.ker) : is_noetherian R N := is_noetherian_iff_well_founded.2 $ well_founded_gt_exact_sequence (well_founded_submodule_gt R M) (well_founded_submodule_gt R P) f.range (submodule.map f) (submodule.comap f) (submodule.comap g) (submodule.map g) (submodule.gci_map_comap hf) (submodule.gi_map_comap hg) (by simp [submodule.map_comap_eq, inf_comm]) (by simp [submodule.comap_map_eq, h]) /-- For any endomorphism of a Noetherian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot [I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w (2 * n + 1) (by linarith), dsimp at w, refine ⟨n+1, nat.succ_ne_zero _, _⟩, rw eq_bot_iff, rintros - ⟨h, ⟨y, rfl⟩⟩, rw [mem_bot, ←linear_map.mem_ker, w], erw linear_map.mem_ker at h ⊢, change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h, rw ←pow_add at h, convert h using 3, linarith, end /-- Any surjective endomorphism of a Noetherian module is injective. -/ theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : injective f := begin obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f, rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq, linear_map.ker_eq_bot] at w, exact linear_map.injective_of_iterate_injective ne w, end /-- Any surjective endomorphism of a Noetherian module is bijective. -/ theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : bijective f := ⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩ /-- A sequence `f` of submodules of a noetherian module, with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`, is eventually zero. -/ lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f), exact ⟨n, (λ m p, eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩ end /-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -/ noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := begin apply nonempty.some, obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) (f.tailings_disjoint_tailing i), specialize w n (le_refl n), apply nonempty.intro, refine (f.tailing_linear_equiv i n).symm ≪≫ₗ _, rw w, exact submodule.bot_equiv_punit, end end /-- A (semi)ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [semiring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [semiring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ /-- A commutative ring is Noetherian if and only if all its ideals are finitely-generated. -/ lemma is_noetherian_ring_iff_ideal_fg (R : Type*) [comm_semiring R] : is_noetherian_ring R ↔ ∀ I : ideal R, I.fg := is_noetherian_ring_iff.trans is_noetherian_def @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [semiring R] [add_comm_monoid M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [semiring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R) theorem is_noetherian_of_submodule_of_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end instance submodule.quotient.is_noetherian {R} [ring R] {M} [add_comm_group M] [module R M] (N : submodule R M) [h : is_noetherian R M] : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end /-- If `M / S / R` is a scalar tower, and `M / R` is Noetherian, then `M / S` is also noetherian. -/ theorem is_noetherian_of_tower (R) {S M} [semiring R] [semiring S] [add_comm_monoid M] [has_scalar R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_noetherian R M) : is_noetherian S M := begin rw is_noetherian_iff_well_founded at h ⊢, refine (submodule.restrict_scalars_embedding R S M).dual.well_founded h end instance ideal.quotient.is_noetherian_ring {R : Type*} [comm_ring R] [h : is_noetherian_ring R] (I : ideal R) : is_noetherian_ring I.quotient := is_noetherian_ring_iff.mpr $ is_noetherian_of_tower R $ submodule.quotient.is_noetherian _ theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_semiring R] [semiring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
a8fdeefc8386be24d6f1a22730f8a0360f0219a6
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-132.lean
1cf2207b05b8debdf4037a621241128ac5add092
[ "MIT", "Apache-2.0" ]
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
323
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.real.basic example (x : ℝ) (f g : ℝ → ℝ) (h₀ : ∀ x, f x = x + 2) (h₁ : ∀ x, g x = x ^ 2) (h₂ : f (g x) = g (f x)) : x = - 1/2 := begin sorry end
b5491b1cd12f88e8e5b4af8aca4046a079bfaf13
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/norm_cast_int.lean
a9808d7cfff84581549b438140310a709af0f201
[ "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
584
lean
import tactic.norm_cast import data.int.basic set_option pp.numerals false set_option pp.notation false -- set_option trace.simplify.rewrite true run_cmd norm_cast.numeral_to_coe `(0 : ℤ) run_cmd norm_cast.numeral_to_coe `(1 : ℤ) run_cmd norm_cast.numeral_to_coe `(2 : ℤ) run_cmd norm_cast.numeral_to_coe `(3 : ℤ) run_cmd norm_cast.coe_to_numeral `((0 : ℕ) : ℤ) run_cmd norm_cast.coe_to_numeral `((1 : ℕ) : ℤ) run_cmd norm_cast.coe_to_numeral `((2 : ℕ) : ℤ) run_cmd norm_cast.coe_to_numeral `((3 : ℕ) : ℤ) example : ((42 : ℕ) : ℤ) = 42 := by norm_cast
1a5a4b776f197642aa31314a0d4fb3a1512ca516
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/native_run/config.lean
e900c86a6d5a669aa2f8bc11ce643be084b456f4
[ "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
109
lean
-- set_option default configuration for tests prelude set_option pp.colors false set_option pp.unicode true
b6353ed269a1d531a13128f933b585df0592c6d0
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/ubscalar.lean
f78eee33d0d7a7ce22c74edb49ab5fa8df880a56
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
316
lean
structure Foo := (flag : Bool := false) (x : UInt16 := 0) (z : UInt32 := 0) (w : UInt64 := 0) (h : USize := 0) (xs : List Nat := []) set_option trace.compiler.ir.init true def f (s : Foo) : Foo := { s with x := s.x + 1 } def g (flag : Bool) : Foo := let s : Foo := { x := 10, flag := flag }; f s
f4bc9f5fd09cc3bbf8a192639b13f2ae7536ef19
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/assert_tac2.lean
d2e24e282a08fb0c9d5b4d489935b5dfe2e9d6e2
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,299
lean
import data.nat open nat eq.ops theorem lcm_dvd {m n k : nat} (H1 : m ∣ k) (H2 : (n ∣ k)) : (lcm m n ∣ k) := match eq_zero_or_pos k with | @or.inl _ _ kzero := begin rewrite kzero, apply dvd_zero end | @or.inr _ _ kpos := obtain (p : nat) (km : k = m * p), from exists_eq_mul_right_of_dvd H1, obtain (q : nat) (kn : k = n * q), from exists_eq_mul_right_of_dvd H2, begin have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos, have npos : n > 0, from pos_of_dvd_of_pos H2 kpos, have gcd_pos : gcd m n > 0, from gcd_pos_of_pos_left n mpos, have ppos : p > 0, begin apply pos_of_mul_pos_left, apply (eq.rec_on km), exact kpos end, have qpos : q > 0, from pos_of_mul_pos_left (kn ▸ kpos), have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), begin apply sorry end, have H4 : m * n * gcd p q = gcd m n * k, from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3, have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k, begin rewrite [-mul.assoc, gcd_mul_lcm], exact H4 end, have H6 : lcm m n * gcd p q = k, from !eq_of_mul_eq_mul_left gcd_pos H5, exact (dvd.intro H6) end end
487c483e8b6096fbb2371886b322738c7b392678
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/witt_vector/witt_polynomial.lean
2393cb95e9486c5c9880a9abd3a5d792bd2d92bf
[]
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
7,502
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.invertible import Mathlib.data.mv_polynomial.variables import Mathlib.data.mv_polynomial.comm_ring import Mathlib.data.mv_polynomial.expand import Mathlib.data.zmod.basic import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Witt polynomials To endow `witt_vector p R` with a ring structure, we need to study the so-called Witt polynomials. Fix a base value `p : ℕ`. The `p`-adic Witt polynomials are an infinite family of polynomials indexed by a natural number `n`, taking values in an arbitrary ring `R`. The variables of these polynomials are represented by natural numbers. The variable set of the `n`th Witt polynomial contains at most `n+1` elements `{0, ..., n}`, with exactly these variables when `R` has characteristic `0`. These polynomials are used to define the addition and multiplication operators on the type of Witt vectors. (While this type itself is not complicated, the ring operations are what make it interesting.) When the base `p` is invertible in `R`, the `p`-adic Witt polynomials form a basis for `mv_polynomial ℕ R`, equivalent to the standard basis. ## Main declarations * `witt_polynomial p R n`: the `n`-th Witt polynomial, viewed as polynomial over the ring `R` * `X_in_terms_of_W p R n`: if `p` is invertible, the polynomial `X n` is contained in the subalgebra generated by the Witt polynomials. `X_in_terms_of_W p R n` is the explicit polynomial, which upon being bound to the Witt polynomials yields `X n`. * `bind₁_witt_polynomial_X_in_terms_of_W`: the proof of the claim that `bind₁ (X_in_terms_of_W p R) (W_ R n) = X n` * `bind₁_X_in_terms_of_W_witt_polynomial`: the converse of the above statement ## Notation In this file we use the following notation * `p` is a natural number, typically assumed to be prime. * `R` and `S` are commutative rings * `W n` (and `W_ R n` when the ring needs to be explicit) denotes the `n`th Witt polynomial -/ /-- `witt_polynomial p R n` is the `n`-th Witt polynomial with respect to a prime `p` with coefficients in a commutative ring `R`. It is defined as: `∑_{i ≤ n} p^i X_i^{p^{n-i}} ∈ R[X_0, X_1, X_2, …]`. -/ def witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] (n : ℕ) : mv_polynomial ℕ R := finset.sum (finset.range (n + 1)) fun (i : ℕ) => mv_polynomial.monomial (finsupp.single i (p ^ (n - i))) (↑p ^ i) theorem witt_polynomial_eq_sum_C_mul_X_pow (p : ℕ) (R : Type u_1) [comm_ring R] (n : ℕ) : witt_polynomial p R n = finset.sum (finset.range (n + 1)) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * mv_polynomial.X i ^ p ^ (n - i) := sorry /-! We set up notation locally to this file, to keep statements short and comprehensible. This allows us to simply write `W n` or `W_ ℤ n`. -/ -- Notation with ring of coefficients explicit -- Notation with ring of coefficients implicit /- The first observation is that the Witt polynomial doesn't really depend on the coefficient ring. If we map the coefficients through a ring homomorphism, we obtain the corresponding Witt polynomial over the target ring. -/ @[simp] theorem map_witt_polynomial (p : ℕ) {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] (f : R →+* S) (n : ℕ) : coe_fn (mv_polynomial.map f) (witt_polynomial p R n) = witt_polynomial p S n := sorry @[simp] theorem constant_coeff_witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_polynomial p R n) = 0 := sorry @[simp] theorem witt_polynomial_zero (p : ℕ) (R : Type u_1) [comm_ring R] : witt_polynomial p R 0 = mv_polynomial.X 0 := sorry @[simp] theorem witt_polynomial_one (p : ℕ) (R : Type u_1) [comm_ring R] : witt_polynomial p R 1 = coe_fn mv_polynomial.C ↑p * mv_polynomial.X 1 + mv_polynomial.X 0 ^ p := sorry theorem aeval_witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] {A : Type u_2} [comm_ring A] [algebra R A] (f : ℕ → A) (n : ℕ) : coe_fn (mv_polynomial.aeval f) (witt_polynomial p R n) = finset.sum (finset.range (n + 1)) fun (i : ℕ) => ↑p ^ i * f i ^ p ^ (n - i) := sorry /-- Over the ring `zmod (p^(n+1))`, we produce the `n+1`st Witt polynomial by expanding the `n`th witt polynomial by `p`. -/ @[simp] theorem witt_polynomial_zmod_self (p : ℕ) (n : ℕ) : witt_polynomial p (zmod (p ^ (n + 1))) (n + 1) = coe_fn (mv_polynomial.expand p) (witt_polynomial p (zmod (p ^ (n + 1))) n) := sorry -- in fact, `0 < p` would be sufficient theorem witt_polynomial_vars (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] [char_zero R] (n : ℕ) : mv_polynomial.vars (witt_polynomial p R n) = finset.range (n + 1) := sorry theorem witt_polynomial_vars_subset (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (witt_polynomial p R n) ⊆ finset.range (n + 1) := sorry /-! ## Witt polynomials as a basis of the polynomial algebra If `p` is invertible in `R`, then the Witt polynomials form a basis of the polynomial algebra `mv_polynomial ℕ R`. The polynomials `X_in_terms_of_W` give the coordinate transformation in the backwards direction. -/ /-- The `X_in_terms_of_W p R n` is the polynomial on the basis of Witt polynomials that corresponds to the ordinary `X n`. -/ def X_in_terms_of_W (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] : ℕ → mv_polynomial ℕ R := sorry theorem X_in_terms_of_W_eq (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] {n : ℕ} : X_in_terms_of_W p R n = (mv_polynomial.X n - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * X_in_terms_of_W p R i ^ p ^ (n - i)) * coe_fn mv_polynomial.C (⅟ ^ n) := sorry @[simp] theorem constant_coeff_X_in_terms_of_W (p : ℕ) (R : Type u_1) [comm_ring R] [hp : fact (nat.prime p)] [invertible ↑p] (n : ℕ) : coe_fn mv_polynomial.constant_coeff (X_in_terms_of_W p R n) = 0 := sorry @[simp] theorem X_in_terms_of_W_zero (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] : X_in_terms_of_W p R 0 = mv_polynomial.X 0 := sorry theorem X_in_terms_of_W_vars_aux (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : n ∈ mv_polynomial.vars (X_in_terms_of_W p ℚ n) ∧ mv_polynomial.vars (X_in_terms_of_W p ℚ n) ⊆ finset.range (n + 1) := sorry theorem X_in_terms_of_W_vars_subset (p : ℕ) [hp : fact (nat.prime p)] (n : ℕ) : mv_polynomial.vars (X_in_terms_of_W p ℚ n) ⊆ finset.range (n + 1) := and.right (X_in_terms_of_W_vars_aux p n) theorem X_in_terms_of_W_aux (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] (n : ℕ) : X_in_terms_of_W p R n * coe_fn mv_polynomial.C (↑p ^ n) = mv_polynomial.X n - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * X_in_terms_of_W p R i ^ p ^ (n - i) := sorry @[simp] theorem bind₁_X_in_terms_of_W_witt_polynomial (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] (k : ℕ) : coe_fn (mv_polynomial.bind₁ (X_in_terms_of_W p R)) (witt_polynomial p R k) = mv_polynomial.X k := sorry @[simp] theorem bind₁_witt_polynomial_X_in_terms_of_W (p : ℕ) (R : Type u_1) [comm_ring R] [invertible ↑p] (n : ℕ) : coe_fn (mv_polynomial.bind₁ (witt_polynomial p R)) (X_in_terms_of_W p R n) = mv_polynomial.X n := sorry
b552afe5bf299e0a6225e76bd5b33e934393cd3b
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Meta/Tactic/Cases.lean
ff7016c56a595d378e2fc2d373b74f25d220519a
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,926
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean namespace Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError ("failed to compile pattern matching, inductive type expected" ++ indentExpr type) def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do type ← whnfD type; matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn; let Iargs := type.getAppArgs; let params := Iargs.extract 0 val.nparams; pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do lhsType ← inferType lhs; rhsType ← inferType rhs; u ← getLevel lhsType; condM (isDefEq lhsType rhsType) (pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs)) (pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs)) private partial def withNewIndexEqsAux {α} (indices newIndices : Array Expr) (k : Array Expr → Array Expr → MetaM α) : Nat → Array Expr → Array Expr → MetaM α | i, newEqs, newRefls => if h : i < indices.size then do let index := indices.get! i; let newIndex := newIndices.get! i; (newEqType, newRefl) ← mkEqAndProof index newIndex; withLocalDeclD `h newEqType $ fun newEq => do withNewIndexEqsAux (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls private def withNewIndexEqs {α} (indices newIndices : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := withNewIndexEqsAux indices newIndices k 0 #[] #[] structure GeneralizeIndicesSubgoal := (mvarId : MVarId) (indicesFVarIds : Array FVarId) (fvarId : FVarId) (numEqs : Nat) /-- Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := do withMVarContext mvarId $ do lctx ← getLCtx; localInsts ← getLocalInstances; checkNotAssigned mvarId `generalizeIndices; fvarDecl ← getLocalDecl fvarId; type ← whnf fvarDecl.type; type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless (val.nindices > 0) $ throwTacticEx `generalizeIndices mvarId "indexed inductive type expected"; unless (args.size == val.nindices + val.nparams) $ throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype"; let indices := args.extract (args.size - val.nindices) args.size; let IA := mkAppN f (args.extract 0 val.nparams); -- `I A` IAType ← inferType IA; forallTelescopeReducing IAType $ fun newIndices _ => do let newType := mkAppN IA newIndices; withLocalDeclD fvarDecl.userName newType $ fun h' => withNewIndexEqs indices newIndices $ fun newEqs newRefls => do (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h'; let newRefls := newRefls.push newRefl; withLocalDeclD `h newEqType $ fun newEq => do let newEqs := newEqs.push newEq; /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ target ← getMVarType mvarId; tag ← getMVarTag mvarId; auxType ← mkForallFVars newEqs target; auxType ← mkForallFVars #[h'] auxType; auxType ← mkForallFVars newIndices auxType; newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag; /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls); (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size; (fvarId, newMVarId) ← intro1P newMVarId; pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal := (ctorName : Name) namespace Cases structure Context := (inductiveVal : InductiveVal) (casesOnVal : DefinitionVal) (nminors : Nat := inductiveVal.ctors.length) (majorDecl : LocalDecl) (majorTypeFn : Expr) (majorTypeArgs : Array Expr) (majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.nindices) majorTypeArgs.size) private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do env ← getEnv; if !env.contains `Eq || !env.contains `HEq then pure none else do majorDecl ← getLocalDecl majorFVarId; majorType ← whnf majorDecl.type; majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.nindices + ival.nparams then pure none else match env.find? (mkNameStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any $ fun i => i.any $ fun j => ctx.majorTypeIndices.get! i == ctx.majorTypeIndices.get! j then /- An index ocurrs more than once -/ pure false else do lctx ← getLCtx; mctx ← getMCtx; pure $ lctx.all $ fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds; s₂.mapM $ fun s => do indicesFVarIds.foldlM (fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s) s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx $ fun i s => let ctorName := ctorNames.get! i; let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields; let s := { s with subst := s.subst.insert majorFVarId ctorApp }; { ctorName := ctorName, toInductionSubgoal := s } private partial def unifyEqsAux : Nat → CasesSubgoal → MetaM (Option CasesSubgoal) | 0, s => do trace! `Meta.Tactic.cases ("unifyEqs " ++ MessageData.ofGoal s.mvarId); pure (some s) | n+1, s => do trace! `Meta.Tactic.cases ("unifyEqs [" ++ toString (n+1) ++ "] " ++ MessageData.ofGoal s.mvarId); (eqFVarId, mvarId) ← intro1 s.mvarId; withMVarContext mvarId $ do eqDecl ← getLocalDecl eqFVarId; match eqDecl.type.heq? with | some (α, a, β, b) => do prf ← mkEqOfHEq (mkFVar eqFVarId); aEqb ← mkEq a b; mvarId ← assert mvarId eqDecl.userName aEqb prf; mvarId ← clear mvarId eqFVarId; unifyEqsAux (n+1) { s with mvarId := mvarId } | none => match eqDecl.type.eq? with | some (α, a, b) => let skip : Unit → MetaM (Option CasesSubgoal) := fun _ => do { mvarId ← clear mvarId eqFVarId; unifyEqsAux n { s with mvarId := mvarId } }; let substEq (symm : Bool) : MetaM (Option CasesSubgoal) := do { (newSubst, mvarId) ← substCore mvarId eqFVarId symm s.subst; unifyEqsAux n { s with mvarId := mvarId, subst := newSubst, fields := s.fields.map $ fun field => newSubst.apply field } }; let inj : Unit → MetaM (Option CasesSubgoal) := fun _ => do { r ← injectionCore mvarId eqFVarId; match r with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqs => unifyEqsAux (n+numEqs) { s with mvarId := mvarId } }; condM (isDefEq a b) (skip ()) $ do a' ← whnf a; b' ← whnf b; if a' != a || b' != b then do let prf := mkFVar eqFVarId; aEqb' ← mkEq a' b'; mvarId ← assert mvarId eqDecl.userName aEqb' prf; mvarId ← clear mvarId eqFVarId; unifyEqsAux (n+1) { s with mvarId := mvarId } else match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => do aDecl ← getLocalDecl aFVarId; bDecl ← getLocalDecl bFVarId; substEq (aDecl.index < bDecl.index) | Expr.fvar _ _, _ => substEq false | _, Expr.fvar _ _ => substEq true | _, _ => inj () | none => throwTacticEx `cases mvarId "equality expected" private def unifyEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (fun subgoals s => do s? ← unifyEqsAux numEqs s; match s? with | none => pure $ subgoals | some s => pure $ subgoals.push s) #[] private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name)) (useUnusedNames : Bool) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do majorType ← inferType (mkFVar majorFVarId); (us, params) ← getInductiveUniverseAndParams majorType; let casesOn := mkCasesOnFor ctx.inductiveVal.name; let ctors := ctx.inductiveVal.ctors.toArray; s ← induction mvarId majorFVarId casesOn givenNames useUnusedNames; pure $ toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases; context? ← mkCasesContext? majorFVarId; match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.nindices == 0 then do -- Simple case inductionCasesOn mvarId majorFVarId givenNames useUnusedNames ctx else do s₁ ← generalizeIndices mvarId majorFVarId; trace! `Meta.Tactic.cases ("after generalizeIndices" ++ Format.line ++ MessageData.ofGoal s₁.mvarId); s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames useUnusedNames ctx; s₂ ← elimAuxIndices s₁ s₂; unifyEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array (List Name) := #[]) (useUnusedNames := false) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames useUnusedNames @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.Tactic.cases end Meta end Lean
d4d67d26b5a12ce648348f55e16e9195611b233a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/state8.lean
99d93a13aa6ff3559a961cc242dfab8cef9026af
[ "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,214
lean
inductive States | s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7 open States def f : States → States → States | s0, s0 => s0 | s0, s1 => s0 | s0, s2 => s0 | s0, s3 => s0 | s0, s4 => s0 | s0, s5 => s0 | s0, s6 => s0 | s0, s7 => s0 | s1, s0 => s0 | s1, s1 => s0 | s1, s2 => s0 | s1, s3 => s0 | s1, s4 => s0 | s1, s5 => s0 | s1, s6 => s0 | s1, s7 => s0 | s2, s0 => s0 | s2, s1 => s0 | s2, s2 => s0 | s2, s3 => s0 | s2, s4 => s0 | s2, s5 => s0 | s2, s6 => s0 | s2, s7 => s0 | s3, s0 => s0 | s3, s1 => s0 | s3, s2 => s0 | s3, s3 => s0 | s3, s4 => s0 | s3, s5 => s0 | s3, s6 => s0 | s3, s7 => s0 | s4, s0 => s0 | s4, s1 => s0 | s4, s2 => s0 | s4, s3 => s0 | s4, s4 => s0 | s4, s5 => s0 | s4, s6 => s0 | s4, s7 => s0 | s5, s0 => s0 | s5, s1 => s0 | s5, s2 => s0 | s5, s3 => s0 | s5, s4 => s0 | s5, s5 => s0 | s5, s6 => s0 | s5, s7 => s0 | s6, s0 => s0 | s6, s1 => s0 | s6, s2 => s0 | s6, s3 => s0 | s6, s4 => s0 | s6, s5 => s0 | s6, s6 => s0 | s6, s7 => s0 | s7, s0 => s0 | s7, s1 => s0 | s7, s2 => s0 | s7, s3 => s0 | s7, s4 => s0 | s7, s5 => s0 | s7, s6 => s0 | s7, s7 => s0 set_option maxHeartbeats 0 example : ∀ x y z, f (f (f s0 x) y) z = f (f x z) (f y z) := by intros x y z cases x <;> cases y <;> cases z <;> rfl
69d0ed6c41f5f9bd0bd1de445eb4ed5e4f2d08f5
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/complex/basic.lean
3f8047f433d9d7344c443bb220e1b48b0e8d4773
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
19,314
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro The complex numbers, modelled as R^2 in the obvious way. -/ import data.real.basic tactic.ring algebra.field_power import tactic.norm_cast structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl @[ext] theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ instance : has_coe ℝ ℂ := ⟨λ r, ⟨r, 0⟩⟩ @[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp, norm_cast] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp lemma smul_re (r : ℝ) (z : ℂ) : (↑r * z).re = r * z.re := by simp lemma smul_im (r : ℝ) (z : ℂ) : (↑r * z).im = r * z.im := by simp @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp def real_prod_equiv : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem real_prod_equiv_apply (z : ℂ) : real_prod_equiv z = (z.re, z.im) := rfl theorem real_prod_equiv_symm_re (x y : ℝ) : (real_prod_equiv.symm (x, y)).re = x := rfl theorem real_prod_equiv_symm_im (x y : ℝ) : (real_prod_equiv.symm (x, y)).im = y := rfl def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩ @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_zero : conj 0 = 0 := ext_iff.2 $ by simp [conj] @[simp] lemma conj_one : conj 1 = 1 := ext_iff.2 $ by simp @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := ext_iff.2 $ by simp [add_comm] @[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := ext_iff.2 $ by simp [add_comm] @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_involutive : function.involutive conj := conj_conj lemma conj_bijective : function.bijective conj := conj_involutive.bijective lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 lemma eq_conj_iff_real {z : ℂ} : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, e.symm ▸ rfl⟩ lemma eq_conj_iff_re {z : ℂ} : conj z = z ↔ (z.re : ℂ) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } /-- Coercion `ℝ → ℂ` as a `ring_hom`. -/ def of_real : ℝ →+* ℂ := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma I_sq : I ^ 2 = -1 := by rw [pow_two, I_mul_I] @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp, norm_cast] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp, norm_cast] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul, sub_eq_add_neg] lemma conj_pow (z : ℂ) (n : ℕ) : conj (z ^ n) = conj z ^ n := by induction n; simp [*, conj_mul, pow_succ] @[simp] lemma conj_two : conj (2 : ℂ) = 2 := by apply complex.ext; simp lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re, add_comm, add_left_comm, sub_eq_add_neg] noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp, norm_cast] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, {simp [h]}, rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv] end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] noncomputable instance : field ℂ := { inv := has_inv.inv, zero_ne_one := mt (congr_arg re) zero_ne_one, mul_inv_cancel := @complex.mul_inv_cancel, inv_zero := complex.inv_zero, ..complex.comm_ring } instance re.is_add_group_hom : is_add_group_hom complex.re := { map_add := complex.add_re } instance im.is_add_group_hom : is_add_group_hom complex.im := { map_add := complex.add_im } instance : is_ring_hom conj := by refine_struct {..}; simp instance of_real.is_ring_hom : is_ring_hom (coe : ℝ → ℂ) := by refine_struct {..}; simp lemma div_re (z w : ℂ) : (z / w).re = z.re * w.re / norm_sq w + z.im * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, add_left_comm] lemma div_im (z w : ℂ) : (z / w).im = z.im * w.re / norm_sq w - z.re * w.im / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, add_left_comm] @[simp, norm_cast] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := is_ring_hom.map_div coe @[simp, norm_cast] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := is_ring_hom.map_fpow of_real r n @[simp, norm_cast] theorem of_real_int_cast : ∀ n : ℤ, ((n : ℝ) : ℂ) = n := of_real.map_int_cast @[simp, norm_cast] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := of_real.map_nat_cast n @[simp] lemma conj_sub (z w : ℂ) : conj (z - w) = conj z - conj w := by simp [sub_eq_add_neg] @[simp] lemma conj_inv (z : ℂ) : conj z⁻¹ = (conj z)⁻¹ := by ext; simp [neg_div] @[simp] lemma conj_div (z w : ℂ) : conj (z / w) = conj z / conj w := by rw [division_def, conj_mul, conj_inv]; refl @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := by classical; exact if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h @[simp, norm_cast] theorem of_real_rat_cast : ∀ n : ℚ, ((n : ℝ) : ℂ) = n := of_real.map_rat_cast theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : complex.abs n = n := calc complex.abs n = complex.abs (n:ℝ) : by rw [of_real_nat_cast] ... = _ : abs_of_nonneg (nat.cast_nonneg n) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value abs := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := by classical; exact if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _) lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := by classical; exact if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _) @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj_sub, abs_conj]; exact hi j hj⟩ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) end complex
eefccb6ebe4512301d139953f0069ca333abe946
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/options.lean
27b27a11904fd6e8e0833b4b0819ed275a8c99ae
[ "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
2,493
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich and Leonardo de Moura -/ prelude import init.lean.kvmap init.io init.control.combinators init.data.tostring namespace Lean def Options := KVMap namespace Options def empty : Options := {KVMap .} instance : HasEmptyc Options := ⟨empty⟩ end Options structure OptionDecl := (defValue : DataValue) (group : String := "") (descr : String := "") def OptionDecls := NameMap OptionDecl private def initOptionDeclsRef : IO (IO.Ref OptionDecls) := IO.mkRef (mkNameMap OptionDecl) @[init initOptionDeclsRef] private constant optionDeclsRef : IO.Ref OptionDecls := default _ def registerOption (name : Name) (decl : OptionDecl) : IO Unit := do decls ← optionDeclsRef.get; when (decls.contains name) $ throw $ IO.userError ("invalid option declaration '" ++ toString name ++ "', option already exists"); optionDeclsRef.set $ decls.insert name decl def getOptionDecls : IO OptionDecls := optionDeclsRef.get def getOptionDecl (name : Name) : IO OptionDecl := do decls ← getOptionDecls; (some decl) ← pure (decls.find name) | throw $ IO.userError ("unknown option '" ++ toString name ++ "'"); pure decl def getOptionDefaulValue (name : Name) : IO DataValue := do decl ← getOptionDecl name; pure decl.defValue def getOptionDescr (name : Name) : IO String := do decl ← getOptionDecl name; pure decl.descr def setOptionFromString (opts : Options) (entry : String) : IO Options := do let ps := (entry.split "=").map String.trim; [key, val] ← pure ps | throw "invalid configuration option entry, it must be of the form '<key> = <value>'"; defValue ← getOptionDefaulValue key.toName; match defValue with | DataValue.ofString v => pure $ opts.setString key val | DataValue.ofBool v => if key == "true" then pure $ opts.setBool key true else if key == "false" then pure $ opts.setBool key false else throw $ IO.userError ("invalid Bool option value '" ++ val ++ "'") | DataValue.ofName v => pure $ opts.setName key val.toName | DataValue.ofNat v => do unless val.isNat $ throw (IO.userError ("invalid Nat option value '" ++ val ++ "'")); pure $ opts.setNat key val.toNat | DataValue.ofInt v => do unless val.isInt $ throw (IO.userError ("invalid Int option value '" ++ val ++ "'")); pure $ opts.setInt key val.toInt end Lean
dac7f27df42f80b9712a97db0bc7a1e8635daa9e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/legendre_symbol/gauss_eisenstein_lemmas.lean
ce813915fe53b501a9d1781747c9f7c18002007e
[ "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
14,964
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 number_theory.legendre_symbol.quadratic_reciprocity /-! # Lemmas of Gauss and Eisenstein This file contains code for the proof of the Lemmas of Gauss and Eisenstein on the Legendre symbol. The main results are `zmod.gauss_lemma_aux` and `zmod.eisenstein_lemma_aux`. -/ open function finset nat finite_field zmod open_locale big_operators nat namespace zmod section wilson variables (p : ℕ) [fact p.prime] /-- **Wilson's Lemma**: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : ((p - 1)! : zmod p) = -1 := begin refine calc ((p - 1)! : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) : by rw [← finset.prod_Ico_id_eq_factorial, prod_nat_cast] ... = (∏ x : (zmod p)ˣ, x) : _ ... = -1 : by simp_rw [← units.coe_hom_apply, ← (units.coe_hom (zmod p)).map_prod, prod_univ_units_id_eq_neg_one, units.coe_hom_apply, units.coe_neg, units.coe_one], have hp : 0 < p := (fact.out p.prime).pos, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [mem_Ico, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [mem_Ico, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (fact.out p.prime).pos] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_factorial, wilsons_lemma] end end wilson end zmod section gauss_eisenstein namespace zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.1.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, mem_Ico.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw nat_cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (mem_Ico.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj le_rfl) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℤ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, card_Ico, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [nat_cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] lemma gauss_lemma_aux (p : ℕ) [hp : fact p.prime] [fact (p % 2 = 1)] {a : ℤ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.1.dvd_factorial, not_le]; exact nat.div_lt_self hp.1.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {p : ℕ} [fact p.prime] {a : ℤ} (hp : p ≠ 2) (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := begin haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩, have : (legendre_sym p a : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p) := by { rw [legendre_sym.eq_pow, gauss_lemma_aux p ha0]; simp }, cases legendre_sym.eq_one_or_neg_one p ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end private lemma eisenstein_lemma_aux₁ (p : ℕ) [fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2.1, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_nat_cast]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, nat.cast_sum, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [nat.cast_sum] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, nat.cast_sum], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [nat.cast_sum]) rfl lemma eisenstein_lemma_aux (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, nat.cast_sum, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter $ λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ (mem_Ico.mp hx).2) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : ((Ico 1 (q / 2).succ ×ˢ Ico 1 (p / 2).succ).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) ((Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, mem_Ico, mem_product] at *; tauto) (nat.div_lt_self hp.1.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, nonpos_iff_eq_zero, mem_Ico, one_ne_zero, false_and, mem_product] using hx }, have hunion : (Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ (Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = (Ico 1 (p / 2).succ ×ˢ Ico 1 (q / 2).succ), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, mem_Ico, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [card_Ico, tsub_zero, succ_sub_succ_eq_sub] end lemma eisenstein_lemma {p : ℕ} [fact p.prime] (hp : p ≠ 2) {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym p a = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := begin haveI hp' : fact (p % 2 = 1) := ⟨nat.prime.mod_two_eq_one_iff_ne_two.mpr hp⟩, have ha0' : ((a : ℤ) : zmod p) ≠ 0 := by { norm_cast, exact ha0 }, rw [neg_one_pow_eq_pow_mod_two, gauss_lemma hp ha0', neg_one_pow_eq_pow_mod_two, (by norm_cast : ((a : ℤ) : zmod p) = (a : zmod p)), show _ = _, from eisenstein_lemma_aux p ha1 ha0] end end zmod end gauss_eisenstein
2327b363c31d5acdb52074c60d5ff7cf62beab6d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/star/prod.lean
2bc74d1b4e8c8a469ac71301d2627f2f69aa3571
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,165
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.star.basic import algebra.ring.prod import algebra.module.prod /-! # `star` on product types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We put a `has_star` structure on product types that operates elementwise. -/ universes u v w variables {R : Type u} {S : Type v} namespace prod instance [has_star R] [has_star S] : has_star (R × S) := { star := λ x, (star x.1, star x.2) } @[simp] lemma fst_star [has_star R] [has_star S] (x : R × S) : (star x).1 = star x.1 := rfl @[simp] lemma snd_star [has_star R] [has_star S] (x : R × S) : (star x).2 = star x.2 := rfl lemma star_def [has_star R] [has_star S] (x : R × S) : star x = (star x.1, star x.2) := rfl instance [has_star R] [has_star S] [has_trivial_star R] [has_trivial_star S] : has_trivial_star (R × S) := { star_trivial := λ _, prod.ext (star_trivial _) (star_trivial _) } instance [has_involutive_star R] [has_involutive_star S] : has_involutive_star (R × S) := { star_involutive := λ _, prod.ext (star_star _) (star_star _) } instance [semigroup R] [semigroup S] [star_semigroup R] [star_semigroup S] : star_semigroup (R × S) := { star_mul := λ _ _, prod.ext (star_mul _ _) (star_mul _ _) } instance [add_monoid R] [add_monoid S] [star_add_monoid R] [star_add_monoid S] : star_add_monoid (R × S) := { star_add := λ _ _, prod.ext (star_add _ _) (star_add _ _) } instance [non_unital_semiring R] [non_unital_semiring S] [star_ring R] [star_ring S] : star_ring (R × S) := { ..prod.star_add_monoid, ..(prod.star_semigroup : star_semigroup (R × S)) } instance {α : Type w} [has_smul α R] [has_smul α S] [has_star α] [has_star R] [has_star S] [star_module α R] [star_module α S] : star_module α (R × S) := { star_smul := λ r x, prod.ext (star_smul _ _) (star_smul _ _) } end prod @[simp] lemma units.embed_product_star [monoid R] [star_semigroup R] (u : Rˣ) : units.embed_product R (star u) = star (units.embed_product R u) := rfl
ebc12053fc98e71195a0c81160809c5297549250
7cef822f3b952965621309e88eadf618da0c8ae9
/src/group_theory/subgroup.lean
d2919514397d2ce5f07f04fd32868b43a863b7b8
[ "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
28,421
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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro, Michael Howes -/ import group_theory.submonoid open set function variables {α : Type*} {β : Type*} {a a₁ a₂ b c: α} section group variables [group α] [add_group β] @[to_additive] lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this section prio set_option default_priority 100 -- see Note [default priority] /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set β) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ @[to_additive is_add_subgroup] class is_subgroup (s : set α) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) end prio instance additive.is_add_subgroup (s : set α) [is_subgroup s] : @is_add_subgroup (additive α) _ s := ⟨@is_subgroup.inv_mem _ _ _ _⟩ theorem additive.is_add_subgroup_iff {s : set α} : @is_add_subgroup (additive α) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk α _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ instance multiplicative.is_subgroup (s : set β) [is_add_subgroup s] : @is_subgroup (multiplicative β) _ s := ⟨@is_add_subgroup.neg_mem _ _ _ _⟩ theorem multiplicative.is_subgroup_iff {s : set β} : @is_subgroup (multiplicative β) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk β _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by resetI; apply_instance⟩ @[to_additive add_group] instance subtype.group {s : set α} [is_subgroup s] : group s := by subtype_instance @[to_additive add_comm_group] instance subtype.comm_group {α : Type*} [comm_group α] {s : set α} [is_subgroup s] : comm_group s := by subtype_instance @[simp, to_additive] lemma is_subgroup.coe_inv {s : set α} [is_subgroup s] (a : s) : ((a⁻¹ : s) : α) = a⁻¹ := rfl @[simp] lemma is_subgroup.coe_gpow {s : set α} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : α) = a ^ n := by induction n; simp [is_submonoid.coe_pow a] @[simp] lemma is_add_subgroup.gsmul_coe {β : Type*} [add_group β] {s : set β} [is_add_subgroup s] (a : s) (n : ℤ) : ((gsmul n a : s) : β) = gsmul n a := by induction n; simp [is_add_submonoid.smul_coe a] attribute [to_additive gsmul_coe] is_subgroup.coe_gpow @[to_additive of_add_neg] theorem is_subgroup.of_div (s : set α) (one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s) : is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set β) (zero_mem : (0:β) ∈ s) (sub_mem : ∀{a b:β}, a ∈ s → b ∈ s → a - b ∈ s) : is_add_subgroup s := is_add_subgroup.of_add_neg s zero_mem (λ x y hx hy, sub_mem hx hy) @[to_additive] instance is_subgroup.inter (s₁ s₂ : set α) [is_subgroup s₁] [is_subgroup s₂] : is_subgroup (s₁ ∩ s₂) := { inv_mem := λ x hx, ⟨is_subgroup.inv_mem hx.1, is_subgroup.inv_mem hx.2⟩ } @[to_additive] instance is_subgroup.Inter {ι : Sort*} (s : ι → set α) [h : ∀ y : ι, is_subgroup (s y)] : is_subgroup (set.Inter s) := { inv_mem := λ x h, set.mem_Inter.2 $ λ y, is_subgroup.inv_mem (set.mem_Inter.1 h y) } @[to_additive is_add_subgroup_Union_of_directed] lemma is_subgroup_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set α) [∀ i, is_subgroup (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subgroup (⋃i, s i) := { inv_mem := λ a ha, let ⟨i, hi⟩ := set.mem_Union.1 ha in set.mem_Union.2 ⟨i, is_subgroup.inv_mem hi⟩, to_is_submonoid := is_submonoid_Union_of_directed s directed } def gpowers (x : α) : set α := set.range ((^) x : ℤ → α) def gmultiples (x : β) : set β := set.range (λ i, gsmul i x) attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : β) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive is_add_subgroup] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : β} {s : set β} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative β) _ _ _ _ lemma gpowers_subset {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : gpowers a ⊆ s := λ x hx, match x, hx with _, ⟨i, rfl⟩ := is_subgroup.gpow_mem h end lemma gmultiples_subset {a : β} {s : set β} [is_add_subgroup s] (h : a ∈ s) : gmultiples a ⊆ s := @gpowers_subset (multiplicative β) _ _ _ _ h attribute [to_additive gmultiples_subset] gpowers_subset lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : β} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group α] (s : set α) [is_subgroup s] @[to_additive] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive] lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup theorem is_add_subgroup.sub_mem {α} [add_group α] (s : set α) [is_add_subgroup s] (a b : α) (ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s := is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb) section prio set_option default_priority 100 -- see Note [default priority] class normal_add_subgroup [add_group α] (s : set α) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g + n - g ∈ s) @[to_additive normal_add_subgroup] class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s) end prio @[to_additive normal_add_subgroup_of_add_comm_group] lemma normal_subgroup_of_comm_group [comm_group α] (s : set α) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } instance additive.normal_add_subgroup [group α] (s : set α) [normal_subgroup s] : @normal_add_subgroup (additive α) _ s := ⟨@normal_subgroup.normal _ _ _ _⟩ theorem additive.normal_add_subgroup_iff [group α] {s : set α} : @normal_add_subgroup (additive α) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk α _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ instance multiplicative.normal_subgroup [add_group α] (s : set α) [normal_add_subgroup s] : @normal_subgroup (multiplicative α) _ s := ⟨@normal_add_subgroup.normal _ _ _ _⟩ theorem multiplicative.normal_subgroup_iff [add_group α] {s : set α} : @normal_subgroup (multiplicative α) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk α _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by resetI; apply_instance⟩ namespace is_subgroup variable [group α] -- Normal subgroup properties @[to_additive] lemma mem_norm_comm {s : set α} [normal_subgroup s] {a b : α} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h @[to_additive] lemma mem_norm_comm_iff {s : set α} [normal_subgroup s] {a b : α} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ @[to_additive] def trivial (α : Type*) [group α] : set α := {1} @[simp, to_additive] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 := mem_singleton_iff @[to_additive] instance trivial_normal : normal_subgroup (trivial α) := by refine {..}; simp [trivial] {contextual := tt} @[to_additive] lemma eq_trivial_iff {H : set α} [is_subgroup H] : H = trivial α ↔ (∀ x ∈ H, x = (1 : α)) := by simp only [set.ext_iff, is_subgroup.mem_trivial]; exact ⟨λ h x, (h x).1, λ h x, ⟨h x, λ hx, hx.symm ▸ is_submonoid.one_mem H⟩⟩ @[to_additive] instance univ_subgroup : normal_subgroup (@univ α) := by refine {..}; simp @[to_additive add_center] def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g} @[to_additive mem_add_center] lemma mem_center {a : α} : a ∈ center α ↔ ∀g, g * a = a * g := iff.rfl @[to_additive add_center_normal] instance center_normal : normal_subgroup (center α) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } @[to_additive add_normalizer] def normalizer (s : set α) : set α := {g : α | ∀ n, n ∈ s ↔ g * n * g⁻¹ ∈ s} @[to_additive normalizer_is_add_subgroup] instance normalizer_is_subgroup (s : set α) [is_subgroup s] : is_subgroup (normalizer s) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) (hb : ∀ n, n ∈ s ↔ b * n * b⁻¹ ∈ s) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } @[to_additive subset_add_normalizer] lemma subset_normalizer (s : set α) [is_subgroup s] : s ⊆ normalizer s := λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_right _ hg] /-- Every subgroup is a normal subgroup of its normalizer -/ @[to_additive add_normal_in_add_normalizer] instance normal_in_normalizer (s : set α) [is_subgroup s] : normal_subgroup (subtype.val ⁻¹' s : set (normalizer s)) := { one_mem := show (1 : α) ∈ s, from is_submonoid.one_mem _, mul_mem := λ a b ha hb, show (a * b : α) ∈ s, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : α) ∈ s, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } end is_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup open is_mul_hom (map_mul) variables [group α] [group β] @[to_additive] def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β) @[to_additive] lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 := mem_trivial @[to_additive] lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end @[to_additive] lemma one_ker_inv' (f : α → β) [is_group_hom f] {a b : α} (h : f (a⁻¹ * b) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, apply eq_of_inv_eq_inv, rw eq_inv_of_mul_eq_one h end @[to_additive] lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma inv_ker_one' (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a⁻¹ * b) = 1 := have (f a)⁻¹ * f b = 1, by rw [h, mul_left_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ @[to_additive] lemma one_iff_ker_inv' (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a⁻¹ * b) = 1 := ⟨inv_ker_one' f, one_ker_inv' f⟩ @[to_additive] lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ @[to_additive] lemma inv_iff_ker' (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a⁻¹ * b ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv' _ _ _ @[to_additive image_add_subgroup] instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, map_mul f]⟩, one_mem := ⟨1, one_mem s, map_one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw map_inv f; simp *⟩ } @[to_additive range_add_subgroup] instance range_subgroup (f : α → β) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal @[to_additive] instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [map_mul f, map_one f, map_inv f, @inv_mem β _ s] {contextual:=tt} @[to_additive] instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [map_mul f, map_inv f] {contextual:=tt}⟩ @[to_additive] instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial β) @[to_additive] lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end @[to_additive] lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) : ker f = trivial α := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [map_one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.map_one f] {contextual := tt}) @[to_additive] lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] : function.injective f ↔ ker f = trivial α := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ @[to_additive] lemma trivial_ker_iff_eq_one (f : α → β) [is_group_hom f] : ker f = trivial α ↔ ∀ x, f x = 1 → x = 1 := by rw set.ext_iff; simp [ker]; exact ⟨λ h x hx, (h x).1 hx, λ h x, ⟨h x, λ hx, by rw [hx, map_one f]⟩⟩ end is_group_hom @[to_additive is_add_group_hom] instance subtype_val.is_group_hom [group α] {s : set α} [is_subgroup s] : is_group_hom (subtype.val : s → α) := { ..subtype_val.is_monoid_hom } @[to_additive is_add_group_hom] instance coe.is_group_hom [group α] {s : set α} [is_subgroup s] : is_group_hom (coe : s → α) := { ..subtype_val.is_monoid_hom } @[to_additive is_add_group_hom] instance subtype_mk.is_group_hom [group α] [group β] {s : set α} [is_subgroup s] (f : β → α) [is_group_hom f] (h : ∀ x, f x ∈ s) : is_group_hom (λ x, (⟨f x, h x⟩ : s)) := { ..subtype_mk.is_monoid_hom f h } @[to_additive is_add_group_hom] instance set_inclusion.is_group_hom [group α] {s t : set α} [is_subgroup s] [is_subgroup t] (h : s ⊆ t) : is_group_hom (set.inclusion h) := subtype_mk.is_group_hom _ _ namespace add_group variables [add_group α] inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | zero : in_closure 0 | neg {a : α} : in_closure a → in_closure (-a) | add {a b : α} : in_closure a → in_closure b → in_closure (a + b) end add_group namespace group open is_submonoid is_subgroup variables [group α] {s : set α} @[to_additive] inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : α} : in_closure a → in_closure a⁻¹ | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ @[to_additive] def closure (s : set α) : set α := {a | in_closure s a } @[to_additive] lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic @[to_additive is_add_subgroup] instance closure.is_subgroup (s : set α) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } @[to_additive] theorem subset_closure {s : set α} : s ⊆ closure s := λ a, mem_closure @[to_additive] theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] @[to_additive] lemma closure_subset_iff (s t : set α) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t := ⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩ @[to_additive] theorem closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure @[simp, to_additive closure_add_subgroup] lemma closure_subgroup (s : set α) [is_subgroup s] : closure s = s := set.subset.antisymm (closure_subset $ set.subset.refl s) subset_closure @[to_additive] theorem exists_list_of_mem_closure {s : set α} {a : α} (h : a ∈ closure s) : (∃l:list α, (∀x∈l, x ∈ s ∨ x⁻¹ ∈ s) ∧ l.prod = a) := in_closure.rec_on h (λ x hxs, ⟨[x], list.forall_mem_singleton.2 $ or.inl hxs, one_mul _⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x _ ⟨L, HL1, HL2⟩, ⟨L.reverse.map has_inv.inv, λ x hx, let ⟨y, hy1, hy2⟩ := list.exists_of_mem_map hx in hy2 ▸ or.imp id (by rw [inv_inv]; exact id) (HL1 _ $ list.mem_reverse.1 hy1).symm, HL2 ▸ list.rec_on L one_inv.symm (λ hd tl ih, by rw [list.reverse_cons, list.map_append, list.prod_append, ih, list.map_singleton, list.prod_cons, list.prod_nil, mul_one, list.prod_cons, mul_inv_rev])⟩) (λ x y hx hy ⟨L1, HL1, HL2⟩ ⟨L2, HL3, HL4⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL3⟩, by rw [list.prod_append, HL2, HL4]⟩) @[to_additive] lemma image_closure [group β] (f : α → β) [is_group_hom f] (s : set α) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_group_hom.map_inv f], apply is_subgroup.inv_mem, assumption }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) @[to_additive] theorem mclosure_subset {s : set α} : monoid.closure s ⊆ closure s := monoid.closure_subset $ subset_closure @[to_additive] theorem mclosure_inv_subset {s : set α} : monoid.closure (has_inv.inv ⁻¹' s) ⊆ closure s := monoid.closure_subset $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx) @[to_additive] theorem closure_eq_mclosure {s : set α} : closure s = monoid.closure (s ∪ has_inv.inv ⁻¹' s) := set.subset.antisymm (@closure_subset _ _ _ (monoid.closure (s ∪ has_inv.inv ⁻¹' s)) { inv_mem := λ x hx, monoid.in_closure.rec_on hx (λ x hx, or.cases_on hx (λ hx, monoid.subset_closure $ or.inr $ show x⁻¹⁻¹ ∈ s, from (inv_inv x).symm ▸ hx) (λ hx, monoid.subset_closure $ or.inl hx)) ((@one_inv α _).symm ▸ is_submonoid.one_mem _) (λ x y hx hy ihx ihy, (mul_inv_rev x y).symm ▸ is_submonoid.mul_mem ihy ihx) } (set.subset.trans (set.subset_union_left _ _) monoid.subset_closure)) (monoid.closure_subset $ set.union_subset subset_closure $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx)) @[to_additive] theorem mem_closure_union_iff {α : Type*} [comm_group α] {s t : set α} {x : α} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := begin simp only [closure_eq_mclosure, monoid.mem_closure_union_iff, exists_prop, preimage_union], split, { rintro ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨_, hys, _, hzs, rfl⟩, _, ⟨_, hyt, _, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm zs], refl }, { rintro ⟨_, ⟨ys, hys, zs, hzs, rfl⟩, _, ⟨yt, hyt, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm yt], refl } end @[to_additive gmultiples_eq_closure] theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} := subset.antisymm (gpowers_subset $ mem_closure $ by simp) (closure_subset $ by simp [mem_gpowers]) end group namespace is_subgroup variable [group α] @[to_additive] lemma trivial_eq_closure : trivial α = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) end is_subgroup /-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. -/ namespace group variables {s : set α} [group α] /-- Given an element a, conjugates a is the set of conjugates. -/ def conjugates (a : α) : set α := {b | is_conj a b} lemma mem_conjugates_self {a : α} : 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 α) : set α := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : α} : x ∈ conjugates_of_set s ↔ ∃ a : α, a ∈ s ∧ is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : α) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set α} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset {t : set α} [normal_subgroup t] {a : α} (h : a ∈ t) : conjugates a ⊆ t := λ x ⟨c,w⟩, begin have H := normal_subgroup.normal a h c, rwa ←w, end theorem conjugates_of_set_subset {s t : set α} [normal_subgroup t] (h : s ⊆ t) : conjugates_of_set s ⊆ t := set.bUnion_subset (λ x H, conjugates_subset (h H)) /-- The set of conjugates of s is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : α} : 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 /-- 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 α) : set α := 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 a set is a subgroup. -/ instance normal_closure.is_subgroup (s : set α) : is_subgroup (normal_closure s) := closure.is_subgroup (conjugates_of_set s) /-- The normal closure of s is a normal subgroup. -/ instance normal_closure.is_normal : normal_subgroup (normal_closure s) := ⟨ λ n h g, begin induction h with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx))}, {simpa using (normal_closure.is_subgroup s).one_mem}, {rw ←conj_inv, exact (is_subgroup.inv_mem ihx)}, {rw ←conj_mul, exact (is_submonoid.mul_mem ihx ihy)}, end ⟩ /-- The normal closure of s is the smallest normal subgroup containing s. -/ theorem normal_closure_subset {s t : set α} [normal_subgroup t] (h : s ⊆ t) : normal_closure s ⊆ t := λ a w, begin induction w with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset h $ hx)}, {exact is_submonoid.one_mem t}, {exact is_subgroup.inv_mem ihx}, {exact is_submonoid.mul_mem ihx ihy} end lemma normal_closure_subset_iff {s t : set α} [normal_subgroup t] : s ⊆ t ↔ normal_closure s ⊆ t := ⟨normal_closure_subset, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set α} : s ⊆ t → normal_closure s ⊆ normal_closure t := λ h, normal_closure_subset (set.subset.trans h (subset_normal_closure)) end group section simple_group class simple_group (α : Type*) [group α] : Prop := (simple : ∀ (N : set α) [normal_subgroup N], N = is_subgroup.trivial α ∨ N = set.univ) class simple_add_group (α : Type*) [add_group α] : Prop := (simple : ∀ (N : set α) [normal_add_subgroup N], N = is_add_subgroup.trivial α ∨ N = set.univ) attribute [to_additive simple_add_group] simple_group theorem additive.simple_add_group_iff [group α] : simple_add_group (additive α) ↔ simple_group α := ⟨λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.1 h)⟩⟩ instance additive.simple_add_group [group α] [simple_group α] : simple_add_group (additive α) := additive.simple_add_group_iff.2 (by apply_instance) theorem multiplicative.simple_group_iff [add_group α] : simple_group (multiplicative α) ↔ simple_add_group α := ⟨λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.1 h)⟩⟩ instance multiplicative.simple_group [add_group α] [simple_add_group α] : simple_group (multiplicative α) := multiplicative.simple_group_iff.2 (by apply_instance) lemma simple_group_of_surjective [group α] [group β] [simple_group α] (f : α → β) [is_group_hom f] (hf : function.surjective f) : simple_group β := ⟨λ H iH, have normal_subgroup (f ⁻¹' H), by resetI; apply_instance, begin resetI, cases simple_group.simple (f ⁻¹' H) with h h, { refine or.inl (is_subgroup.eq_trivial_iff.2 (λ x hx, _)), cases hf x with y hy, rw ← hy at hx, rw [← hy, is_subgroup.eq_trivial_iff.1 h y hx, is_group_hom.map_one f] }, { refine or.inr (set.eq_univ_of_forall (λ x, _)), cases hf x with y hy, rw set.eq_univ_iff_forall at h, rw ← hy, exact h y } end⟩ lemma simple_add_group_of_surjective [add_group α] [add_group β] [simple_add_group α] (f : α → β) [is_add_group_hom f] (hf : function.surjective f) : simple_add_group β := multiplicative.simple_group_iff.1 (@simple_group_of_surjective (multiplicative α) (multiplicative β) _ _ _ f _ hf) attribute [to_additive simple_add_group_of_surjective] simple_group_of_surjective end simple_group
c0b4664db53ed08d3ee4abcc73df41f24a3e4a2a
56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3
/src/evaluation/greedy/gptf.lean
84aed2dfe9295a17a249d30c78e57f88e2d574bb
[ "Apache-2.0" ]
permissive
DyeKuu/lean-tpe-public
3a9968f286ca182723ef7e7d97e155d8cb6b1e70
750ade767ab28037e80b7a80360d213a875038f8
refs/heads/master
1,682,842,633,115
1,621,330,793,000
1,621,330,793,000
368,475,816
0
0
Apache-2.0
1,621,330,745,000
1,621,330,744,000
null
UTF-8
Lean
false
false
1,853
lean
import evaluation_step import backends.greedy.openai section main local notation `ENGINE_ID` := "" local notation `OPENAI_API_KEY` := "" meta def SEARCH_CORE (req : openai.CompletionRequest) (engine_id : string := ENGINE_ID) (api_key : string := OPENAI_API_KEY) (fuel : ℕ := 25) : state_t GreedyProofSearchState tactic unit := openai.openai_greedy_proof_search_core req engine_id api_key fuel meta def main : io unit := do { args ← io.cmdline_args, decls_file ← lift_option $ args.nth 0 | io.fail "must supply decls_file as first argument", dest ← lift_option $ args.nth 1 | io.fail "must supply dest as second argument", max_tokens ← string.to_nat <$> (lift_option $ args.nth 2) | io.fail "must supply max tokens", (some temperature) ← (native.float.of_string <$> (lift_option $ args.nth 3)) | io.fail "must supply temperature", (some top_p) ← (native.float.of_string <$> (lift_option $ args.nth 4)) | io.fail "must supply top_p", n ← string.to_nat <$> (lift_option $ args.nth 5) | io.fail "must supply n", best_of ← string.to_nat <$> (lift_option $ args.nth 6) | io.fail "must supply best_of", fuel ← string.to_nat <$> (lift_option $ args.nth 7) | io.fail "must supply fuel", engine_id ← lift_option $ args.nth 8 | io.fail "must supply engine id", api_key ← lift_option $ args.nth 9 | io.fail "must supply api key", tac_timeout ← string.to_nat <$> args.nth_except 10 "tac_timeout", global_timeout ← string.to_nat <$> args.nth_except 11 "global_timeout", let req := { max_tokens := max_tokens, temperature := temperature, top_p := top_p, n := n, best_of := best_of, ..openai.default_partial_req }, evaluation_harness_from_decls_file (SEARCH_CORE req engine_id api_key fuel) decls_file dest global_timeout $ pure {tac_timeout := tac_timeout} } end main
c0b5dccadf16862d776f66a26cb3df10a4038ccc
f1dc39e1c68f71465c8bf79910c4664d03824751
/library/init/data/nat/basic.lean
10432315890aa73cbf308e2da7ea507e1f9fd986
[ "Apache-2.0" ]
permissive
kckennylau/lean-2
6504f45da07bc98b098d726b74130103be25885c
c9a9368bc0fd600d832bd56c5cb2124b8a523ef9
refs/heads/master
1,659,140,308,864
1,589,361,166,000
1,589,361,166,000
263,748,786
0
0
null
1,589,405,915,000
1,589,405,915,000
null
UTF-8
Lean
false
false
6,063
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import init.logic notation `ℕ` := nat namespace nat inductive less_than_or_equal (a : ℕ) : ℕ → Prop | refl : less_than_or_equal a | step : Π {b}, less_than_or_equal b → less_than_or_equal (succ b) instance : has_le ℕ := ⟨nat.less_than_or_equal⟩ @[reducible] protected def le (n m : ℕ) := nat.less_than_or_equal n m @[reducible] protected def lt (n m : ℕ) := nat.less_than_or_equal (succ n) m instance : has_lt ℕ := ⟨nat.lt⟩ def pred : ℕ → ℕ | 0 := 0 | (a+1) := a protected def sub : ℕ → ℕ → ℕ | a 0 := a | a (b+1) := pred (sub a b) protected def mul : nat → nat → nat | a 0 := 0 | a (b+1) := (mul a b) + a instance : has_sub ℕ := ⟨nat.sub⟩ instance : has_mul ℕ := ⟨nat.mul⟩ instance : decidable_eq ℕ | zero zero := is_true rfl | (succ x) zero := is_false (λ h, nat.no_confusion h) | zero (succ y) := is_false (λ h, nat.no_confusion h) | (succ x) (succ y) := match decidable_eq x y with | is_true xeqy := is_true (xeqy ▸ eq.refl (succ x)) | is_false xney := is_false (λ h, nat.no_confusion h (λ xeqy, absurd xeqy xney)) end def {u} repeat {α : Type u} (f : ℕ → α → α) : ℕ → α → α | 0 a := a | (succ n) a := f n (repeat n a) instance : inhabited ℕ := ⟨nat.zero⟩ @[simp] lemma nat_zero_eq_zero : nat.zero = 0 := rfl /- properties of inequality -/ @[refl] protected def le_refl (a : ℕ) : a ≤ a := less_than_or_equal.refl lemma le_succ (n : ℕ) : n ≤ succ n := less_than_or_equal.step (nat.le_refl n) lemma succ_le_succ {n m : ℕ} : n ≤ m → succ n ≤ succ m := λ h, less_than_or_equal.rec (nat.le_refl (succ n)) (λ a b, less_than_or_equal.step) h lemma zero_le : ∀ (n : ℕ), 0 ≤ n | 0 := nat.le_refl 0 | (n+1) := less_than_or_equal.step (zero_le n) lemma zero_lt_succ (n : ℕ) : 0 < succ n := succ_le_succ (zero_le n) def succ_pos := zero_lt_succ lemma not_succ_le_zero : ∀ (n : ℕ), succ n ≤ 0 → false . lemma not_lt_zero (a : ℕ) : ¬ a < 0 := not_succ_le_zero a lemma pred_le_pred {n m : ℕ} : n ≤ m → pred n ≤ pred m := λ h, less_than_or_equal.rec_on h (nat.le_refl (pred n)) (λ n, nat.rec (λ a b, b) (λ a b c, less_than_or_equal.step) n) lemma le_of_succ_le_succ {n m : ℕ} : succ n ≤ succ m → n ≤ m := pred_le_pred instance decidable_le : ∀ a b : ℕ, decidable (a ≤ b) | 0 b := is_true (zero_le b) | (a+1) 0 := is_false (not_succ_le_zero a) | (a+1) (b+1) := match decidable_le a b with | is_true h := is_true (succ_le_succ h) | is_false h := is_false (λ a, h (le_of_succ_le_succ a)) end instance decidable_lt : ∀ a b : ℕ, decidable (a < b) := λ a b, nat.decidable_le (succ a) b protected lemma eq_or_lt_of_le {a b : ℕ} (h : a ≤ b) : a = b ∨ a < b := less_than_or_equal.cases_on h (or.inl rfl) (λ n h, or.inr (succ_le_succ h)) lemma lt_succ_of_le {a b : ℕ} : a ≤ b → a < succ b := succ_le_succ @[simp] lemma succ_sub_succ_eq_sub (a b : ℕ) : succ a - succ b = a - b := nat.rec_on b (show succ a - succ zero = a - zero, from (eq.refl (succ a - succ zero))) (λ b, congr_arg pred) lemma not_succ_le_self : ∀ n : ℕ, ¬succ n ≤ n := λ n, nat.rec (not_succ_le_zero 0) (λ a b c, b (le_of_succ_le_succ c)) n protected lemma lt_irrefl (n : ℕ) : ¬n < n := not_succ_le_self n protected lemma le_trans {n m k : ℕ} (h1 : n ≤ m) : m ≤ k → n ≤ k := less_than_or_equal.rec h1 (λ p h2, less_than_or_equal.step) lemma pred_le : ∀ (n : ℕ), pred n ≤ n | 0 := less_than_or_equal.refl | (succ a) := less_than_or_equal.step less_than_or_equal.refl lemma pred_lt : ∀ {n : ℕ}, n ≠ 0 → pred n < n | 0 h := absurd rfl h | (succ a) h := lt_succ_of_le less_than_or_equal.refl lemma sub_le (a b : ℕ) : a - b ≤ a := nat.rec_on b (nat.le_refl (a - 0)) (λ b₁, nat.le_trans (pred_le (a - b₁))) lemma sub_lt : ∀ {a b : ℕ}, 0 < a → 0 < b → a - b < a | 0 b h1 h2 := absurd h1 (nat.lt_irrefl 0) | (a+1) 0 h1 h2 := absurd h2 (nat.lt_irrefl 0) | (a+1) (b+1) h1 h2 := eq.symm (succ_sub_succ_eq_sub a b) ▸ show a - b < succ a, from lt_succ_of_le (sub_le a b) protected lemma lt_of_lt_of_le {n m k : ℕ} : n < m → m ≤ k → n < k := nat.le_trans /- Basic nat.add lemmas -/ protected lemma zero_add : ∀ n : ℕ, 0 + n = n | 0 := rfl | (n+1) := congr_arg succ (zero_add n) lemma succ_add : ∀ n m : ℕ, (succ n) + m = succ (n + m) | n 0 := rfl | n (m+1) := congr_arg succ (succ_add n m) lemma add_succ (n m : ℕ) : n + succ m = succ (n + m) := rfl protected lemma add_zero (n : ℕ) : n + 0 = n := rfl lemma add_one (n : ℕ) : n + 1 = succ n := rfl lemma succ_eq_add_one (n : ℕ) : succ n = n + 1 := rfl /- Basic lemmas for comparing numerals -/ protected lemma bit0_succ_eq (n : ℕ) : bit0 (succ n) = succ (succ (bit0 n)) := show succ (succ n + n) = succ (succ (n + n)), from congr_arg succ (succ_add n n) protected lemma zero_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 0 < bit0 n | 0 h := absurd rfl h | (succ n) h := calc 0 < succ (succ (bit0 n)) : zero_lt_succ _ ... = bit0 (succ n) : (nat.bit0_succ_eq n).symm protected lemma zero_lt_bit1 (n : nat) : 0 < bit1 n := zero_lt_succ _ protected lemma bit0_ne_zero : ∀ {n : ℕ}, n ≠ 0 → bit0 n ≠ 0 | 0 h := absurd rfl h | (n+1) h := suffices (n+1) + (n+1) ≠ 0, from this, suffices succ ((n+1) + n) ≠ 0, from this, λ h, nat.no_confusion h protected lemma bit1_ne_zero (n : ℕ) : bit1 n ≠ 0 := show succ (n + n) ≠ 0, from λ h, nat.no_confusion h /- Exponentiation -/ protected def pow (b : ℕ) : ℕ → ℕ | 0 := 1 | (succ n) := pow n * b instance : has_pow nat nat := ⟨nat.pow⟩ lemma pow_succ (b n : ℕ) : b^(succ n) = b^n * b := rfl @[simp] lemma pow_zero (b : ℕ) : b^0 = 1 := rfl end nat
9e65eb87be273e5a168de512dd5bc449ff970961
46125763b4dbf50619e8846a1371029346f4c3db
/src/order/fixed_points.lean
187f81795c3dfc6f9fe60c9eca7a4676bba591b7
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
8,811
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, Kenny Lau Fixed point construction on complete lattices. -/ import order.complete_lattice universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace lattice def fixed_points (f : α → α) : set α := { x | f x = x } section fixedpoint variables [complete_lattice α] {f : α → α} /-- Least fixed point of a monotone function -/ def lfp (f : α → α) : α := Inf {a | f a ≤ a} /-- Greatest fixed point of a monotone function -/ def gfp (f : α → α) : α := Sup {a | a ≤ f a} theorem lfp_le {a : α} (h : f a ≤ a) : lfp f ≤ a := Inf_le h theorem le_lfp {a : α} (h : ∀b, f b ≤ b → a ≤ b) : a ≤ lfp f := le_Inf h theorem lfp_eq (m : monotone f) : lfp f = f (lfp f) := have f (lfp f) ≤ lfp f, from le_lfp $ assume b, assume h : f b ≤ b, le_trans (m (lfp_le h)) h, le_antisymm (lfp_le (m this)) this theorem lfp_induct {p : α → Prop} (m : monotone f) (step : ∀a, p a → a ≤ lfp f → p (f a)) (sup : ∀s, (∀a∈s, p a) → p (Sup s)) : p (lfp f) := let s := {a | a ≤ lfp f ∧ p a} in have p_s : p (Sup s), from sup s (assume a ⟨_, h⟩, h), have Sup s ≤ lfp f, from le_lfp $ assume a, assume h : f a ≤ a, Sup_le $ assume b ⟨b_le, _⟩, le_trans b_le (lfp_le h), have Sup s = lfp f, from le_antisymm this $ lfp_le $ le_Sup ⟨le_trans (m this) $ ge_of_eq $ lfp_eq m, step _ p_s this⟩, this ▸ p_s theorem monotone_lfp : monotone (@lfp α _) := assume f g, assume : f ≤ g, le_lfp $ assume a, assume : g a ≤ a, lfp_le $ le_trans (‹f ≤ g› a) this theorem le_gfp {a : α} (h : a ≤ f a) : a ≤ gfp f := le_Sup h theorem gfp_le {a : α} (h : ∀b, b ≤ f b → b ≤ a) : gfp f ≤ a := Sup_le h theorem gfp_eq (m : monotone f) : gfp f = f (gfp f) := have gfp f ≤ f (gfp f), from gfp_le $ assume b, assume h : b ≤ f b, le_trans h (m (le_gfp h)), le_antisymm this (le_gfp (m this)) theorem gfp_induct {p : α → Prop} (m : monotone f) (step : ∀a, p a → gfp f ≤ a → p (f a)) (inf : ∀s, (∀a∈s, p a) → p (Inf s)) : p (gfp f) := let s := {a | gfp f ≤ a ∧ p a} in have p_s : p (Inf s), from inf s (assume a ⟨_, h⟩, h), have gfp f ≤ Inf s, from gfp_le $ assume a, assume h : a ≤ f a, le_Inf $ assume b ⟨le_b, _⟩, le_trans (le_gfp h) le_b, have Inf s = gfp f, from le_antisymm (le_gfp $ Inf_le ⟨le_trans (le_of_eq $ gfp_eq m) (m this), step _ p_s this⟩) this, this ▸ p_s theorem monotone_gfp : monotone (@gfp α _) := assume f g, assume : f ≤ g, gfp_le $ assume a, assume : a ≤ f a, le_gfp $ le_trans this (‹f ≤ g› a) end fixedpoint section fixedpoint_eqn variables [complete_lattice α] [complete_lattice β] {f : β → α} {g : α → β} -- Rolling rule theorem lfp_comp (m_f : monotone f) (m_g : monotone g) : lfp (f ∘ g) = f (lfp (g ∘ f)) := le_antisymm (lfp_le $ m_f $ ge_of_eq $ lfp_eq $ m_g.comp m_f) (le_lfp $ assume a fg_le, le_trans (m_f $ lfp_le $ show (g ∘ f) (g a) ≤ g a, from m_g fg_le) fg_le) theorem gfp_comp (m_f : monotone f) (m_g : monotone g) : gfp (f ∘ g) = f (gfp (g ∘ f)) := le_antisymm (gfp_le $ assume a fg_le, le_trans fg_le $ m_f $ le_gfp $ show g a ≤ (g ∘ f) (g a), from m_g fg_le) (le_gfp $ m_f $ le_of_eq $ gfp_eq $ m_g.comp m_f) -- Diagonal rule theorem lfp_lfp {h : α → α → α} (m : ∀⦃a b c d⦄, a ≤ b → c ≤ d → h a c ≤ h b d) : lfp (lfp ∘ h) = lfp (λx, h x x) := let f := lfp (lfp ∘ h) in have f_eq : f = lfp (h f), from lfp_eq $ monotone.comp monotone_lfp (assume a b h x, m h (le_refl _)) , le_antisymm (lfp_le $ lfp_le $ ge_of_eq $ lfp_eq $ assume a b h, m h h) (lfp_le $ ge_of_eq $ calc f = lfp (h f) : f_eq ... = h f (lfp (h f)) : lfp_eq $ assume a b h, m (le_refl _) h ... = h f f : congr_arg (h f) f_eq.symm) theorem gfp_gfp {h : α → α → α} (m : ∀⦃a b c d⦄, a ≤ b → c ≤ d → h a c ≤ h b d) : gfp (gfp ∘ h) = gfp (λx, h x x) := let f := gfp (gfp ∘ h) in have f_eq : f = gfp (h f), from gfp_eq $ monotone.comp monotone_gfp (assume a b h x, m h (le_refl _)), le_antisymm (le_gfp $ le_of_eq $ calc f = gfp (h f) : f_eq ... = h f (gfp (h f)) : gfp_eq $ assume a b h, m (le_refl _) h ... = h f f : congr_arg (h f) f_eq.symm) (le_gfp $ le_gfp $ le_of_eq $ gfp_eq $ assume a b h, m h h) end fixedpoint_eqn /- The complete lattice of fixed points of a function f -/ namespace fixed_points variables [complete_lattice α] (f : α → α) (hf : monotone f) def prev (x : α) : α := gfp (λ z, x ⊓ f z) def next (x : α) : α := lfp (λ z, x ⊔ f z) variable {f} theorem prev_le {x : α} : prev f x ≤ x := gfp_le $ λ z hz, le_trans hz inf_le_left lemma prev_eq (hf : monotone f) {a : α} (h : f a ≤ a) : prev f a = f (prev f a) := calc prev f a = a ⊓ f (prev f a) : gfp_eq $ show monotone (λz, a ⊓ f z), from assume x y h, inf_le_inf (le_refl _) (hf h) ... = f (prev f a) : by rw [inf_of_le_right]; exact le_trans (hf prev_le) h def prev_fixed (hf : monotone f) (a : α) (h : f a ≤ a) : fixed_points f := ⟨prev f a, (prev_eq hf h).symm⟩ theorem next_le {x : α} : x ≤ next f x := le_lfp $ λ z hz, le_trans le_sup_left hz lemma next_eq (hf : monotone f) {a : α} (h : a ≤ f a) : next f a = f (next f a) := calc next f a = a ⊔ f (next f a) : lfp_eq $ show monotone (λz, a ⊔ f z), from assume x y h, sup_le_sup (le_refl _) (hf h) ... = f (next f a) : by rw [sup_of_le_right]; exact le_trans h (hf next_le) def next_fixed (hf : monotone f) (a : α) (h : a ≤ f a) : fixed_points f := ⟨next f a, (next_eq hf h).symm⟩ variable f theorem sup_le_f_of_fixed_points (x y : fixed_points f) : x.1 ⊔ y.1 ≤ f (x.1 ⊔ y.1) := sup_le (x.2 ▸ (hf $ show x.1 ≤ f x.1 ⊔ y.1, from x.2.symm ▸ le_sup_left)) (y.2 ▸ (hf $ show y.1 ≤ x.1 ⊔ f y.1, from y.2.symm ▸ le_sup_right)) theorem f_le_inf_of_fixed_points (x y : fixed_points f) : f (x.1 ⊓ y.1) ≤ x.1 ⊓ y.1 := le_inf (x.2 ▸ (hf $ show f (x.1) ⊓ y.1 ≤ x.1, from x.2.symm ▸ inf_le_left)) (y.2 ▸ (hf $ show x.1 ⊓ f (y.1) ≤ y.1, from y.2.symm ▸ inf_le_right)) theorem Sup_le_f_of_fixed_points (A : set α) (HA : A ⊆ fixed_points f) : Sup A ≤ f (Sup A) := Sup_le $ λ x hxA, (HA hxA) ▸ (hf $ le_Sup hxA) theorem f_le_Inf_of_fixed_points (A : set α) (HA : A ⊆ fixed_points f) : f (Inf A) ≤ Inf A := le_Inf $ λ x hxA, (HA hxA) ▸ (hf $ Inf_le hxA) /-- The fixed points of `f` form a complete lattice. This cannot be an instance, since it depends on the monotonicity of `f`. -/ protected def complete_lattice : complete_lattice (fixed_points f) := { le := λx y, x.1 ≤ y.1, le_refl := λ x, le_refl x, le_trans := λ x y z, le_trans, le_antisymm := λ x y hx hy, subtype.eq $ le_antisymm hx hy, sup := λ x y, next_fixed hf (x.1 ⊔ y.1) (sup_le_f_of_fixed_points f hf x y), le_sup_left := λ x y, show x.1 ≤ _, from le_trans le_sup_left next_le, le_sup_right := λ x y, show y.1 ≤ _, from le_trans le_sup_right next_le, sup_le := λ x y z hxz hyz, lfp_le $ sup_le (sup_le hxz hyz) (z.2.symm ▸ le_refl z.1), inf := λ x y, prev_fixed hf (x.1 ⊓ y.1) (f_le_inf_of_fixed_points f hf x y), inf_le_left := λ x y, show _ ≤ x.1, from le_trans prev_le inf_le_left, inf_le_right := λ x y, show _ ≤ y.1, from le_trans prev_le inf_le_right, le_inf := λ x y z hxy hxz, le_gfp $ le_inf (le_inf hxy hxz) (x.2.symm ▸ le_refl x), top := prev_fixed hf ⊤ le_top, le_top := λ ⟨x, H⟩, le_gfp $ le_inf le_top (H.symm ▸ le_refl x), bot := next_fixed hf ⊥ bot_le, bot_le := λ ⟨x, H⟩, lfp_le $ sup_le bot_le (H.symm ▸ le_refl x), Sup := λ A, next_fixed hf (Sup $ subtype.val '' A) (Sup_le_f_of_fixed_points f hf (subtype.val '' A) (λ z ⟨x, hx⟩, hx.2 ▸ x.2)), le_Sup := λ A x hxA, show x.1 ≤ _, from le_trans (le_Sup $ show x.1 ∈ subtype.val '' A, from ⟨x, hxA, rfl⟩) next_le, Sup_le := λ A x Hx, lfp_le $ sup_le (Sup_le $ λ z ⟨y, hyA, hyz⟩, hyz ▸ Hx y hyA) (x.2.symm ▸ le_refl x), Inf := λ A, prev_fixed hf (Inf $ subtype.val '' A) (f_le_Inf_of_fixed_points f hf (subtype.val '' A) (λ z ⟨x, hx⟩, hx.2 ▸ x.2)), le_Inf := λ A x Hx, le_gfp $ le_inf (le_Inf $ λ z ⟨y, hyA, hyz⟩, hyz ▸ Hx y hyA) (x.2.symm ▸ le_refl x.1), Inf_le := λ A x hxA, show _ ≤ x.1, from le_trans prev_le (Inf_le $ show x.1 ∈ subtype.val '' A, from ⟨x, hxA, rfl⟩) } end fixed_points end lattice
703b034d96f1cab98953b4d6a565e9c8b5541528
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/num/lemmas.lean
6e1aeaa0c269e16d47f33636ce02cee44544ec16
[ "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
48,635
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.num.bitwise import data.int.char_zero import data.nat.gcd /-! # Properties of the binary representation of integers -/ local attribute [simp] add_assoc namespace pos_num variables {α : Type*} @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl @[simp] theorem cast_one' [has_zero α] [has_one α] [has_add α] : (pos_num.one : α) = 1 := rfl @[simp, norm_cast] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp, norm_cast] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : pos_num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp [add_left_comm] theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp [add_left_comm] | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp [add_left_comm] | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp [add_comm, add_left_comm] | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp [add_left_comm] theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[norm_cast] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, 0 < (n : ℕ) | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[norm_cast] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp, norm_cast] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] : (num.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] (n : pos_num) : (num.pos n : α) = n := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp, norm_cast] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp, norm_cast] theorem to_nat_to_int (n : num) : ((n : ℕ) : ℤ) = n := by rw [← int.nat_cast_eq_coe_nat, cast_to_nat] @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← to_nat_to_int, int.cast_coe_nat, cast_to_nat] @[norm_cast] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] @[simp, norm_cast] theorem of_nat_cast [add_monoid α] [has_one α] (n : ℕ) : ((n : num) : α) = n := by rw [← cast_to_nat, to_of_nat] @[norm_cast] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.left_inverse.injective to_of_nat h, congr_arg _⟩ @[norm_cast] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[norm_cast] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[norm_cast] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[norm_cast] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp, norm_cast] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat @[norm_cast] theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm, add_comm] instance : ordered_cancel_add_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_add_comm_monoid } @[norm_cast] theorem dvd_to_nat (m n : num) : (m : ℕ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_nat n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e, mul_to_nat]⟩⟩ end num namespace pos_num variables {α : Type*} open num @[norm_cast] theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] instance : has_dvd pos_num := ⟨λ m n, pos m ∣ pos n⟩ @[norm_cast] theorem dvd_to_nat {m n : pos_num} : (m:ℕ) ∣ n ↔ m ∣ n := num.dvd_to_nat (pos m) (pos n) theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 1 := rfl | (bit0 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] | (bit1 n) := by rw [size, succ_to_nat, nat_size, size_eq_nat_size] theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] theorem nat_size_pos (n) : 0 < nat_size n := by cases n; apply nat.succ_pos meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] @[simp, norm_cast] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast, priority 500] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem cast_inj [add_monoid α] [has_one α] [char_zero α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] @[simp] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos @[simp] theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : 0 < (n : α) := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp, norm_cast] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] @[simp] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp, norm_cast] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp, norm_cast] theorem cast_bit0 [semiring α] (n : num) : (n.bit0 : α) = _root_.bit0 n := by rw [← bit0_of_bit0, _root_.bit0, cast_add]; refl @[simp, norm_cast] theorem cast_bit1 [semiring α] (n : num) : (n.bit1 : α) = _root_.bit1 n := by rw [← bit1_of_bit1, _root_.bit1, bit0_of_bit0, cast_add, cast_bit0]; refl @[simp, norm_cast] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 0 := nat.size_zero.symm | (pos p) := p.size_to_nat theorem size_eq_nat_size : ∀ n, (size n : ℕ) = nat_size n | 0 := rfl | (pos p) := p.size_eq_nat_size theorem nat_size_to_nat (n) : nat_size n = nat.size n := by rw [← size_eq_nat_size, size_to_nat] @[simp] theorem of_nat'_eq : ∀ n, num.of_nat' n = n := nat.binary_rec rfl $ λ b n IH, begin rw of_nat' at IH ⊢, rw [nat.binary_rec_eq, IH], { cases b; simp [nat.bit, bit0_of_bit0, bit1_of_bit1] }, { refl } end theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl theorem to_znum_inj {m n : num} : m.to_znum = n.to_znum ↔ m = n := ⟨λ h, by cases m; cases n; cases h; refl, congr_arg _⟩ @[simp, norm_cast squash] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp, norm_cast] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp, norm_cast] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, simp, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH end @[simp, norm_cast] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp, norm_cast] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_zero' [has_zero α] [has_one α] [has_add α] [has_neg α] : (znum.zero : α) = 0 := rfl @[simp, norm_cast] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp, norm_cast] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp, norm_cast] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem abs_to_nat : ∀ n, (abs n : ℕ) = int.nat_abs n | 0 := rfl | (pos p) := congr_arg int.nat_abs p.to_nat_to_int | (neg p) := show int.nat_abs ((p:ℕ):ℤ) = int.nat_abs (- p), by rw [p.to_nat_to_int, int.nat_abs_neg] @[simp] theorem abs_to_znum : ∀ n : num, abs n.to_znum = n | 0 := rfl | (num.pos p) := rfl @[simp, norm_cast] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp, norm_cast] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp, norm_cast] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp [add_comm]}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp [add_comm, add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit0, sub_eq_add_neg] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), { simp [add_comm, add_left_comm] }, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp [add_left_comm]}, simpa [_root_.bit1, _root_.bit0, sub_eq_add_neg] end theorem to_nat_eq_succ_pred (n : pos_num) : (n:ℕ) = n.pred' + 1 := by rw [← num.succ'_to_nat, n.succ'_pred'] theorem to_int_eq_succ_pred (n : pos_num) : (n:ℤ) = (n.pred' : ℕ) + 1 := by rw [← n.to_nat_to_int, to_nat_eq_succ_pred]; refl end pos_num namespace num variables {α : Type*} @[simp] theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] theorem mem_of_znum' : ∀ {m : num} {n : znum}, m ∈ of_znum' n ↔ n = to_znum m | 0 0 := ⟨λ _, rfl, λ _, rfl⟩ | (pos m) 0 := ⟨λ h, by cases h, λ h, by cases h⟩ | m (znum.pos p) := option.some_inj.trans $ by cases m; split; intro h; try {cases h}; refl | m (znum.neg p) := ⟨λ h, by cases h, λ h, by cases m; cases h⟩ theorem of_znum'_to_nat : ∀ (n : znum), coe <$> of_znum' n = int.to_nat' n | 0 := rfl | (znum.pos p) := show _ = int.to_nat' p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat' (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem of_znum_to_nat : ∀ (n : znum), (of_znum n : ℕ) = int.to_nat n | 0 := rfl | (znum.pos p) := show _ = int.to_nat p, by rw [← pos_num.to_nat_to_int p]; refl | (znum.neg p) := congr_arg (λ x, int.to_nat (-x)) $ show ((p.pred' + 1 : ℕ) : ℤ) = p, by rw ← succ'_to_nat; simp @[simp] theorem cast_of_znum [add_group α] [has_one α] (n : znum) : (of_znum n : α) = int.to_nat n := by rw [← cast_to_nat, of_znum_to_nat] @[simp, norm_cast] theorem sub_to_nat (m n) : ((m - n : num) : ℕ) = m - n := show (of_znum _ : ℕ) = _, by rw [of_znum_to_nat, cast_sub', ← to_nat_to_int, ← to_nat_to_int, int.to_nat_sub] end num namespace znum variables {α : Type*} @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp [add_comm] | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp [add_comm] @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp, norm_cast] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp, norm_cast] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl @[norm_cast] theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.left_inverse.injective of_to_int h, congr_arg _⟩ @[simp, norm_cast] theorem of_int_cast [add_group α] [has_one α] (n : ℤ) : ((n : znum) : α) = n := by rw [← cast_to_int, to_of_int] @[simp, norm_cast] theorem of_nat_cast [add_group α] [has_one α] (n : ℕ) : ((n : znum) : α) = n := of_int_cast n @[simp] theorem of_int'_eq : ∀ n, znum.of_int' n = n | (n : ℕ) := to_int_inj.1 $ by simp [znum.of_int'] | -[1+ n] := to_int_inj.1 $ by simp [znum.of_int'] theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((m:ℤ) > n) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[norm_cast] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp, norm_cast] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [add_comm, add_left_comm, mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, exists_pair_ne := ⟨0, 1, dec_trivial⟩, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, mul_pos := λ a b, show 0 < a → 0 < b → 0 < a * b, by {transfer_rw, apply mul_pos}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } @[simp, norm_cast] theorem dvd_to_int (m n : znum) : (m : ℤ) ∣ n ↔ m ∣ n := ⟨λ ⟨k, e⟩, ⟨k, by rw [← of_to_int n, e]; simp⟩, λ ⟨k, e⟩, ⟨k, by simp [e]⟩⟩ end znum namespace pos_num theorem divmod_to_nat_aux {n d : pos_num} {q r : num} (h₁ : (r:ℕ) + d * _root_.bit0 q = n) (h₂ : (r:ℕ) < 2 * d) : ((divmod_aux d q r).2 + d * (divmod_aux d q r).1 : ℕ) = ↑n ∧ ((divmod_aux d q r).2 : ℕ) < d := begin unfold divmod_aux, have : ∀ {r₂}, num.of_znum' (num.sub' r (num.pos d)) = some r₂ ↔ (r : ℕ) = r₂ + d, { intro r₂, apply num.mem_of_znum'.trans, rw [← znum.to_int_inj, num.cast_to_znum, num.cast_sub', sub_eq_iff_eq_add, ← int.coe_nat_inj'], simp }, cases e : num.of_znum' (num.sub' r (num.pos d)) with r₂; simp [divmod_aux], { refine ⟨h₁, lt_of_not_ge (λ h, _)⟩, cases nat.le.dest h with r₂ e', rw [← num.to_of_nat r₂, add_comm] at e', cases e.symm.trans (this.2 e'.symm) }, { have := this.1 e, split, { rwa [_root_.bit1, add_comm _ 1, mul_add, mul_one, ← add_assoc, ← this] }, { rwa [this, two_mul, add_lt_add_iff_right] at h₂ } } end theorem divmod_to_nat (d n : pos_num) : (n / d : ℕ) = (divmod d n).1 ∧ (n % d : ℕ) = (divmod d n).2 := begin rw nat.div_mod_unique (pos_num.cast_pos _), induction n with n IH n IH, { exact divmod_to_nat_aux (by simp; refl) (nat.mul_le_mul_left 2 (pos_num.cast_pos d : (0 : ℕ) < d)) }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [_root_.bit1, _root_.bit1, add_right_comm, bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit1_lt_bit0 IH.2 } }, { unfold divmod, cases divmod d n with q r, simp only [divmod] at IH ⊢, apply divmod_to_nat_aux; simp, { rw [bit0_eq_two_mul ↑n, ← IH.1, mul_add, ← bit0_eq_two_mul, mul_left_comm, ← bit0_eq_two_mul] }, { rw ← bit0_eq_two_mul, exact nat.bit0_lt IH.2 } } end @[simp] theorem div'_to_nat (n d) : (div' n d : ℕ) = n / d := (divmod_to_nat _ _).1.symm @[simp] theorem mod'_to_nat (n d) : (mod' n d : ℕ) = n % d := (divmod_to_nat _ _).2.symm end pos_num namespace num @[simp, norm_cast] theorem div_to_nat : ∀ n d, ((n / d : num) : ℕ) = n / d | 0 0 := rfl | 0 (pos d) := (nat.zero_div _).symm | (pos n) 0 := (nat.div_zero _).symm | (pos n) (pos d) := pos_num.div'_to_nat _ _ @[simp, norm_cast] theorem mod_to_nat : ∀ n d, ((n % d : num) : ℕ) = n % d | 0 0 := rfl | 0 (pos d) := (nat.zero_mod _).symm | (pos n) 0 := (nat.mod_zero _).symm | (pos n) (pos d) := pos_num.mod'_to_nat _ _ theorem gcd_to_nat_aux : ∀ {n} {a b : num}, a ≤ b → (a * b).nat_size ≤ n → (gcd_aux n a b : ℕ) = nat.gcd a b | 0 0 b ab h := (nat.gcd_zero_left _).symm | 0 (pos a) 0 ab h := (not_lt_of_ge ab).elim rfl | 0 (pos a) (pos b) ab h := (not_lt_of_le h).elim $ pos_num.nat_size_pos _ | (nat.succ n) 0 b ab h := (nat.gcd_zero_left _).symm | (nat.succ n) (pos a) b ab h := begin simp [gcd_aux], rw [nat.gcd_rec, gcd_to_nat_aux, mod_to_nat], {refl}, { rw [← le_to_nat, mod_to_nat], exact le_of_lt (nat.mod_lt _ (pos_num.cast_pos _)) }, rw [nat_size_to_nat, mul_to_nat, nat.size_le] at h ⊢, rw [mod_to_nat, mul_comm], rw [nat.pow_succ, ← nat.mod_add_div b (pos a)] at h, refine lt_of_mul_lt_mul_right (lt_of_le_of_lt _ h) (nat.zero_le 2), rw [mul_two, mul_add], refine add_le_add_left (nat.mul_le_mul_left _ (le_trans (le_of_lt (nat.mod_lt _ (pos_num.cast_pos _))) _)) _, suffices : 1 ≤ _, simpa using nat.mul_le_mul_left (pos a) this, rw [nat.le_div_iff_mul_le _ _ a.cast_pos, one_mul], exact le_to_nat.2 ab end @[simp] theorem gcd_to_nat : ∀ a b, (gcd a b : ℕ) = nat.gcd a b := have ∀ a b : num, (a * b).nat_size ≤ a.nat_size + b.nat_size, begin intros, simp [nat_size_to_nat], rw [nat.size_le, nat.pow_add], exact mul_lt_mul'' (nat.lt_size_self _) (nat.lt_size_self _) (nat.zero_le _) (nat.zero_le _) end, begin intros, unfold gcd, split_ifs, { exact gcd_to_nat_aux h (this _ _) }, { rw nat.gcd_comm, exact gcd_to_nat_aux (le_of_not_le h) (this _ _) } end theorem dvd_iff_mod_eq_zero {m n : num} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_nat, nat.dvd_iff_mod_eq_zero, ← to_nat_inj, mod_to_nat]; refl instance decidable_dvd : decidable_rel ((∣) : num → num → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end num instance pos_num.decidable_dvd : decidable_rel ((∣) : pos_num → pos_num → Prop) | a b := num.decidable_dvd _ _ namespace znum @[simp, norm_cast] theorem div_to_int : ∀ n d, ((n / d : znum) : ℤ) = n / d | 0 0 := rfl | 0 (pos d) := (int.zero_div _).symm | 0 (neg d) := (int.zero_div _).symm | (pos n) 0 := (int.div_zero _).symm | (neg n) 0 := (int.div_zero _).symm | (pos n) (pos d) := (num.cast_to_znum _).trans $ by rw ← num.to_nat_to_int; simp | (pos n) (neg d) := (num.cast_to_znum_neg _).trans $ by rw ← num.to_nat_to_int; simp | (neg n) (pos d) := show - _ = (-_/↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change -[1+ n.pred' / ↑d] = -[1+ n.pred' / (d.pred' + 1)], rw d.to_nat_eq_succ_pred end | (neg n) (neg d) := show ↑(pos_num.pred' n / num.pos d).succ' = (-_ / -↑d), begin rw [n.to_int_eq_succ_pred, d.to_int_eq_succ_pred, ← pos_num.to_nat_to_int, num.succ'_to_nat, num.div_to_nat], change (nat.succ (_/d) : ℤ) = nat.succ (n.pred'/(d.pred' + 1)), rw d.to_nat_eq_succ_pred end @[simp, norm_cast] theorem mod_to_int : ∀ n d, ((n % d : znum) : ℤ) = n % d | 0 d := (int.zero_mod _).symm | (pos n) d := (num.cast_to_znum _).trans $ by rw [← num.to_nat_to_int, cast_pos, num.mod_to_nat, ← pos_num.to_nat_to_int, abs_to_nat]; refl | (neg n) d := (num.cast_sub' _ _).trans $ by rw [← num.to_nat_to_int, cast_neg, ← num.to_nat_to_int, num.succ_to_nat, num.mod_to_nat, abs_to_nat, ← int.sub_nat_nat_eq_coe, n.to_int_eq_succ_pred]; refl @[simp] theorem gcd_to_nat (a b) : (gcd a b : ℕ) = int.gcd a b := (num.gcd_to_nat _ _).trans $ by simpa theorem dvd_iff_mod_eq_zero {m n : znum} : m ∣ n ↔ n % m = 0 := by rw [← dvd_to_int, int.dvd_iff_mod_eq_zero, ← to_int_inj, mod_to_int]; refl instance : decidable_rel ((∣) : znum → znum → Prop) | a b := decidable_of_iff' _ dvd_iff_mod_eq_zero end znum namespace int def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
b1b06989d109275d6d8032b13a52edaecc4a6ded
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/MetavarContext.lean
132b0b0c28b7d9141f720c0ee64a73a332881d12
[ "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
54,438
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.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind where | natural | synthetic | syntheticOpaque deriving Inhabited, Repr def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl where userName : Name := Name.anonymous lctx : LocalContext type : Expr depth : Nat localInstances : LocalInstances kind : MetavarKind numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` index : Nat -- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment where lctx : LocalContext fvars : Array Expr val : Expr open Std (HashMap PersistentHashMap) structure MetavarContext where depth : Nat := 0 mvarCounter : Nat := 0 -- Counter for setting the field `index` at `MetavarDecl` lDepth : PersistentHashMap MVarId Nat := {} decls : PersistentHashMap MVarId MetavarDecl := {} userNames : PersistentHashMap Name MVarId := {} lAssignment : PersistentHashMap MVarId Level := {} eAssignment : PersistentHashMap MVarId Expr := {} dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } userNames := if userName.isAnonymous then mctx.userNames else mctx.userNames.insert userName mvarId } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := mctx.userNames.find? userName def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } userNames := let userNames := mctx.userNames.erase decl.userName if userName.isAnonymous then userNames else userNames.insert userName mvarId } /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot m mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId /- Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId _) => do match getLevelAssignment? (← getMCtx) mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s) | Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl) | Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b) | Expr.app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | Expr.mvar mvarId _ => let mctx ← getMCtx match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars val if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache { val := e : ExprStructEq } fun _ => do let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some newE => do let newE' ← instantiateExprMVars newE modifyMCtx fun mctx => mctx.assignExpr mvarId newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr $ StateRefT MetavarContext $ ST ω) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (init := ({}, mctx)) fun (lctx, mctx) ldecl => match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type let (value, mctx) := mctx.instantiateMVars value (lctx.mkLetDecl fvarId userName type value nonDep, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx let (type, mctx) := mctx.instantiateMVars mvarDecl.type { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).contains e then return false else modify fun s => s.insert e return true @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitMain : Expr → M Bool | Expr.proj _ _ s _ => visit s | Expr.forallE _ d b _ => visit d <||> visit b | Expr.lam _ d b _ => visit d <||> visit b | Expr.letE _ t v b _ => visit t <||> visit v <||> visit b | Expr.mdata _ b _ => visit b | Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f | Expr.mvar mvarId _ => match mctx.getExprAssignment? mvarId with | some a => visit a | none => let lctx := (mctx.getDecl mvarId).lctx return lctx.any fun decl => p decl.fvarId | Expr.fvar fvarId _ => return p fvarId | e => pure false visit e @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := DependsOn.main mctx p e |>.run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl (type := t) .. => findExprDependsOn mctx t p | LocalDecl.ldecl (type := t) (value := v) .. => (DependsOn.main mctx p t <||> DependsOn.main mctx p v).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool MCore def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := Id.run <| do let mut d : LocalDecl := lctx.getFVar! xs[0] for i in [1:xs.size] do let curr := lctx.getFVar! xs[i] if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do if toRevert.size == 0 then pure toRevert else if preserveOrder then -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i] let decl := lctx.getFVar! fvar i.forM fun j => do let prevFVar := toRevert[j] let prevDecl := lctx.getFVar! prevFVar if localDeclDependsOn mctx prevDecl fvar.fvarId! then throw (Exception.revertFailure mctx lctx toRevert prevDecl) let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => if initSize.any fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => lctx.erase x.fvarId! @[inline] private def getMCtx : M MetavarContext := return (← get).mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => exprDependsOn mctx e fvarId mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | Expr.proj _ _ s _ => return e.updateProj! (← visit xs s) | Expr.forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | Expr.letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | Expr.mdata _ b _ => return e.updateMData! (← visit xs b) | Expr.app _ _ _ => e.withApp fun f args => elimApp xs f args | Expr.mvar mvarId _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta let type ← abstractRangeAux xs i type pure <| Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 pure <| mkForall n BinderInfo.default type e | _ => pure e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mctx ← getMCtx let mvarDecl := mctx.getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let rec cont (nestedFVars : Array Expr) (nestedLCtx : LocalContext) : M (Expr × Array Expr) := do let args ← args.mapM (visit xs) let preserve ← preserveOrder match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => let newMVarLCtx := reduceLocalContext mvarLCtx toRevert let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := { name := (← get).ngen.curr } let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } match newMVarKind with | MetavarKind.syntheticOpaque => modify fun s => { s with mctx := assignDelayed s.mctx newMVarId nestedLCtx (toRevert ++ nestedFVars) (mkAppN (mkMVar mvarId) nestedFVars) } | _ => modify fun s => { s with mctx := assignExpr s.mctx mvarId result } return (mkAppN result args, toRevert) if !mvarDecl.kind.isSyntheticOpaque then cont #[] mvarLCtx else match mctx.getDelayedAssignment? mvarId with | none => cont #[] mvarLCtx | some { fvars := fvars, lctx := nestedLCtx, .. } => cont fvars nestedLCtx -- Remark: nestedLCtx is bigger than mvarLCtx private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId _ => match (← getMCtx).getExprAssignment? mvarId with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (fun i (p : Expr × Nat) => do let (e, num) := p; let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun _ => MkBinding.revert xs mvarId preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly usedLetOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := true) xs e usedOnly usedLetOnly pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := false) xs e usedOnly usedLetOnly pure e @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun _ => MkBinding.abstractRange xs n e false /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed mctx lctx e | Expr.proj _ _ e _ => isWellFormed mctx lctx e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b) | Expr.const .. => true | Expr.bvar .. => true | Expr.sort .. => true | Expr.lit .. => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed mctx lctx v | Expr.fvar fvarId _ => lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context $ StateM State instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | Level.succ v _ => return u.updateSucc! (← visitLevel v) | Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | Level.zero _ => pure u | Level.param .. => pure u | Level.mvar mvarId _ => let s ← get match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => let p ← mkParamName let p := mkLevelParam p modify fun s => { s with mctx := s.mctx.assignLevel mvarId p } pure p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← main s) | Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | Expr.app .. => e.withApp fun f args => visitApp f args | Expr.mdata _ b _ => return e.updateMData! (← main b) | Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel) | Expr.sort u _ => return e.updateSort! (← visitLevel u) | Expr.mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId .. => match (← get).mctx.getExprAssignment? mvarId with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx } { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
6336b46cd3448b27561e1c18df30195ee15ece1e
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/list/cycle.lean
2bd3e95ee54b4afd9f9cc40d52b705f92a34ce8e
[ "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
30,218
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.multiset.sort import data.fintype.list import data.list.rotate /-! # Cycles of a list Lists have an equivalence relation of whether they are rotational permutations of one another. This relation is defined as `is_rotated`. Based on this, we define the quotient of lists by the rotation relation, called `cycle`. We also define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ namespace list variables {α : Type*} [decidable_eq α] /-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/ def next_or : Π (xs : list α) (x default : α), α | [] x default := default | [y] x default := default -- Handles the not-found and the wraparound case | (y :: z :: xs) x default := if x = y then z else next_or (z :: xs) x default @[simp] lemma next_or_nil (x d : α) : next_or [] x d = d := rfl @[simp] lemma next_or_singleton (x y d : α) : next_or [y] x d = d := rfl @[simp] lemma next_or_self_cons_cons (xs : list α) (x y d : α) : next_or (x :: y :: xs) x d = y := if_pos rfl lemma next_or_cons_of_ne (xs : list α) (y x d : α) (h : x ≠ y) : next_or (y :: xs) x d = next_or xs x d := begin cases xs with z zs, { refl }, { exact if_neg h } end /-- `next_or` does not depend on the default value, if the next value appears. -/ lemma next_or_eq_next_or_of_mem_of_ne (xs : list α) (x d d' : α) (x_mem : x ∈ xs) (x_ne : x ≠ xs.last (ne_nil_of_mem x_mem)) : next_or xs x d = next_or xs x d' := begin induction xs with y ys IH, { cases x_mem }, cases ys with z zs, { simp at x_mem x_ne, contradiction }, by_cases h : x = y, { rw [h, next_or_self_cons_cons, next_or_self_cons_cons] }, { rw [next_or, next_or, IH]; simpa [h] using x_mem } end lemma mem_of_next_or_ne {xs : list α} {x d : α} (h : next_or xs x d ≠ d) : x ∈ xs := begin induction xs with y ys IH, { simpa using h }, cases ys with z zs, { simpa using h }, { by_cases hx : x = y, { simp [hx] }, { rw [next_or_cons_of_ne _ _ _ _ hx] at h, simpa [hx] using IH h } } end lemma next_or_concat {xs : list α} {x : α} (d : α) (h : x ∉ xs) : next_or (xs ++ [x]) x d = d := begin induction xs with z zs IH, { simp }, { obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h), rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs] } end lemma next_or_mem {xs : list α} {x d : α} (hd : d ∈ xs) : next_or xs x d ∈ xs := begin revert hd, suffices : ∀ (xs' : list α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs', { exact this xs (λ _, id) }, intros xs' hxs' hd, induction xs with y ys ih, { exact hd }, cases ys with z zs, { exact hd }, rw next_or, split_ifs with h, { exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _)) }, { exact ih (λ _ h, hxs' _ (mem_cons_of_mem _ h)) }, end /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. For example: * `next [1, 2, 3] 2 _ = 3` * `next [1, 2, 3] 3 _ = 1` * `next [1, 2, 3, 2, 4] 2 _ = 3` * `next [1, 2, 3, 2] 2 _ = 3` * `next [1, 1, 2, 3, 2] 1 _ = 1` -/ def next (l : list α) (x : α) (h : x ∈ l) : α := next_or l x (l.nth_le 0 (length_pos_of_mem h)) /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. * `prev [1, 2, 3] 2 _ = 1` * `prev [1, 2, 3] 1 _ = 3` * `prev [1, 2, 3, 2, 4] 2 _ = 1` * `prev [1, 2, 3, 4, 2] 2 _ = 1` * `prev [1, 1, 2] 1 _ = 2` -/ def prev : Π (l : list α) (x : α) (h : x ∈ l), α | [] _ h := by simpa using h | [y] _ _ := y | (y :: z :: xs) x h := if hx : x = y then (last (z :: xs) (cons_ne_nil _ _)) else if x = z then y else prev (z :: xs) x (by simpa [hx] using h) variables (l : list α) (x : α) (h : x ∈ l) @[simp] lemma next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y := rfl @[simp] lemma prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y := rfl lemma next_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : next (y :: z :: l) x h = z := by rw [next, next_or, if_pos hx] @[simp] lemma next_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : next (x :: z :: l) x h = z := next_cons_cons_eq' l x x z h rfl lemma next_ne_head_ne_last (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x ≠ last (y :: l) (cons_ne_nil _ _)) : next (y :: l) x h = next l x (by simpa [hy] using h) := begin rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne], { rwa last_cons at hx }, { simpa [hy] using h } end lemma next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l) (h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) : next (y :: l ++ [x]) x h = y := begin rw [next, next_or_concat], { refl }, { simp [hy, hx] } end lemma next_last_cons (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x = last (y :: l) (cons_ne_nil _ _)) (hl : nodup l) : next (y :: l) x h = y := begin rw [next, nth_le, ←init_append_last (cons_ne_nil y l), hx, next_or_concat], subst hx, intro H, obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H, { simpa [init_eq_take, nth_le_take', hy.symm] using hk' }, suffices : k.succ = l.length, { simpa [this] using hk }, cases l with hd tl, { simpa using hk }, { rw nodup_iff_nth_le_inj at hl, rw [length, nat.succ_inj'], apply hl, simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk' } end lemma prev_last_cons' (y : α) (h : x ∈ (y :: l)) (hx : x = y) : prev (y :: l) x h = last (y :: l) (cons_ne_nil _ _) := begin cases l; simp [prev, hx] end @[simp] lemma prev_last_cons (h : x ∈ (x :: l)) : prev (x :: l) x h = last (x :: l) (cons_ne_nil _ _) := prev_last_cons' l x x h rfl lemma prev_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : prev (y :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx] @[simp] lemma prev_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : prev (x :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := prev_cons_cons_eq' l x x z h rfl lemma prev_cons_cons_of_ne' (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x = z) : prev (y :: z :: l) x h = y := begin cases l, { simp [prev, hy, hz] }, { rw [prev, dif_neg hy, if_pos hz] } end lemma prev_cons_cons_of_ne (y : α) (h : x ∈ (y :: x :: l)) (hy : x ≠ y) : prev (y :: x :: l) x h = y := prev_cons_cons_of_ne' _ _ _ _ _ hy rfl lemma prev_ne_cons_cons (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x ≠ z) : prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := begin cases l, { simpa [hy, hz] using h }, { rw [prev, dif_neg hy, if_neg hz] } end include h lemma next_mem : l.next x h ∈ l := next_or_mem (nth_le_mem _ _ _) lemma prev_mem : l.prev x h ∈ l := begin cases l with hd tl, { simpa using h }, induction tl with hd' tl hl generalizing hd, { simp }, { by_cases hx : x = hd, { simp only [hx, prev_cons_cons_eq], exact mem_cons_of_mem _ (last_mem _) }, { rw [prev, dif_neg hx], split_ifs with hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ (hl _ _) } } } end lemma next_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : next l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + 1) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing x n, { simp }, { cases n, { simp }, { have hn' : n.succ ≤ l.length.succ, { refine nat.succ_le_of_lt _, simpa [nat.succ_lt_succ_iff] using hn }, have hx': (x :: y :: l).nth_le n.succ hn ≠ x, { intro H, suffices : n.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, rcases hn'.eq_or_lt with hn''|hn'', { rw [next_last_cons], { simp [hn''] }, { exact hx' }, { simp [last_eq_nth_le, hn''] }, { exact h.of_cons } }, { have : n < l.length := by simpa [nat.succ_lt_succ_iff] using hn'' , rw [next_ne_head_ne_last _ _ _ _ hx'], { simp [nat.mod_eq_of_lt (nat.succ_lt_succ (nat.succ_lt_succ this)), hl _ _ h.of_cons, nat.mod_eq_of_lt (nat.succ_lt_succ this)] }, { rw last_eq_nth_le, intro H, suffices : n.succ = l.length.succ, { exact absurd hn'' this.ge.not_lt }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn _ _, { simp }, { simpa using H } } } } } end lemma prev_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : prev l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + (l.length - 1)) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing n x, { simp }, { rcases n with _|_|n, { simpa [last_eq_nth_le, nat.mod_eq_of_lt (nat.succ_lt_succ l.length.lt_succ_self)] }, { simp only [mem_cons_iff, nodup_cons] at h, push_neg at h, simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm] }, { rw [prev_ne_cons_cons], { convert hl _ _ h.of_cons _ using 1, have : ∀ k hk, (y :: l).nth_le k hk = (x :: y :: l).nth_le (k + 1) (nat.succ_lt_succ hk), { intros, simpa }, rw [this], congr, simp only [nat.add_succ_sub_one, add_zero, length], simp only [length, nat.succ_lt_succ_iff] at hn, set k := l.length, rw [nat.succ_add, ←nat.add_succ, nat.add_mod_right, nat.succ_add, ←nat.add_succ _ k, nat.add_mod_right, nat.mod_eq_of_lt, nat.mod_eq_of_lt], { exact nat.lt_succ_of_lt hn }, { exact nat.succ_lt_succ (nat.lt_succ_of_lt hn) } }, { intro H, suffices : n.succ.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, { intro H, suffices : n.succ.succ = 1, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn (nat.succ_lt_succ nat.succ_pos') _, simpa using H } } } end lemma pmap_next_eq_rotate_one (h : nodup l) : l.pmap l.next (λ _ h, h) = l.rotate 1 := begin apply list.ext_le, { simp }, { intros, rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h] } end lemma pmap_prev_eq_rotate_length_sub_one (h : nodup l) : l.pmap l.prev (λ _ h, h) = l.rotate (l.length - 1) := begin apply list.ext_le, { simp }, { intros n hn hn', rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h] } end lemma prev_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l (next l x hx) (next_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma next_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l (prev l x hx) (prev_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma prev_reverse_eq_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l.reverse x (mem_reverse.mpr hx) = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, have lpos : 0 < l.length := k.zero_le.trans_lt hk, have key : l.length - 1 - k < l.length := (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos'), rw ←nth_le_pmap l.next (λ _ h, h) (by simpa using hk), simp_rw [←nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h], rw ←nth_le_pmap l.reverse.prev (λ _ h, h), { simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse, length_reverse, nat.mod_eq_of_lt (tsub_lt_self lpos nat.succ_pos'), tsub_tsub_cancel_of_le (nat.succ_le_of_lt lpos)], rw ←nth_le_reverse, { simp [tsub_tsub_cancel_of_le (nat.le_pred_of_lt hk)] }, { simpa using (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos') } }, { simpa using (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos') } end lemma next_reverse_eq_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l.reverse x (mem_reverse.mpr hx) = prev l x hx := begin convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm, exact (reverse_reverse l).symm end lemma is_rotated_next_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.next x hx = l'.next x (h.mem_iff.mp hx) := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, obtain ⟨n, rfl⟩ := id h, rw [next_nth_le _ hn], simp_rw ←nth_le_rotate' _ n k, rw [next_nth_le _ (h.nodup_iff.mp hn), ←nth_le_rotate' _ n], simp [add_assoc] end lemma is_rotated_prev_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.prev x hx = l'.prev x (h.mem_iff.mp hx) := begin rw [←next_reverse_eq_prev _ hn, ←next_reverse_eq_prev _ (h.nodup_iff.mp hn)], exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _ end end list open list /-- `cycle α` is the quotient of `list α` by cyclic permutation. Duplicates are allowed. -/ def cycle (α : Type*) : Type* := quotient (is_rotated.setoid α) namespace cycle variables {α : Type*} instance : has_coe (list α) (cycle α) := ⟨quot.mk _⟩ @[simp] lemma coe_eq_coe {l₁ l₂ : list α} : (l₁ : cycle α) = l₂ ↔ (l₁ ~r l₂) := @quotient.eq _ (is_rotated.setoid _) _ _ @[simp] lemma mk_eq_coe (l : list α) : quot.mk _ l = (l : cycle α) := rfl @[simp] lemma mk'_eq_coe (l : list α) : quotient.mk' l = (l : cycle α) := rfl lemma coe_cons_eq_coe_append (l : list α) (a : α) : (↑(a :: l) : cycle α) = ↑(l ++ [a]) := quot.sound ⟨1, by rw [rotate_cons_succ, rotate_zero]⟩ /-- The unique empty cycle. -/ def nil : cycle α := ([] : list α) @[simp] lemma coe_nil : ↑([] : list α) = @nil α := rfl @[simp] lemma coe_eq_nil (l : list α) : (l : cycle α) = nil ↔ l = [] := coe_eq_coe.trans is_rotated_nil_iff /-- For consistency with `list.has_emptyc`. -/ instance : has_emptyc (cycle α) := ⟨nil⟩ @[simp] lemma empty_eq : ∅ = @nil α := rfl instance : inhabited (cycle α) := ⟨nil⟩ /-- An induction principle for `cycle`. Use as `induction s using cycle.induction_on`. -/ @[elab_as_eliminator] lemma induction_on {C : cycle α → Prop} (s : cycle α) (H0 : C nil) (HI : ∀ a (l : list α), C ↑l → C ↑(a :: l)) : C s := quotient.induction_on' s $ λ l, by { apply list.rec_on l; simp, assumption' } /-- For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/ def mem (a : α) (s : cycle α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ e, propext $ e.mem_iff) instance : has_mem α (cycle α) := ⟨mem⟩ @[simp] lemma mem_coe_iff {a : α} {l : list α} : a ∈ (l : cycle α) ↔ a ∈ l := iff.rfl @[simp] lemma not_mem_nil : ∀ a, a ∉ @nil α := not_mem_nil instance [decidable_eq α] : decidable_eq (cycle α) := λ s₁ s₂, quotient.rec_on_subsingleton₂' s₁ s₂ (λ l₁ l₂, decidable_of_iff' _ quotient.eq') instance [decidable_eq α] (x : α) (s : cycle α) : decidable (x ∈ s) := quotient.rec_on_subsingleton' s (λ l, list.decidable_mem x l) /-- Reverse a `s : cycle α` by reversing the underlying `list`. -/ def reverse (s : cycle α) : cycle α := quot.map reverse (λ l₁ l₂, is_rotated.reverse) s @[simp] lemma reverse_coe (l : list α) : (l : cycle α).reverse = l.reverse := rfl @[simp] lemma mem_reverse_iff {a : α} {s : cycle α} : a ∈ s.reverse ↔ a ∈ s := quot.induction_on s (λ _, mem_reverse) @[simp] lemma reverse_reverse (s : cycle α) : s.reverse.reverse = s := quot.induction_on s (λ _, by simp) @[simp] lemma reverse_nil : nil.reverse = @nil α := rfl /-- The length of the `s : cycle α`, which is the number of elements, counting duplicates. -/ def length (s : cycle α) : ℕ := quot.lift_on s length (λ l₁ l₂ e, e.perm.length_eq) @[simp] lemma length_coe (l : list α) : length (l : cycle α) = l.length := rfl @[simp] lemma length_nil : length (@nil α) = 0 := rfl @[simp] lemma length_reverse (s : cycle α) : s.reverse.length = s.length := quot.induction_on s length_reverse /-- A `s : cycle α` that is at most one element. -/ def subsingleton (s : cycle α) : Prop := s.length ≤ 1 lemma subsingleton_nil : subsingleton (@nil α) := zero_le_one lemma length_subsingleton_iff {s : cycle α} : subsingleton s ↔ length s ≤ 1 := iff.rfl @[simp] lemma subsingleton_reverse_iff {s : cycle α} : s.reverse.subsingleton ↔ s.subsingleton := by simp [length_subsingleton_iff] lemma subsingleton.congr {s : cycle α} (h : subsingleton s) : ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y := begin induction s using quot.induction_on with l, simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, nat.lt_add_one_iff, length_eq_zero, length_eq_one, nat.not_lt_zero, false_or] at h, rcases h with rfl|⟨z, rfl⟩; simp end /-- A `s : cycle α` that is made up of at least two unique elements. -/ def nontrivial (s : cycle α) : Prop := ∃ (x y : α) (h : x ≠ y), x ∈ s ∧ y ∈ s @[simp] lemma nontrivial_coe_nodup_iff {l : list α} (hl : l.nodup) : nontrivial (l : cycle α) ↔ 2 ≤ l.length := begin rw nontrivial, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simp }, { simp }, { simp only [mem_cons_iff, exists_prop, mem_coe_iff, list.length, ne.def, nat.succ_le_succ_iff, zero_le, iff_true], refine ⟨hd, hd', _, by simp⟩, simp only [not_or_distrib, mem_cons_iff, nodup_cons] at hl, exact hl.left.left } end @[simp] lemma nontrivial_reverse_iff {s : cycle α} : s.reverse.nontrivial ↔ s.nontrivial := by simp [nontrivial] lemma length_nontrivial {s : cycle α} (h : nontrivial s) : 2 ≤ length s := begin obtain ⟨x, y, hxy, hx, hy⟩ := h, induction s using quot.induction_on with l, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simpa using hx }, { simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy, simpa [hx, hy] using hxy }, { simp [bit0] } end /-- The `s : cycle α` contains no duplicates. -/ def nodup (s : cycle α) : Prop := quot.lift_on s nodup (λ l₁ l₂ e, propext $ e.nodup_iff) @[simp] lemma nodup_nil : nodup (@nil α) := nodup_nil @[simp] lemma nodup_coe_iff {l : list α} : nodup (l : cycle α) ↔ l.nodup := iff.rfl @[simp] lemma nodup_reverse_iff {s : cycle α} : s.reverse.nodup ↔ s.nodup := quot.induction_on s (λ _, nodup_reverse) lemma subsingleton.nodup {s : cycle α} (h : subsingleton s) : nodup s := begin induction s using quot.induction_on with l, cases l with hd tl, { simp }, { have : tl = [] := by simpa [subsingleton, length_eq_zero] using h, simp [this] } end lemma nodup.nontrivial_iff {s : cycle α} (h : nodup s) : nontrivial s ↔ ¬ subsingleton s := begin rw length_subsingleton_iff, induction s using quotient.induction_on', simp only [mk'_eq_coe, nodup_coe_iff] at h, simp [h, nat.succ_le_iff] end /-- The `s : cycle α` as a `multiset α`. -/ def to_multiset (s : cycle α) : multiset α := quotient.lift_on' s coe (λ l₁ l₂ h, multiset.coe_eq_coe.mpr h.perm) @[simp] lemma coe_to_multiset (l : list α) : (l : cycle α).to_multiset = l := rfl @[simp] lemma nil_to_multiset : nil.to_multiset = (0 : multiset α) := rfl @[simp] lemma card_to_multiset (s : cycle α) : s.to_multiset.card = s.length := quotient.induction_on' s (by simp) @[simp] lemma to_multiset_eq_nil {s : cycle α} : s.to_multiset = 0 ↔ s = cycle.nil := quotient.induction_on' s (by simp) /-- The lift of `list.map`. -/ def map {β : Type*} (f : α → β) : cycle α → cycle β := quotient.map' (list.map f) $ λ l₁ l₂ h, h.map _ @[simp] lemma map_nil {β : Type*} (f : α → β) : map f nil = nil := rfl @[simp] lemma map_coe {β : Type*} (f : α → β) (l : list α) : map f ↑l = list.map f l := rfl @[simp] lemma map_eq_nil {β : Type*} (f : α → β) (s : cycle α) : map f s = nil ↔ s = nil := quotient.induction_on' s (by simp) /-- The `multiset` of lists that can make the cycle. -/ def lists (s : cycle α) : multiset (list α) := quotient.lift_on' s (λ l, (l.cyclic_permutations : multiset (list α))) $ λ l₁ l₂ h, by simpa using h.cyclic_permutations.perm @[simp] lemma lists_coe (l : list α) : lists (l : cycle α) = ↑l.cyclic_permutations := rfl @[simp] lemma mem_lists_iff_coe_eq {s : cycle α} {l : list α} : l ∈ s.lists ↔ (l : cycle α) = s := quotient.induction_on' s $ λ l, by { rw [lists, quotient.lift_on'_mk'], simp } @[simp] lemma lists_nil : lists (@nil α) = [([] : list α)] := by rw [nil, lists_coe, cyclic_permutations_nil] section decidable variable [decidable_eq α] /-- Auxiliary decidability algorithm for lists that contain at least two unique elements. -/ def decidable_nontrivial_coe : Π (l : list α), decidable (nontrivial (l : cycle α)) | [] := is_false (by simp [nontrivial]) | [x] := is_false (by simp [nontrivial]) | (x :: y :: l) := if h : x = y then @decidable_of_iff' _ (nontrivial ((x :: l) : cycle α)) (by simp [h, nontrivial]) (decidable_nontrivial_coe (x :: l)) else is_true ⟨x, y, h, by simp, by simp⟩ instance {s : cycle α} : decidable (nontrivial s) := quot.rec_on_subsingleton s decidable_nontrivial_coe instance {s : cycle α} : decidable (nodup s) := quot.rec_on_subsingleton s list.nodup_decidable instance fintype_nodup_cycle [fintype α] : fintype {s : cycle α // s.nodup} := fintype.of_surjective (λ (l : {l : list α // l.nodup}), ⟨l.val, by simpa using l.prop⟩) (λ ⟨s, hs⟩, by { induction s using quotient.induction_on', exact ⟨⟨s, hs⟩, by simp⟩ }) instance fintype_nodup_nontrivial_cycle [fintype α] : fintype {s : cycle α // s.nodup ∧ s.nontrivial} := fintype.subtype (((finset.univ : finset {s : cycle α // s.nodup}).map (function.embedding.subtype _)).filter cycle.nontrivial) (by simp) /-- The `s : cycle α` as a `finset α`. -/ def to_finset (s : cycle α) : finset α := s.to_multiset.to_finset @[simp] theorem to_finset_to_multiset (s : cycle α) : s.to_multiset.to_finset = s.to_finset := rfl @[simp] lemma coe_to_finset (l : list α) : (l : cycle α).to_finset = l.to_finset := rfl @[simp] lemma nil_to_finset : (@nil α).to_finset = ∅ := rfl @[simp] lemma to_finset_eq_nil {s : cycle α} : s.to_finset = ∅ ↔ s = cycle.nil := quotient.induction_on' s (by simp) /-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/ def next : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, next l x hx) (λ l₁ l₂ h, function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_next_eq h h₁ _))))) /-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/ def prev : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, prev l x hx) (λ l₁ l₂ h, function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_prev_eq h h₁ _))))) @[simp] lemma prev_reverse_eq_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx := (quotient.induction_on' s prev_reverse_eq_next) hs x hx @[simp] lemma next_reverse_eq_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by simp [←prev_reverse_eq_next] @[simp] lemma next_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs x hx ∈ s := by { induction s using quot.induction_on, apply next_mem } lemma prev_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs x hx ∈ s := by { rw [←next_reverse_eq_prev, ←mem_reverse_iff], apply next_mem } @[simp] lemma prev_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x := (quotient.induction_on' s prev_next) hs x hx @[simp] lemma next_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x := (quotient.induction_on' s next_prev) hs x hx end decidable /-- We define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ instance [has_repr α] : has_repr (cycle α) := ⟨λ s, "c[" ++ string.intercalate ", " ((s.map repr).lists.sort (≤)).head ++ "]"⟩ /-- `chain R s` means that `R` holds between adjacent elements of `s`. `chain R ([a, b, c] : cycle α) ↔ R a b ∧ R b c ∧ R c a` -/ def chain (r : α → α → Prop) (c : cycle α) : Prop := quotient.lift_on' c (λ l, match l with | [] := true | (a :: m) := chain r a (m ++ [a]) end) $ λ a b hab, propext $ begin cases a with a l; cases b with b m, { refl }, { have := is_rotated_nil_iff'.1 hab, contradiction }, { have := is_rotated_nil_iff.1 hab, contradiction }, { unfold chain._match_1, cases hab with n hn, induction n with d hd generalizing a b l m, { simp only [rotate_zero] at hn, rw [hn.1, hn.2] }, { cases l with c s, { simp only [rotate_singleton] at hn, rw [hn.1, hn.2] }, { rw [nat.succ_eq_one_add, ←rotate_rotate, rotate_cons_succ, rotate_zero, cons_append] at hn, rw [←hd c _ _ _ hn], simp [and.comm] } } } end @[simp] lemma chain.nil (r : α → α → Prop) : cycle.chain r (@nil α) := by trivial @[simp] lemma chain_coe_cons (r : α → α → Prop) (a : α) (l : list α) : chain r (a :: l) ↔ list.chain r a (l ++ [a]) := iff.rfl @[simp] lemma chain_singleton (r : α → α → Prop) (a : α) : chain r [a] ↔ r a a := by rw [chain_coe_cons, nil_append, chain_singleton] lemma chain_ne_nil (r : α → α → Prop) {l : list α} : Π hl : l ≠ [], chain r l ↔ list.chain r (last l hl) l := begin apply l.reverse_rec_on, exact λ hm, hm.irrefl.elim, intros m a H _, rw [←coe_cons_eq_coe_append, chain_coe_cons, last_append_singleton] end lemma chain_map {β : Type*} {r : α → α → Prop} (f : β → α) {s : cycle β} : chain r (s.map f) ↔ chain (λ a b, r (f a) (f b)) s := quotient.induction_on' s $ λ l, begin cases l with a l, refl, convert list.chain_map f, rw map_append f l [a], refl end theorem chain_range_succ (r : ℕ → ℕ → Prop) (n : ℕ) : chain r (list.range n.succ) ↔ r n 0 ∧ ∀ m < n, r m m.succ := by rw [range_succ, ←coe_cons_eq_coe_append, chain_coe_cons, ←range_succ, chain_range_succ] variables {r : α → α → Prop} {s : cycle α} theorem chain_of_pairwise : (∀ (a ∈ s) (b ∈ s), r a b) → chain r s := begin induction s using cycle.induction_on with a l _, exact λ _, cycle.chain.nil r, intro hs, have Ha : a ∈ ((a :: l) : cycle α) := by simp, have Hl : ∀ {b} (hb : b ∈ l), b ∈ ((a :: l) : cycle α) := λ b hb, by simp [hb], rw cycle.chain_coe_cons, apply pairwise.chain, rw pairwise_cons, refine ⟨λ b hb, _, pairwise_append.2 ⟨pairwise_of_forall_mem_list (λ b hb c hc, hs b (Hl hb) c (Hl hc)), pairwise_singleton r a, λ b hb c hc, _⟩⟩, { rw mem_append at hb, cases hb, { exact hs a Ha b (Hl hb) }, { rw mem_singleton at hb, rw hb, exact hs a Ha a Ha } }, { rw mem_singleton at hc, rw hc, exact hs b (Hl hb) a Ha } end theorem chain_iff_pairwise (hr : transitive r) : chain r s ↔ ∀ (a ∈ s) (b ∈ s), r a b := ⟨begin induction s using cycle.induction_on with a l _, exact λ _ b hb, hb.elim, intros hs b hb c hc, rw [cycle.chain_coe_cons, chain_iff_pairwise hr] at hs, simp only [pairwise_append, pairwise_cons, mem_append, mem_singleton, list.not_mem_nil, is_empty.forall_iff, implies_true_iff, pairwise.nil, forall_eq, true_and] at hs, simp only [mem_coe_iff, mem_cons_iff] at hb hc, rcases hb with rfl | hb; rcases hc with rfl | hc, { exact hs.1 c (or.inr rfl) }, { exact hs.1 c (or.inl hc) }, { exact hs.2.2 b hb }, { exact hr (hs.2.2 b hb) (hs.1 c (or.inl hc)) } end, cycle.chain_of_pairwise⟩ theorem forall_eq_of_chain (hr : transitive r) (hr' : anti_symmetric r) (hs : chain r s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : a = b := by { rw chain_iff_pairwise hr at hs, exact hr' (hs a ha b hb) (hs b hb a ha) } end cycle
1e148180db473eb2cec585b35d0ad01694852860
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/nat/lattice.lean
c21fe473aff373e5c2440bb88f91b3d91e8517b2
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
6,900
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Floris van Doorn, Gabriel Ebner, Yury Kudryashov -/ import order.conditionally_complete_lattice /-! # Conditionally complete linear order structure on `ℕ` In this file we * define a `conditionally_complete_linear_order_bot` structure on `ℕ`; * define a `complete_linear_order` structure on `part_enat`; * prove a few lemmas about `supr`/`infi`/`set.Union`/`set.Inter` and natural numbers. -/ open set namespace nat open_locale classical noncomputable instance : has_Inf ℕ := ⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup ℕ := ⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩ lemma Inf_def {s : set ℕ} (h : s.nonempty) : Inf s = @nat.find (λn, n ∈ s) _ h := dif_pos _ lemma Sup_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) : Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h := dif_pos _ lemma _root_.set.infinite.nat.Sup_eq_zero {s : set ℕ} (h : s.infinite) : Sup s = 0 := dif_neg $ λ ⟨n, hn⟩, let ⟨k, hks, hk⟩ := h.exists_nat_lt n in (hn k hks).not_lt hk @[simp] lemma Inf_eq_zero {s : set ℕ} : Inf s = 0 ↔ 0 ∈ s ∨ s = ∅ := begin cases eq_empty_or_nonempty s, { subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf, mem_empty_eq, exists_false, dif_neg, not_false_iff] }, { have := ne_empty_iff_nonempty.mpr h, simp only [this, or_false, nat.Inf_def, h, nat.find_eq_zero] } end @[simp] lemma Inf_empty : Inf ∅ = 0 := by { rw Inf_eq_zero, right, refl } @[simp] lemma infi_of_empty {ι : Sort*} [is_empty ι] (f : ι → ℕ) : infi f = 0 := by rw [infi_of_empty', Inf_empty] lemma Inf_mem {s : set ℕ} (h : s.nonempty) : Inf s ∈ s := by { rw [nat.Inf_def h], exact nat.find_spec h } lemma not_mem_of_lt_Inf {s : set ℕ} {m : ℕ} (hm : m < Inf s) : m ∉ s := begin cases eq_empty_or_nonempty s, { subst h, apply not_mem_empty }, { rw [nat.Inf_def h] at hm, exact nat.find_min h hm } end protected lemma Inf_le {s : set ℕ} {m : ℕ} (hm : m ∈ s) : Inf s ≤ m := by { rw [nat.Inf_def ⟨m, hm⟩], exact nat.find_min' ⟨m, hm⟩ hm } lemma nonempty_of_pos_Inf {s : set ℕ} (h : 0 < Inf s) : s.nonempty := begin by_contradiction contra, rw set.not_nonempty_iff_eq_empty at contra, have h' : Inf s ≠ 0, { exact ne_of_gt h, }, apply h', rw nat.Inf_eq_zero, right, assumption, end lemma nonempty_of_Inf_eq_succ {s : set ℕ} {k : ℕ} (h : Inf s = k + 1) : s.nonempty := nonempty_of_pos_Inf (h.symm ▸ (succ_pos k) : Inf s > 0) lemma eq_Ici_of_nonempty_of_upward_closed {s : set ℕ} (hs : s.nonempty) (hs' : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s) : s = Ici (Inf s) := ext (λ n, ⟨λ H, nat.Inf_le H, λ H, hs' (Inf s) n H (Inf_mem hs)⟩) lemma Inf_upward_closed_eq_succ_iff {s : set ℕ} (hs : ∀ (k₁ k₂ : ℕ), k₁ ≤ k₂ → k₁ ∈ s → k₂ ∈ s) (k : ℕ) : Inf s = k + 1 ↔ k + 1 ∈ s ∧ k ∉ s := begin split, { intro H, rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_Inf_eq_succ H) hs, H, mem_Ici, mem_Ici], exact ⟨le_rfl, k.not_succ_le_self⟩, }, { rintro ⟨H, H'⟩, rw [Inf_def (⟨_, H⟩ : s.nonempty), find_eq_iff], exact ⟨H, λ n hnk hns, H' $ hs n k (lt_succ_iff.mp hnk) hns⟩, }, end /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice ℕ := linear_order.to_lattice noncomputable instance : conditionally_complete_linear_order_bot ℕ := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_def hs]; exact hb (@nat.find_spec (λn, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot ℕ), .. (linear_order.to_lattice : lattice ℕ), .. (infer_instance : linear_order ℕ) } lemma Sup_mem {s : set ℕ} (h₁ : s.nonempty) (h₂ : bdd_above s) : Sup s ∈ s := let ⟨k, hk⟩ := h₂ in h₁.cSup_mem ((finite_le_nat k).subset hk) lemma Inf_add {n : ℕ} {p : ℕ → Prop} (hn : n ≤ Inf {m | p m}) : Inf {m | p (m + n)} + n = Inf {m | p m} := begin obtain h | ⟨m, hm⟩ := {m | p (m + n)}.eq_empty_or_nonempty, { rw [h, nat.Inf_empty, zero_add], obtain hnp | hnp := hn.eq_or_lt, { exact hnp }, suffices hp : p (Inf {m | p m} - n + n), { exact (h.subset hp).elim }, rw tsub_add_cancel_of_le hn, exact Inf_mem (nonempty_of_pos_Inf $ n.zero_le.trans_lt hnp) }, { have hp : ∃ n, n ∈ {m | p m} := ⟨_, hm⟩, rw [nat.Inf_def ⟨m, hm⟩, nat.Inf_def hp], rw [nat.Inf_def hp] at hn, exact find_add hn } end lemma Inf_add' {n : ℕ} {p : ℕ → Prop} (h : 0 < Inf {m | p m}) : Inf {m | p m} + n = Inf {m | p (m - n)} := begin convert Inf_add _, { simp_rw add_tsub_cancel_right }, obtain ⟨m, hm⟩ := nonempty_of_pos_Inf h, refine le_cInf ⟨m + n, _⟩ (λ b hb, le_of_not_lt $ λ hbn, ne_of_mem_of_not_mem _ (not_mem_of_lt_Inf h) (tsub_eq_zero_of_le hbn.le)), { dsimp, rwa add_tsub_cancel_right }, { exact hb } end section variables {α : Type*} [complete_lattice α] lemma supr_lt_succ (u : ℕ → α) (n : ℕ) : (⨆ k < n + 1, u k) = (⨆ k < n, u k) ⊔ u n := by simp [nat.lt_succ_iff_lt_or_eq, supr_or, supr_sup_eq] lemma supr_lt_succ' (u : ℕ → α) (n : ℕ) : (⨆ k < n + 1, u k) = u 0 ⊔ (⨆ k < n, u (k + 1)) := by { rw ← sup_supr_nat_succ, simp } lemma infi_lt_succ (u : ℕ → α) (n : ℕ) : (⨅ k < n + 1, u k) = (⨅ k < n, u k) ⊓ u n := @supr_lt_succ αᵒᵈ _ _ _ lemma infi_lt_succ' (u : ℕ → α) (n : ℕ) : (⨅ k < n + 1, u k) = u 0 ⊓ (⨅ k < n, u (k + 1)) := @supr_lt_succ' αᵒᵈ _ _ _ end end nat namespace set variable {α : Type*} lemma bUnion_lt_succ (u : ℕ → set α) (n : ℕ) : (⋃ k < n + 1, u k) = (⋃ k < n, u k) ∪ u n := nat.supr_lt_succ u n lemma bUnion_lt_succ' (u : ℕ → set α) (n : ℕ) : (⋃ k < n + 1, u k) = u 0 ∪ (⋃ k < n, u (k + 1)) := nat.supr_lt_succ' u n lemma bInter_lt_succ (u : ℕ → set α) (n : ℕ) : (⋂ k < n + 1, u k) = (⋂ k < n, u k) ∩ u n := nat.infi_lt_succ u n lemma bInter_lt_succ' (u : ℕ → set α) (n : ℕ) : (⋂ k < n + 1, u k) = u 0 ∩ (⋂ k < n, u (k + 1)) := nat.infi_lt_succ' u n end set
697f292f2e719771de262908f8d36afe02768b20
7a0854479980a89e813e3c93d127f09a8e2c3a7e
/src/hom/theorems.lean
1d0a93fb6876ca28058b69aaa19877f303415468
[]
no_license
cfbolz/group-theory-game
020e382df58bf9a510dce38304f27400e4ef0b80
b5282ce72a2a22e9ba1b48cee432ff3d77496040
refs/heads/master
1,668,643,052,237
1,594,820,769,000
1,594,820,769,000
279,899,736
0
0
null
1,594,825,474,000
1,594,825,473,000
null
UTF-8
Lean
false
false
2,274
lean
import hom.definitions /- The type of group homs G → H is denoted f : G →* H and the underlying function of types is ⇑f : G → H TODO: can we switch those arrows off? The axiom: if `f : G →* H` then `f.map_mul` is the assertion that for all a, b ∈ G we have f(a) = f(b). Our first job is to prove `f.map_one` and `f.map_inv`. `f.map_one : f 1 = 1` `f.map_inv {x : G} : f (x⁻¹) = f(x)⁻¹` -/ -- the entire project takes place in the mygroup namespace namespace mygroup -- We're proving things about group homs so this all goes in the `group_hom` -- namespace open set namespace group_hom variables {G H K : Type} [group G] [group H] [group K] /-- If f is a group homomorphism then f 1 = 1. -/ @[simp] -- it's a good simp lemma lemma map_one (f : G →* H) : f 1 = 1 := begin have h : f 1 * f 1 = f 1, rw ←f.map_mul, rw group.one_mul, -- annoying but stops cheating -- TODO: can I kill one_mul somehow? I asked on Zulip rw group.mul_left_eq_self at h, -- annoying assumption end /-- If f is a group homomorphism then f(x⁻¹) = f(x)⁻¹ -/ @[simp] -- it's also a good simp lemma lemma map_inv (f : G →* H) {x : G} : f (x⁻¹) = (f x)⁻¹ := begin apply group.eq_inv_of_mul_eq_one, rw ←f.map_mul, rw group.mul_left_inv, rw f.map_one, -- refl end -- TODO: map and comap, kernel and image -- We prove the theorems here (only); -- definitions need to go elsewhere -- Rather than defining the kernel as the preimage of {1}, I think defining it -- as a subgroup of the domain is better -- We uses this and it should be moved to group @[simp] lemma one_inv : (1 : G)⁻¹ = 1 := by conv_rhs { rw [←(group.mul_left_inv (1 : G)), group.mul_one] } /-- The kernel of a homomorphism `f : G →* H` is the subgroup of `G` whos carrier is the preimage of `{1}`, i.e. `f ⁻¹' {1}` -/ def kernel (f : G →* H) : subgroup G := { carrier := f ⁻¹' {1}, one_mem' := map_one _, mul_mem' := begin intros _ _ hx hy, rw [mem_preimage, mem_singleton_iff] at *, rw [map_mul f, hx, hy, group.mul_one] end, inv_mem' := begin intros _ hx, rw [mem_preimage, mem_singleton_iff] at *, rw [map_inv f, hx, one_inv] end } end group_hom end mygroup
a79a079c14cde8bc4151c64fd51864bd99c6e6ac
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/tests/lean/server/diags.lean
c8cd3c2a136d20d7342635f12111da9c9a481f42
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
1,172
lean
import Lean.Data.Lsp open IO Lean Lsp #eval (do Ipc.runWith (←IO.appPath) #["--server"] do let hIn ← Ipc.stdin hIn.write (←FS.readBinFile "init_vscode_1_47_2.log") hIn.flush discard $ Ipc.readResponseAs 0 InitializeResult Ipc.writeNotification ⟨"initialized", InitializedParams.mk⟩ hIn.write (←FS.readBinFile "open_content.log") hIn.flush let diags ← Ipc.collectDiagnostics 1 "file:///test.lean" 1 if diags.isEmpty then throw $ userError "Test failed, no diagnostics received." else let diag := diags.getLast! FS.writeFile "content_diag.json.produced" (toString <| toJson (diag : JsonRpc.Message)) if let some (refDiag : JsonRpc.Notification PublishDiagnosticsParams) := (Json.parse $ ←FS.readFile "content_diag.json") >>= fromJson? then assert! (diag == refDiag) else throw $ userError "Failed parsing test file." Ipc.writeRequest ⟨2, "shutdown", Json.null⟩ let shutResp ← Ipc.readResponseAs 2 Json assert! shutResp.result.isNull Ipc.writeNotification ⟨"exit", Json.null⟩ discard $ Ipc.waitForExit : IO Unit)
899dee8c351949f5d8b2ad6f9e3ff0c459472533
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/data/seq/seq.lean
b248b2084b04ef6be95471d7e241240e05b2a957
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
28,415
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import tactic.basic import data.list.basic data.stream data.lazy_list data.seq.computation logic.basic universes u v w /- coinductive seq (α : Type u) : Type u | nil : seq α | cons : α → seq α → seq α -/ /-- A stream `s : option α` is a sequence if `s.nth n = none` implies `s.nth (n + 1) = none`. -/ def stream.is_seq {α : Type u} (s : stream (option α)) : Prop := ∀ {n : ℕ}, s n = none → s (n + 1) = none /-- `seq α` is the type of possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m ≥ n`. -/ def seq (α : Type u) : Type u := { f : stream (option α) // f.is_seq } /-- `seq1 α` is the type of nonempty sequences. -/ def seq1 (α) := α × seq α namespace seq variables {α : Type u} {β : Type v} {γ : Type w} /-- The empty sequence -/ def nil : seq α := ⟨stream.const none, λn h, rfl⟩ /-- Prepend an element to a sequence -/ def cons (a : α) : seq α → seq α | ⟨f, al⟩ := ⟨some a :: f, λn h, by {cases n with n, contradiction, exact al h}⟩ /-- Get the nth element of a sequence (if it exists) -/ def nth : seq α → ℕ → option α := subtype.val /-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/ def terminated_at (s : seq α) (n : ℕ) : Prop := s.nth n = none /-- It is decidable whether a sequence terminates at a given position. -/ instance terminated_at_decidable (s : seq α) (n : ℕ) : decidable (s.terminated_at n) := if p : s.nth n = none then is_true p else is_false (assume h, by contradiction) /-- A sequence terminates if there is some position `n` at which it has terminated. -/ def terminates (s : seq α) : Prop := ∃ (n : ℕ), s.terminated_at n /-- Functorial action of the functor `option (α × _)` -/ @[simp] def omap (f : β → γ) : option (α × β) → option (α × γ) | none := none | (some (a, b)) := some (a, f b) /-- Get the first element of a sequence -/ def head (s : seq α) : option α := nth s 0 /-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/ def tail : seq α → seq α | ⟨f, al⟩ := ⟨f.tail, λ n, al⟩ protected def mem (a : α) (s : seq α) := some a ∈ s.1 instance : has_mem α (seq α) := ⟨seq.mem⟩ theorem le_stable (s : seq α) {m n} (h : m ≤ n) : s.1 m = none → s.1 n = none := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} /-- If a sequence terminated at position `n`, it also terminated at `m ≥ n `. -/ lemma terminated_stable {s : seq α} {m n : ℕ} (m_le_n : m ≤ n) (terminated_at_m : s.terminated_at m) : s.terminated_at n := le_stable s m_le_n terminated_at_m /-- If `s.nth n = some aₙ` for some value `aₙ`, then there is also some value `aₘ` such that `s.nth = some aₘ` for `m ≤ n`. -/ lemma ge_stable (s : seq α) {aₙ : α} {n m : ℕ} (m_le_n : m ≤ n) (s_nth_eq_some : s.nth n = some aₙ) : ∃ (aₘ : α), s.nth m = some aₘ := have s.nth n ≠ none, by simp [s_nth_eq_some], have s.nth m ≠ none, from mt (s.le_stable m_le_n) this, with_one.ne_one_iff_exists.elim_left this theorem not_mem_nil (a : α) : a ∉ @nil α := λ ⟨n, (h : some a = none)⟩, by injection h theorem mem_cons (a : α) : ∀ (s : seq α), a ∈ cons a s | ⟨f, al⟩ := stream.mem_cons (some a) _ theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : seq α}, a ∈ s → a ∈ cons y s | ⟨f, al⟩ := stream.mem_cons_of_mem (some y) theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : seq α}, a ∈ cons b s → a = b ∨ a ∈ s | ⟨f, al⟩ h := (stream.eq_or_mem_of_mem_cons h).imp_left (λh, by injection h) @[simp] theorem mem_cons_iff {a b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s := ⟨eq_or_mem_of_mem_cons, λo, by cases o with e m; [{rw e, apply mem_cons}, exact mem_cons_of_mem _ m]⟩ /-- Destructor for a sequence, resulting in either `none` (for `nil`) or `some (a, s)` (for `cons a s`). -/ def destruct (s : seq α) : option (seq1 α) := (λa', (a', s.tail)) <$> nth s 0 theorem destruct_eq_nil {s : seq α} : destruct s = none → s = nil := begin dsimp [destruct], induction f0 : nth s 0; intro h, { apply subtype.eq, funext n, induction n with n IH, exacts [f0, s.2 IH] }, { contradiction } end theorem destruct_eq_cons {s : seq α} {a s'} : destruct s = some (a, s') → s = cons a s' := begin dsimp [destruct], induction f0 : nth s 0 with a'; intro h, { contradiction }, { unfold functor.map at h, cases s with f al, injections with _ h1 h2, rw ←h2, apply subtype.eq, dsimp [tail, cons], rw h1 at f0, rw ←f0, exact (stream.eta f).symm } end @[simp] theorem destruct_nil : destruct (nil : seq α) = none := rfl @[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s) | ⟨f, al⟩ := begin unfold cons destruct functor.map, apply congr_arg (λ s, some (a, s)), apply subtype.eq, dsimp [tail], rw [stream.tail_cons] end theorem head_eq_destruct (s : seq α) : head s = prod.fst <$> destruct s := by unfold destruct head; cases nth s 0; refl @[simp] theorem head_nil : head (nil : seq α) = none := rfl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a := by rw [head_eq_destruct, destruct_cons]; refl @[simp] theorem tail_nil : tail (nil : seq α) = nil := rfl @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, cons]; rw [stream.tail_cons] def cases_on {C : seq α → Sort v} (s : seq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_nil H, apply h1 }, { cases v with a s', rw destruct_eq_cons H, apply h2 } end theorem mem_rec_on {C : seq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) : C s := begin cases M with k e, unfold stream.nth at e, induction k with k IH generalizing s, { have TH : s = cons a (tail s), { apply destruct_eq_cons, unfold destruct nth functor.map, rw ←e, refl }, rw TH, apply h1 _ _ (or.inl rfl) }, revert e, apply s.cases_on _ (λ b s', _); intro e, { injection e }, { have h_eq : (cons b s').val (nat.succ k) = s'.val k, { cases s'; refl }, rw [h_eq] at e, apply h1 _ _ (or.inr (IH e)) } end def corec.F (f : β → option (α × β)) : option β → option α × option β | none := (none, none) | (some b) := match f b with none := (none, none) | some (a, b') := (some a, some b') end /-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements of the sequence until `none` is obtained. -/ def corec (f : β → option (α × β)) (b : β) : seq α := begin refine ⟨stream.corec' (corec.F f) (some b), λn h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (some b)).2 n = none, revert h, generalize : some b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = none → (corec.F f (corec.F f o).2).1 = none, cases o with b; intro h, { refl }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with s, { refl }, { cases s with a b', contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end @[simp] theorem corec_eq (f : β → option (α × β)) (b : β) : destruct (corec f b) = omap (corec f) (f b) := begin dsimp [corec, destruct, nth], change stream.corec' (corec.F f) (some b) 0 with (corec.F f (some b)).1, unfold functor.map, dsimp [corec.F], induction h : f b with s, { refl }, cases s with a b', dsimp [corec.F], apply congr_arg (λ b', some (a, b')), apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h, refl end /-- Embed a list as a sequence -/ def of_list (l : list α) : seq α := ⟨list.nth l, λn h, begin induction l with a l IH generalizing n, refl, dsimp [list.nth], cases n with n; dsimp [list.nth] at h, { contradiction }, { apply IH _ h } end⟩ instance coe_list : has_coe (list α) (seq α) := ⟨of_list⟩ section bisim variable (R : seq α → seq α → Prop) local infix ~ := R def bisim_o : option (seq1 α) → option (seq1 α) → Prop | none none := true | (some (a, s)) (some (a', s')) := a = a' ∧ R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : seq α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, refl, assumption }, { rw [destruct_nil, destruct_cons] at this, exact false.elim this }, { rw [destruct_nil, destruct_cons] at this, exact false.elim this }, { rw [destruct_cons, destruct_cons] at this, rw [head_cons, head_cons, tail_cons, tail_cons], cases this with h1 h2, constructor, rw h1, exact h2 } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim theorem coinduction : ∀ {s₁ s₂ : seq α}, head s₁ = head s₂ → (∀ (β : Type u) (fr : seq α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ | ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ hh ht := subtype.eq (stream.coinduction hh (λ β fr, ht β (λs, fr s.1))) theorem coinduction2 (s) (f g : seq α → seq β) (H : ∀ s, bisim_o (λ (s1 s2 : seq β), ∃ (s : seq α), s1 = f s ∧ s2 = g s) (destruct (f s)) (destruct (g s))) : f s = g s := begin refine eq_of_bisim (λ s1 s2, ∃ s, s1 = f s ∧ s2 = g s) _ ⟨s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨s, h1, h2⟩, rw [h1, h2], apply H end /-- Embed an infinite stream as a sequence -/ def of_stream (s : stream α) : seq α := ⟨s.map some, λn h, by contradiction⟩ instance coe_stream : has_coe (stream α) (seq α) := ⟨of_stream⟩ /-- Embed a `lazy_list α` as a sequence. Note that even though this is non-meta, it will produce infinite sequences if used with cyclic `lazy_list`s created by meta constructions. -/ def of_lazy_list : lazy_list α → seq α := corec (λl, match l with | lazy_list.nil := none | lazy_list.cons a l' := some (a, l' ()) end) instance coe_lazy_list : has_coe (lazy_list α) (seq α) := ⟨of_lazy_list⟩ /-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list` are isomorphic as non-meta types, this function is necessarily meta. -/ meta def to_lazy_list : seq α → lazy_list α | s := match destruct s with | none := lazy_list.nil | some (a, s') := lazy_list.cons a (to_lazy_list s') end /-- Translate a sequence to a list. This function will run forever if run on an infinite sequence. -/ meta def force_to_list (s : seq α) : list α := (to_lazy_list s).to_list /-- The sequence of natural numbers some 0, some 1, ... -/ def nats : seq ℕ := stream.nats @[simp] lemma nats_nth (n : ℕ) : nats.nth n = some n := rfl /-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`, otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/ def append (s₁ s₂ : seq α) : seq α := @corec α (seq α × seq α) (λ⟨s₁, s₂⟩, match destruct s₁ with | none := omap (λs₂, (nil, s₂)) (destruct s₂) | some (a, s₁') := some (a, s₁', s₂) end) (s₁, s₂) /-- Map a function over a sequence. -/ def map (f : α → β) : seq α → seq β | ⟨s, al⟩ := ⟨s.map (option.map f), λn, begin dsimp [stream.map, stream.nth], induction e : s n; intro, { rw al e, assumption }, { contradiction } end⟩ /-- Flatten a sequence of sequences. (It is required that the sequences be nonempty to ensure productivity; in the case of an infinite sequence of `nil`, the first element is never generated.) -/ def join : seq (seq1 α) → seq α := corec (λS, match destruct S with | none := none | some ((a, s), S') := some (a, match destruct s with | none := S' | some s' := cons s' S' end) end) /-- Remove the first `n` elements from the sequence. -/ def drop (s : seq α) : ℕ → seq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Take the first `n` elements of the sequence (producing a list) -/ def take : ℕ → seq α → list α | 0 s := [] | (n+1) s := match destruct s with | none := [] | some (x, r) := list.cons x (take n r) end /-- Split a sequence at `n`, producing a finite initial segment and an infinite tail. -/ def split_at : ℕ → seq α → list α × seq α | 0 s := ([], s) | (n+1) s := match destruct s with | none := ([], nil) | some (x, s') := let (l, r) := split_at n s' in (list.cons x l, r) end section zip_with /-- Combine two sequences with a function -/ def zip_with (f : α → β → γ) : seq α → seq β → seq γ | ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ := ⟨λn, match f₁ n, f₂ n with | some a, some b := some (f a b) | _, _ := none end, λn, begin induction h1 : f₁ n, { intro H, simp only [(a₁ h1)], refl }, induction h2 : f₂ n; dsimp [seq.zip_with._match_1]; intro H, { rw (a₂ h2), cases f₁ (n + 1); refl }, { rw [h1, h2] at H, contradiction } end⟩ variables {s : seq α} {s' : seq β} {n : ℕ} lemma zip_with_nth_some {a : α} {b : β} (s_nth_eq_some : s.nth n = some a) (s_nth_eq_some' : s'.nth n = some b) (f : α → β → γ) : (zip_with f s s').nth n = some (f a b) := begin cases s with st, have : st n = some a, from s_nth_eq_some, cases s' with st', have : st' n = some b, from s_nth_eq_some', simp only [zip_with, seq.nth, *] end lemma zip_with_nth_none (s_nth_eq_none : s.nth n = none) (f : α → β → γ) : (zip_with f s s').nth n = none := begin cases s with st, have : st n = none, from s_nth_eq_none, cases s' with st', cases st'_nth_eq : st' n; simp only [zip_with, seq.nth, *] end lemma zip_with_nth_none' (s'_nth_eq_none : s'.nth n = none) (f : α → β → γ) : (zip_with f s s').nth n = none := begin cases s' with st', have : st' n = none, from s'_nth_eq_none, cases s with st, cases st_nth_eq : st n; simp only [zip_with, seq.nth, *] end end zip_with /-- Pair two sequences into a sequence of pairs -/ def zip : seq α → seq β → seq (α × β) := zip_with prod.mk /-- Separate a sequence of pairs into two sequences -/ def unzip (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s) /-- Convert a sequence which is known to terminate into a list -/ def to_list (s : seq α) (h : ∃ n, ¬ (nth s n).is_some) : list α := take (nat.find h) s /-- Convert a sequence which is known not to terminate into a stream -/ def to_stream (s : seq α) (h : ∀ n, (nth s n).is_some) : stream α := λn, option.get (h n) /-- Convert a sequence into either a list or a stream depending on whether it is finite or infinite. (Without decidability of the infiniteness predicate, this is not constructively possible.) -/ def to_list_or_stream (s : seq α) [decidable (∃ n, ¬ (nth s n).is_some)] : list α ⊕ stream α := if h : ∃ n, ¬ (nth s n).is_some then sum.inl (to_list s h) else sum.inr (to_stream s (λn, decidable.by_contradiction (λ hn, h ⟨n, hn⟩))) @[simp] theorem nil_append (s : seq α) : append nil s = s := begin apply coinduction2, intro s, dsimp [append], rw [corec_eq], dsimp [append], apply cases_on s _ _, { trivial }, { intros x s, rw [destruct_cons], dsimp, exact ⟨rfl, s, rfl, rfl⟩ } end @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := destruct_eq_cons $ begin dsimp [append], rw [corec_eq], dsimp [append], rw [destruct_cons], dsimp [append], refl end @[simp] theorem append_nil (s : seq α) : append s nil = s := begin apply coinduction2 s, intro s, apply cases_on s _ _, { trivial }, { intros x s, rw [cons_append, destruct_cons, destruct_cons], dsimp, exact ⟨rfl, s, rfl, rfl⟩ } end @[simp] theorem append_assoc (s t u : seq α) : append (append s t) u = append s (append t u) := begin apply eq_of_bisim (λs1 s2, ∃ s t u, s1 = append (append s t) u ∧ s2 = append s (append t u)), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, u, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on t; simp, { apply cases_on u; simp, { intros x u, refine ⟨nil, nil, u, _, _⟩; simp } }, { intros x t, refine ⟨nil, t, u, _, _⟩; simp } }, { intros x s, exact ⟨s, t, u, rfl, rfl⟩ } end end }, { exact ⟨s, t, u, rfl, rfl⟩ } end @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [cons, map]; rw stream.map_cons; refl @[simp] theorem map_id : ∀ (s : seq α), map id s = s | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw [option.map_id, stream.map_id]; refl end @[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [tail, map]; rw stream.map_tail; refl theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : seq α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), funext x, cases x with x; refl end @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := begin apply eq_of_bisim (λs1 s2, ∃ s t, s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩, intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on t; simp, { intros x t, refine ⟨nil, t, _, _⟩; simp } }, { intros x s, refine ⟨s, t, rfl, rfl⟩ } end end end @[simp] theorem map_nth (f : α → β) : ∀ s n, nth (map f s) n = (nth s n).map f | ⟨s, al⟩ n := rfl instance : functor seq := {map := @map} instance : is_lawful_functor seq := { id_map := @map_id, comp_map := @map_comp } @[simp] theorem join_nil : join nil = (nil : seq α) := destruct_eq_nil rfl @[simp] theorem join_cons_nil (a : α) (S) : join (cons (a, nil) S) = cons a (join S) := destruct_eq_cons $ by simp [join] @[simp] theorem join_cons_cons (a b : α) (s S) : join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) := destruct_eq_cons $ by simp [join] @[simp] theorem join_cons (a : α) (s S) : join (cons (a, s) S) = cons a (append s (join S)) := begin apply eq_of_bisim (λs1 s2, s1 = s2 ∨ ∃ a s S, s1 = join (cons (a, s) S) ∧ s2 = cons a (append s (join S))) _ (or.inr ⟨a, s, S, rfl, rfl⟩), intros s1 s2 h, exact match s1, s2, h with | _, _, (or.inl $ eq.refl s) := begin apply cases_on s, { trivial }, { intros x s, rw [destruct_cons], exact ⟨rfl, or.inl rfl⟩ } end | ._, ._, (or.inr ⟨a, s, S, rfl, rfl⟩) := begin apply cases_on s, { simp }, { intros x s, simp, refine or.inr ⟨x, s, S, rfl, rfl⟩ } end end end @[simp] theorem join_append (S T : seq (seq1 α)) : join (append S T) = append (join S) (join T) := begin apply eq_of_bisim (λs1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on S; simp, { apply cases_on T, { simp }, { intros s T, cases s with a s; simp, refine ⟨s, nil, T, _, _⟩; simp } }, { intros s S, cases s with a s; simp, exact ⟨s, S, T, rfl, rfl⟩ } }, { intros x s, exact ⟨s, S, T, rfl, rfl⟩ } end end }, { refine ⟨nil, S, T, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : seq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := begin apply subtype.eq, simp [of_list, cons], funext n, cases n; simp [list.nth, stream.cons] end @[simp] theorem of_stream_cons (a : α) (s) : of_stream (a :: s) = cons a (of_stream s) := by apply subtype.eq; simp [of_stream, cons]; rw stream.map_cons @[simp] theorem of_list_append (l l' : list α) : of_list (l ++ l') = append (of_list l) (of_list l') := by induction l; simp [*] @[simp] theorem of_stream_append (l : list α) (s : stream α) : of_stream (l ++ₛ s) = append (of_list l) (of_stream s) := by induction l; simp [*, stream.nil_append_stream, stream.cons_append_stream] /-- Convert a sequence into a list, embedded in a computation to allow for the possibility of infinite sequences (in which case the computation never returns anything). -/ def to_list' {α} (s : seq α) : computation (list α) := @computation.corec (list α) (list α × seq α) (λ⟨l, s⟩, match destruct s with | none := sum.inl l.reverse | some (a, s') := sum.inr (a::l, s') end) ([], s) theorem dropn_add (s : seq α) (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 : seq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_tail : ∀ (s : seq α) n, nth (tail s) n = nth s (n + 1) | ⟨f, al⟩ n := rfl @[extensionality] protected lemma ext (s s': seq α) (hyp : ∀ (n : ℕ), s.nth n = s'.nth n) : s = s' := begin let ext := (λ (s s' : seq α), ∀ n, s.nth n = s'.nth n), apply seq.eq_of_bisim ext _ hyp, -- we have to show that ext is a bisimulation clear hyp s s', assume s s' (hyp : ext s s'), unfold seq.destruct, rw (hyp 0), cases (s'.nth 0), { simp [seq.bisim_o] }, -- option.none { -- option.some suffices : ext s.tail s'.tail, by simpa, assume n, simp only [seq.nth_tail _ n, (hyp $ n + 1)] } end @[simp] theorem head_dropn (s : seq α) (n) : head (drop s n) = nth s n := begin induction n with n IH generalizing s, { refl }, rw [nat.succ_eq_add_one, ←nth_tail, ←dropn_tail], apply IH end theorem mem_map (f : α → β) {a : α} : ∀ {s : seq α}, a ∈ s → f a ∈ map f s | ⟨g, al⟩ := stream.mem_map (option.map f) theorem exists_of_mem_map {f} {b : β} : ∀ {s : seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := stream.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ theorem of_mem_append {s₁ s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ := begin have := h, revert this, generalize e : append s₁ s₂ = ss, intro h, revert s₁, apply mem_rec_on h _, intros b s' o s₁, apply s₁.cases_on _ (λ c t₁, _); intros m e; have := congr_arg destruct e, { apply or.inr, simpa using m }, { cases (show a = c ∨ a ∈ append t₁ s₂, by simpa using m) with e' m, { rw e', exact or.inl (mem_cons _ _) }, { cases (show c = b ∧ append t₁ s₂ = s', by simpa) with i1 i2, cases o with e' IH, { simp [i1, e'] }, { exact or.imp_left (mem_cons_of_mem _) (IH m i2) } } } end theorem mem_append_left {s₁ s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ := by apply mem_rec_on h; intros; simp [*] end seq namespace seq1 variables {α : Type u} {β : Type v} {γ : Type w} open seq /-- Convert a `seq1` to a sequence. -/ def to_seq : seq1 α → seq α | (a, s) := cons a s instance coe_seq : has_coe (seq1 α) (seq α) := ⟨to_seq⟩ /-- Map a function on a `seq1` -/ def map (f : α → β) : seq1 α → seq1 β | (a, s) := (f a, seq.map f s) theorem map_id : ∀ (s : seq1 α), map id s = s | ⟨a, s⟩ := by simp [map] /-- Flatten a nonempty sequence of nonempty sequences -/ def join : seq1 (seq1 α) → seq1 α | ((a, s), S) := match destruct s with | none := (a, seq.join S) | some s' := (a, seq.join (cons s' S)) end @[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, seq.join S) := rfl @[simp] theorem join_cons (a b : α) (s S) : join ((a, cons b s), S) = (a, seq.join (cons (b, s) S)) := by dsimp [join]; rw [destruct_cons]; refl /-- The `return` operator for the `seq1` monad, which produces a singleton sequence. -/ def ret (a : α) : seq1 α := (a, nil) /-- The `bind` operator for the `seq1` monad, which maps `f` on each element of `s` and appends the results together. (Not all of `s` may be evaluated, because the first few elements of `s` may already produce an infinite result.) -/ def bind (s : seq1 α) (f : α → seq1 β) : seq1 β := join (map f s) @[simp] theorem join_map_ret (s : seq α) : seq.join (seq.map ret s) = s := by apply coinduction2 s; intro s; apply cases_on s; simp [ret] @[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s | ⟨a, s⟩ := begin dsimp [bind, map], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], simp [function.comp, ret] end @[simp] theorem ret_bind (a : α) (f : α → seq1 β) : bind (ret a) f = f a := begin simp [ret, bind, map], cases f a with a s, apply cases_on s; intros; simp end @[simp] theorem map_join' (f : α → β) (S) : seq.map f (seq.join S) = seq.join (seq.map (map f) S) := begin apply eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (seq.map f (seq.join S)) ∧ s2 = append s (seq.join (seq.map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on S; simp, { intros x S, cases x with a s; simp [map], exact ⟨_, _, rfl, rfl⟩ } }, { intros x s, refine ⟨s, S, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S) | ((a, s), S) := by apply cases_on s; intros; simp [map] @[simp] theorem join_join (SS : seq (seq1 (seq1 α))) : seq.join (seq.join SS) = seq.join (seq.map join SS) := begin apply eq_of_bisim (λs1 s2, ∃ s SS, s1 = seq.append s (seq.join (seq.join SS)) ∧ s2 = seq.append s (seq.join (seq.map join SS))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, SS, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on SS; simp, { intros S SS, cases S with s S; cases s with x s; simp [map], apply cases_on s; simp, { exact ⟨_, _, rfl, rfl⟩ }, { intros x s, refine ⟨cons x (append s (seq.join S)), SS, _, _⟩; simp } } }, { intros x s, exact ⟨s, SS, rfl, rfl⟩ } end end }, { refine ⟨nil, SS, _, _⟩; simp } end @[simp] theorem bind_assoc (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin cases s with a s, simp [bind, map], rw [←map_comp], change (λ x, join (map g (f x))) with (join ∘ ((map g) ∘ f)), rw [map_comp _ join], generalize : seq.map (map g ∘ f) s = SS, rcases map g (f a) with ⟨⟨a, s⟩, S⟩, apply cases_on s; intros; apply cases_on S; intros; simp, { cases x with x t, apply cases_on t; intros; simp }, { cases x_1 with y t; simp } end instance : monad seq1 := { map := @map, pure := @ret, bind := @bind } instance : is_lawful_monad seq1 := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } end seq1
fb2b49bdcda59680489396658d31b0fc6274a012
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/bicones.lean
398c59142b902e906720cb3990259e0ec3ae670e
[ "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
4,699
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import category_theory.limits.cones import category_theory.structured_arrow import category_theory.fin_category /-! # Bicones Given a category `J`, a walking `bicone J` is a category whose objects are the objects of `J` and two extra vertices `bicone.left` and `bicone.right`. The morphisms are the morphisms of `J` and `left ⟶ j`, `right ⟶ j` for each `j : J` such that `⬝ ⟶ j` and `⬝ ⟶ k` commutes with each `f : j ⟶ k`. Given a diagram `F : J ⥤ C` and two `cone F`s, we can join them into a diagram `bicone J ⥤ C` via `bicone_mk`. This is used in `category_theory.flat_functors.preserves_finite_limits_of_flat`. -/ universes v₁ u₁ noncomputable theory open category_theory.limits open_locale classical namespace category_theory section bicone variables (J : Type u₁) /-- Given a category `J`, construct a walking `bicone J` by adjoining two elements. -/ @[derive decidable_eq] inductive bicone | left : bicone | right : bicone | diagram (val : J) : bicone instance : inhabited (bicone J) := ⟨bicone.left⟩ instance fin_bicone [fintype J] : fintype (bicone J) := { elems := [bicone.left, bicone.right].to_finset ∪ finset.image bicone.diagram (fintype.elems J), complete := λ j, by { cases j; simp, exact fintype.complete j, }, } variables [category.{v₁} J] /-- The homs for a walking `bicone J`. -/ inductive bicone_hom : bicone J → bicone J → Type (max u₁ v₁) | left_id : bicone_hom bicone.left bicone.left | right_id : bicone_hom bicone.right bicone.right | left (j : J) : bicone_hom bicone.left (bicone.diagram j) | right (j : J) : bicone_hom bicone.right (bicone.diagram j) | diagram {j k : J} (f : j ⟶ k) : bicone_hom (bicone.diagram j) (bicone.diagram k) instance : inhabited (bicone_hom J bicone.left bicone.left) := ⟨bicone_hom.left_id⟩ instance bicone_hom.decidable_eq {j k : bicone J} : decidable_eq (bicone_hom J j k) := λ f g, by { cases f; cases g; simp; apply_instance } @[simps] instance bicone_category_struct : category_struct (bicone J) := { hom := bicone_hom J, id := λ j, bicone.cases_on j bicone_hom.left_id bicone_hom.right_id (λ k, bicone_hom.diagram (𝟙 k)), comp := λ X Y Z f g, by { cases f, exact g, exact g, cases g, exact bicone_hom.left g_k, cases g, exact bicone_hom.right g_k, cases g, exact bicone_hom.diagram (f_f ≫ g_f) } } instance bicone_category : category (bicone J) := { id_comp' := λ X Y f, by { cases f; simp }, comp_id' := λ X Y f, by { cases f; simp }, assoc' := λ W X Y Z f g h, by { cases f; cases g; cases h; simp } } end bicone section small_category variables (J : Type v₁) [small_category J] /-- Given a diagram `F : J ⥤ C` and two `cone F`s, we can join them into a diagram `bicone J ⥤ C`. -/ @[simps] def bicone_mk {C : Type u₁} [category.{v₁} C] {F : J ⥤ C} (c₁ c₂ : cone F) : bicone J ⥤ C := { obj := λ X, bicone.cases_on X c₁.X c₂.X (λ j, F.obj j), map := λ X Y f, by { cases f, exact (𝟙 _), exact (𝟙 _), exact c₁.π.app f_1, exact c₂.π.app f_1, exact F.map f_f, }, map_id' := λ X, by { cases X; simp }, map_comp' := λ X Y Z f g, by { cases f, exact (category.id_comp _).symm, exact (category.id_comp _).symm, cases g, exact (category.id_comp _).symm.trans (c₁.π.naturality g_f : _), cases g, exact (category.id_comp _).symm.trans (c₂.π.naturality g_f : _), cases g, exact F.map_comp _ _ } } instance fin_bicone_hom [fin_category J] (j k : bicone J) : fintype (j ⟶ k) := begin cases j; cases k, exact { elems := {bicone_hom.left_id}, complete := λ f, by { cases f, simp } }, exact { elems := ∅, complete := λ f, by { cases f } }, exact { elems := {bicone_hom.left k}, complete := λ f, by { cases f, simp } }, exact { elems := ∅, complete := λ f, by { cases f } }, exact { elems := {bicone_hom.right_id}, complete := λ f, by { cases f, simp } }, exact { elems := {bicone_hom.right k}, complete := λ f, by { cases f, simp } }, exact { elems := ∅, complete := λ f, by { cases f } }, exact { elems := ∅, complete := λ f, by { cases f } }, exact { elems := finset.image (bicone_hom.diagram) (fintype.elems (j ⟶ k)), complete := λ f, by { cases f, simp only [finset.mem_image], use f_f, simpa using fintype.complete _, } }, end instance bicone_small_category : small_category (bicone J) := category_theory.bicone_category J instance bicone_fin_category [fin_category J] : fin_category (bicone J) := {} end small_category end category_theory
8427badc0646f13adf3bcc8d8182516c4a44c124
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/vector_bundle.lean
ad1b6332151a2e29821287a06b743c9f6f268e0e
[ "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
17,702
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Sebastien Gouezel -/ import topology.fiber_bundle import topology.algebra.module /-! # Topological vector bundles In this file we define topological vector bundles. Let `B` be the base space. In our formalism, a topological vector bundle is by definition the type `bundle.total_space E` where `E : B → Type*` is a function associating to `x : B` the fiber over `x`. This type `bundle.total_space E` is just a type synonym for `Σ (x : B), E x`, with the interest that one can put another topology than on `Σ (x : B), E x` which has the disjoint union topology. To have a topological vector bundle structure on `bundle.total_space E`, one should addtionally have the following data: * `F` should be a topological space and a module over a semiring `R`; * There should be a topology on `bundle.total_space E`, for which the projection to `B` is a topological fiber bundle with fiber `F` (in particular, each fiber `E x` is homeomorphic to `F`); * For each `x`, the fiber `E x` should be a topological vector space over `R`, and the injection from `E x` to `bundle.total_space F E` should be an embedding; * The most important condition: around each point, there should be a bundle trivialization which is a continuous linear equiv in the fibers. If all these conditions are satisfied, we register the typeclass `topological_vector_bundle R F E`. We emphasize that the data is provided by other classes, and that the `topological_vector_bundle` class is `Prop`-valued. The point of this formalism is that it is unbundled in the sense that the total space of the bundle is a type with a topology, with which one can work or put further structure, and still one can perform operations on topological vector bundles (which are yet to be formalized). For instance, assume that `E₁ : B → Type*` and `E₂ : B → Type*` define two topological vector bundles over `R` with fiber models `F₁` and `F₂` which are normed spaces. Then one can construct the vector bundle of continuous linear maps from `E₁ x` to `E₂ x` with fiber `E x := (E₁ x →L[R] E₂ x)` (and with the topology inherited from the norm-topology on `F₁ →L[R] F₂`, without the need to define the strong topology on continuous linear maps between general topological vector spaces). Let `vector_bundle_continuous_linear_map R F₁ E₁ F₂ E₂ (x : B)` be a type synonym for `E₁ x →L[R] E₂ x`. Then one can endow `bundle.total_space (vector_bundle_continuous_linear_map R F₁ E₁ F₂ E₂)` with a topology and a topological vector bundle structure. Similar constructions can be done for tensor products of topological vector bundles, exterior algebras, and so on, where the topology can be defined using a norm on the fiber model if this helps. ## Tags Vector bundle -/ noncomputable theory open bundle set variables (R : Type*) {B : Type*} (F : Type*) (E : B → Type*) [semiring R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [topological_space F] [add_comm_monoid F] [module R F] [topological_space (total_space E)] [topological_space B] section /-- Local trivialization for vector bundles. -/ @[nolint has_inhabited_instance] structure topological_vector_bundle.trivialization extends to_fiber_bundle_trivialization : topological_fiber_bundle.trivialization F (proj E) := (linear : ∀ x ∈ base_set, is_linear_map R (λ y : (E x), (to_fun y).2)) open topological_vector_bundle instance : has_coe_to_fun (trivialization R F E) := ⟨_, λ e, e.to_fun⟩ instance : has_coe (trivialization R F E) (topological_fiber_bundle.trivialization F (proj E)) := ⟨topological_vector_bundle.trivialization.to_fiber_bundle_trivialization⟩ namespace topological_vector_bundle variables {R F E} lemma trivialization.mem_source (e : trivialization R F E) {x : total_space E} : x ∈ e.source ↔ proj E x ∈ e.base_set := topological_fiber_bundle.trivialization.mem_source e @[simp, mfld_simps] lemma trivialization.coe_coe (e : trivialization R F E) : ⇑e.to_local_homeomorph = e := rfl @[simp, mfld_simps] lemma trivialization.coe_fst (e : trivialization R F E) {x : total_space E} (ex : x ∈ e.source) : (e x).1 = (proj E) x := e.proj_to_fun x ex end topological_vector_bundle end variables [∀ x, topological_space (E x)] /-- The space `total_space E` (for `E : B → Type*` such that each `E x` is a topological vector space) has a topological vector space structure with fiber `F` (denoted with `topological_vector_bundle R F E`) if around every point there is a fiber bundle trivialization which is linear in the fibers. -/ class topological_vector_bundle : Prop := (inducing [] : ∀ (b : B), inducing (λ x : (E b), (id ⟨b, x⟩ : total_space E))) (locally_trivial [] : ∀ b : B, ∃ e : topological_vector_bundle.trivialization R F E, b ∈ e.base_set) variable [topological_vector_bundle R F E] namespace topological_vector_bundle /-- `trivialization_at R F E b` is some choice of trivialization of a vector bundle whose base set contains a given point `b`. -/ def trivialization_at : Π b : B, trivialization R F E := λ b, classical.some (locally_trivial R F E b) @[simp, mfld_simps] lemma mem_base_set_trivialization_at (b : B) : b ∈ (trivialization_at R F E b).base_set := classical.some_spec (locally_trivial R F E b) @[simp, mfld_simps] lemma mem_source_trivialization_at (z : total_space E) : z ∈ (trivialization_at R F E z.1).source := by { rw topological_fiber_bundle.trivialization.mem_source, apply mem_base_set_trivialization_at } variables {R F E} namespace trivialization /-- In a topological vector bundle, a trivialization in the fiber (which is a priori only linear) is in fact a continuous linear equiv between the fibers and the model fiber. -/ def continuous_linear_equiv_at (e : trivialization R F E) (b : B) (hb : b ∈ e.base_set) : E b ≃L[R] F := { to_fun := λ y, (e ⟨b, y⟩).2, inv_fun := λ z, begin have : ((e.to_local_homeomorph.symm) (b, z)).fst = b := topological_fiber_bundle.trivialization.proj_symm_apply' _ hb, have C : E ((e.to_local_homeomorph.symm) (b, z)).fst = E b, by rw this, exact cast C (e.to_local_homeomorph.symm (b, z)).2 end, left_inv := begin assume v, rw [← heq_iff_eq], apply (cast_heq _ _).trans, have A : (b, (e ⟨b, v⟩).snd) = e ⟨b, v⟩, { refine prod.ext _ rfl, symmetry, exact topological_fiber_bundle.trivialization.coe_fst' _ hb }, have B : e.to_local_homeomorph.symm (e ⟨b, v⟩) = ⟨b, v⟩, { apply local_homeomorph.left_inv_on, rw topological_fiber_bundle.trivialization.mem_source, exact hb }, rw [A, B], end, right_inv := begin assume v, have B : e (e.to_local_homeomorph.symm (b, v)) = (b, v), { apply local_homeomorph.right_inv_on, rw topological_fiber_bundle.trivialization.mem_target, exact hb }, have C : (e (e.to_local_homeomorph.symm (b, v))).2 = v, by rw [B], conv_rhs { rw ← C }, dsimp, congr, ext, { exact (topological_fiber_bundle.trivialization.proj_symm_apply' _ hb).symm }, { exact (cast_heq _ _).trans (by refl) }, end, map_add' := λ v w, (e.linear _ hb).map_add v w, map_smul' := λ c v, (e.linear _ hb).map_smul c v, continuous_to_fun := begin refine continuous_snd.comp _, apply continuous_on.comp_continuous e.to_local_homeomorph.continuous_on (topological_vector_bundle.inducing R F E b).continuous (λ x, _), rw topological_fiber_bundle.trivialization.mem_source, exact hb, end, continuous_inv_fun := begin rw (topological_vector_bundle.inducing R F E b).continuous_iff, dsimp, have : continuous (λ (z : F), e.to_fiber_bundle_trivialization.to_local_homeomorph.symm (b, z)), { apply e.to_local_homeomorph.symm.continuous_on.comp_continuous (continuous_const.prod_mk continuous_id') (λ z, _), simp only [topological_fiber_bundle.trivialization.mem_target, hb, local_equiv.symm_source, local_homeomorph.symm_to_local_equiv] }, convert this, ext z, { exact (topological_fiber_bundle.trivialization.proj_symm_apply' _ hb).symm }, { exact cast_heq _ _ }, end } @[simp] lemma continuous_linear_equiv_at_apply (e : trivialization R F E) (b : B) (hb : b ∈ e.base_set) (y : E b) : e.continuous_linear_equiv_at b hb y = (e ⟨b, y⟩).2 := rfl @[simp] lemma continuous_linear_equiv_at_apply' (e : trivialization R F E) (x : total_space E) (hx : x ∈ e.source) : e.continuous_linear_equiv_at (proj E x) (e.mem_source.1 hx) x.2 = (e x).2 := by { cases x, refl } end trivialization section local attribute [reducible] bundle.trivial instance {B : Type*} {F : Type*} [add_comm_monoid F] (b : B) : add_comm_monoid (bundle.trivial B F b) := ‹add_comm_monoid F› instance {B : Type*} {F : Type*} [add_comm_group F] (b : B) : add_comm_group (bundle.trivial B F b) := ‹add_comm_group F› instance {B : Type*} {F : Type*} [add_comm_monoid F] [module R F] (b : B) : module R (bundle.trivial B F b) := ‹module R F› end variables (R B F) /-- Local trivialization for trivial bundle. -/ def trivial_topological_vector_bundle.trivialization : trivialization R F (bundle.trivial B F) := { to_fun := λ x, (x.fst, x.snd), inv_fun := λ y, ⟨y.fst, y.snd⟩, source := univ, target := univ, map_source' := λ x h, mem_univ (x.fst, x.snd), map_target' :=λ y h, mem_univ ⟨y.fst, y.snd⟩, left_inv' := λ x h, sigma.eq rfl rfl, right_inv' := λ x h, prod.ext rfl rfl, open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced], simp only [prod.topological_space, induced_inf, induced_compose], exact le_refl _, }, continuous_inv_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced], simp only [bundle.total_space.topological_space, induced_inf, induced_compose], exact le_refl _, }, base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp only [univ_prod_univ], proj_to_fun := λ y hy, rfl, linear := λ x hx, ⟨λ y z, rfl, λ c y, rfl⟩ } instance trivial_bundle.topological_vector_bundle : topological_vector_bundle R F (bundle.trivial B F) := { locally_trivial := λ x, ⟨trivial_topological_vector_bundle.trivialization R B F, mem_univ x⟩, inducing := λ b, ⟨begin have : (λ (x : trivial B F b), x) = @id F, by { ext x, refl }, simp only [total_space.topological_space, induced_inf, induced_compose, function.comp, proj, induced_const, top_inf_eq, trivial.proj_snd, id.def, trivial.topological_space, this, induced_id], end⟩ } variables {R B F} /- Not registered as an instance because of a metavariable. -/ lemma is_topological_vector_bundle_is_topological_fiber_bundle : is_topological_fiber_bundle F (proj E) := λ x, ⟨(trivialization_at R F E x).to_fiber_bundle_trivialization, mem_base_set_trivialization_at R F E x⟩ end topological_vector_bundle /-! ### Constructing topological vector bundles -/ variables (B) /-- Analogous construction of `topological_fiber_bundle_core` for vector bundles. This construction gives a way to construct vector bundles from a structure registering how trivialization changes act on fibers.-/ @[nolint has_inhabited_instance] structure topological_vector_bundle_core (ι : Type*) := (base_set : ι → set B) (is_open_base_set : ∀ i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀ x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → (F →ₗ[R] F)) (coord_change_self : ∀ i, ∀ x ∈ base_set i, ∀ v, coord_change i i x v = v) (coord_change_continuous : ∀ i j, continuous_on (λp : B × F, coord_change i j p.1 p.2) (set.prod ((base_set i) ∩ (base_set j)) univ)) (coord_change_comp : ∀ i j k, ∀ x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀ v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) attribute [simp, mfld_simps] topological_vector_bundle_core.mem_base_set_at namespace topological_vector_bundle_core variables {R B F} {ι : Type*} (Z : topological_vector_bundle_core R B F ι) /-- Natural identification to a `topological_fiber_bundle_core`. -/ def to_topological_vector_bundle_core : topological_fiber_bundle_core ι B F := { coord_change := λ i j b, Z.coord_change i j b, ..Z } instance to_topological_vector_bundle_core_coe : has_coe (topological_vector_bundle_core R B F ι) (topological_fiber_bundle_core ι B F) := ⟨to_topological_vector_bundle_core⟩ include Z lemma coord_change_linear_comp (i j k : ι): ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j) ∩ (Z.base_set k), (Z.coord_change j k x).comp (Z.coord_change i j x) = Z.coord_change i k x := λ x hx, by { ext v, exact Z.coord_change_comp i j k x hx v } /-- The index set of a topological vector bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments has_inhabited_instance] def index := ι /-- The base space of a topological vector bundle core, as a convenience function for dot notation-/ @[nolint unused_arguments, reducible] def base := B /-- The fiber of a topological vector bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments has_inhabited_instance] def fiber (x : B) := F section fiber_instances local attribute [reducible] fiber --just to record instances instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by apply_instance instance add_comm_monoid_fiber : ∀ (x : B), add_comm_monoid (Z.fiber x) := λ x, by apply_instance instance module_fiber : ∀ (x : B), module R (Z.fiber x) := λ x, by apply_instance end fiber_instances /-- The projection from the total space of a topological fiber bundle core, on its base. -/ @[reducible, simp, mfld_simps] def proj : total_space Z.fiber → B := bundle.proj Z.fiber /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := topological_fiber_bundle_core.triv_change ↑Z i j @[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := topological_fiber_bundle_core.mem_triv_change_source ↑Z i j p variable (ι) /-- Topological structure on the total space of a topological bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space (total_space Z.fiber) := topological_fiber_bundle_core.to_topological_space ι ↑Z variables {ι} (b : B) (a : F) @[simp, mfld_simps] lemma coe_cord_change (i j : ι) : topological_fiber_bundle_core.coord_change ↑Z i j b = Z.coord_change i j b := rfl /-- Extended version of the local trivialization of a fiber bundle constructed from core, registering additionally in its type that it is a local bundle trivialization. -/ def local_triv (i : ι) : topological_vector_bundle.trivialization R F Z.fiber := { linear := λ x hx, { map_add := λ v w, by simp only [linear_map.map_add] with mfld_simps, map_smul := λ r v, by simp only [linear_map.map_smul] with mfld_simps}, ..topological_fiber_bundle_core.local_triv ↑Z i } @[simp, mfld_simps] lemma mem_local_triv_source (i : ι) (p : total_space Z.fiber) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i := iff.rfl /-- Preferred local trivialization of a vector bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at (b : B) : topological_vector_bundle.trivialization R F Z.fiber := Z.local_triv (Z.index_at b) lemma mem_source_at : (⟨b, a⟩ : total_space Z.fiber) ∈ (Z.local_triv_at b).source := by { rw [local_triv_at, mem_local_triv_source], exact Z.mem_base_set_at b } @[simp, mfld_simps] lemma local_triv_at_apply : ((Z.local_triv_at b) ⟨b, a⟩) = ⟨b, a⟩ := topological_fiber_bundle_core.local_triv_at_apply Z b a instance : topological_vector_bundle R F Z.fiber := { inducing := λ b, ⟨ begin refine le_antisymm _ (λ s h, _), { rw ←continuous_iff_le_induced, exact topological_fiber_bundle_core.continuous_total_space_mk ↑Z b, }, { refine is_open_induced_iff.mpr ⟨(Z.local_triv_at b).source ∩ (Z.local_triv_at b) ⁻¹' (Z.local_triv_at b).base_set.prod s, (continuous_on_open_iff (Z.local_triv_at b).open_source).mp (Z.local_triv_at b).continuous_to_fun _ (is_open.prod (Z.local_triv_at b).open_base_set h), _⟩, rw [preimage_inter, ←preimage_comp, function.comp], simp only [id.def], refine ext_iff.mpr (λ a, ⟨λ ha, _, λ ha, ⟨Z.mem_base_set_at b, _⟩⟩), { simp only [mem_prod, mem_preimage, mem_inter_eq, local_triv_at_apply] at ha, exact ha.2.2, }, { simp only [mem_prod, mem_preimage, mem_inter_eq, local_triv_at_apply], exact ⟨Z.mem_base_set_at b, ha⟩, } } end⟩, locally_trivial := λ b, ⟨Z.local_triv_at b, Z.mem_base_set_at b⟩, } /-- The projection on the base of a topological vector bundle created from core is continuous -/ @[continuity] lemma continuous_proj : continuous Z.proj := topological_fiber_bundle_core.continuous_proj Z /-- The projection on the base of a topological vector bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := topological_fiber_bundle_core.is_open_map_proj Z end topological_vector_bundle_core
c8aa0f3d3a1aeeeac85a793d3854ca159b0b20a7
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/euclidean_domain.lean
6def05b27ee67bd14accf055c007502037548bbd
[]
no_license
johoelzl/mason-stother
0c78bca183eb729d7f0f93e87ce073bc8cd8808d
573ecfaada288176462c03c87b80ad05bdab4644
refs/heads/master
1,631,751,973,492
1,528,923,934,000
1,528,923,934,000
109,133,224
0
1
null
null
null
null
UTF-8
Lean
false
false
466
lean
universe u variable {α : Type u} --variable [integral_domain α ] --structure has_norm (α : Type u) [integral_domain α]: Type u:= -- Can this be made into a type class? -- (h2 : ∀ a : α, a ≠ 0 → norm a ≠ 0) class euclidean_domain (α : Type u) extends integral_domain α := (norm : α → nat) (h1 : norm 0 = 0) (h_norm: ∀ a b : α, b ≠ 0 → (∃ q : α, ∃ r : α,( (a = q * b + r) ∧ ((r = 0) ∨ ( (norm r ) < (norm b)) ) ) ) )
cc3720db6743d3af487d28535ed53bea4a064702
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/transform_decl.lean
e9fc5b29bf230df36d5ce60cc1fed158d73ea422
[]
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
328
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.meta.expr import Mathlib.meta.rb_map import Mathlib.PostPort namespace Mathlib namespace tactic
198fb6a7b9aa16b5877fa9b4604a3bc215e49ed6
dc15192b741b5d1c22cea8d65d6eb38bce3d838d
/src/rank.lean
a384e147d1f925d67db419ba17fc0aa7f4a11438
[]
no_license
VArtem/lean-matroids
86910241ac8d1a5ec7b35adb77c1cc9969480fb9
a8969b1cb2456820ccbdce65e2e168c48c30d9bf
refs/heads/main
1,678,556,999,525
1,614,537,008,000
1,614,537,008,000
338,915,729
0
1
null
null
null
null
UTF-8
Lean
false
false
3,995
lean
import data.fintype.basic import tactic import matroid import finset import base_of variables {α : Type*} [fintype α] [decidable_eq α] {m : matroid α} {A B X: finset α} open finset namespace matroid instance : decidable_pred m.ind := m.ind_dec -- def rank (m : matroid α) (A : finset α) : ℕ := card (classical.some $ exists_base_of m A) def rank (m : matroid α) (A : finset α) : ℕ := sup (filter m.ind (powerset A)) card @[simp] lemma rank_def : rank m A = sup (filter m.ind (powerset A)) card := rfl @[simp] lemma rank_empty : rank m ∅ = 0 := begin rw rank, simp only [card_empty, filter_true_of_mem, forall_eq, powerset_empty, sup_singleton, ind_empty_def, mem_singleton], end lemma rank_eq_card_base_of (Bbase : m.base_of A B) : rank m A = B.card := begin rw rank_def, apply nat.le_antisymm, { apply finset.sup_le, intros C hC, simp only [mem_powerset, mem_filter] at hC, exact ind_card_le_base_of_card hC.1 hC.2 Bbase, }, { apply le_sup, simp only [mem_powerset, mem_filter], exact ⟨Bbase.1, Bbase.2.1⟩, } end lemma rank_exists_base_of (m : matroid α) (A : finset α) : ∃ (B : finset α), m.rank A = B.card ∧ m.base_of A B := begin obtain ⟨B, Bbase⟩ := exists_base_of m A, refine ⟨B, rank_eq_card_base_of Bbase, Bbase⟩, end theorem rank_le_card : rank m A ≤ A.card := begin obtain ⟨bA, bAcard, bAbase⟩ := rank_exists_base_of m A, rw bAcard, exact card_le_of_subset bAbase.1, end @[simp] lemma rank_subset (hAB : A ⊆ B) : rank m A ≤ rank m B := begin obtain ⟨bA, bAbase⟩ := exists_base_of m A, obtain ⟨bB, bBbase⟩ := exists_base_of m B, rw rank_eq_card_base_of bAbase, rw rank_eq_card_base_of bBbase, refine ind_card_le_base_of_card (subset.trans bAbase.1 hAB) bAbase.2.1 bBbase, end @[simp] lemma rank_ind : m.ind A ↔ rank m A = A.card := begin split, { intro Aind, rw [base_of_refl_iff_ind] at Aind, rw rank_eq_card_base_of Aind, }, { intro h_card, obtain ⟨B, Bcard, Bbase⟩ := rank_exists_base_of m A, rw h_card at Bcard, suffices h_eq : A = B, { subst h_eq, exact Bbase.2.1, }, symmetry, exact eq_of_subset_of_card_le Bbase.1 (le_of_eq Bcard), } end theorem rank_submodular : m.rank (A ∩ B) + m.rank (A ∪ B) ≤ m.rank A + m.rank B := begin obtain ⟨bInter, bInter_base⟩ := exists_base_of m (A ∩ B), have rankInter := rank_eq_card_base_of bInter_base, obtain ⟨bA, bA_sub, bA_base⟩ := ind_subset_base_of (subset.trans bInter_base.1 (inter_subset_left _ _)) (bInter_base.2.1), have rankA := rank_eq_card_base_of bA_base, obtain ⟨bUnion, bUnion_sub, bUnion_base⟩ := ind_subset_base_of (subset.trans bA_base.1 (subset_union_left A B)) bA_base.2.1, have rankUnion := rank_eq_card_base_of bUnion_base, obtain ⟨bB, bB_base⟩ := exists_base_of m B, have rankB := rank_eq_card_base_of bB_base, have indB_sub : (bUnion \ (bA \ bInter)) ⊆ B := by { intros x hx, rw [mem_sdiff, not_mem_sdiff_iff] at hx, rcases hx with ⟨xBunion, xA | xInter⟩, { have xAB := bUnion_base.1 xBunion, cases (mem_union.1 xAB), { exfalso, have h_insert_dep := bA_base.2.2 _ xA h, refine h_insert_dep (ind_subset_def _ (bUnion_base.2.1)), rw ← insert_eq_of_mem xBunion, refine insert_subset_insert x bUnion_sub, }, { exact h, } }, { exact mem_of_mem_inter_right (bInter_base.1 xInter), }, }, have indB_ind : m.ind (bUnion \ (bA \ bInter)) := ind_subset_def (sdiff_subset _ _) bUnion_base.2.1, have tmp := ind_card_le_base_of_card indB_sub indB_ind bB_base, have indB_card : (bUnion \ (bA \ bInter)).card + bA.card = bUnion.card + bInter.card := by { zify, rw card_sdiff_ℤ (subset.trans (sdiff_subset bA bInter) bUnion_sub), rw card_sdiff_ℤ bA_sub, ring, }, rw [rankInter, rankA, rankUnion, rankB], linarith, end end matroid
a4da2b19ea8785c372cf4b9c4e471c2680f39503
8f209eb34c0c4b9b6be5e518ebfc767a38bed79c
/code/src/definitions.lean
7c36ff2af6e393a814a19cfb6860440e241b97f7
[]
no_license
hediet/masters-thesis
13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5
dc40c14cc4ed073673615412f36b4e386ee7aac9
refs/heads/master
1,680,591,056,302
1,617,710,887,000
1,617,710,887,000
311,762,038
4
0
null
null
null
null
UTF-8
Lean
false
false
6,715
lean
import data.bool import data.finset class GuardModule := -- Represents the result type of evaluating a guard tree. (Rhs : Type) [rhs_decidable: decidable_eq Rhs] -- Represents an environment type that is used to define a semantic for a guard tree. (Env : Type) -- Represents the type of all guards. -- A guard resembles an if-condition that can fail or pass. -- If it passes, it can modify the environment. -- The semantic of guards is defined in a way that allows for direct reuse in -- so called refinement types. (TGrd : Type) -- Describes a semantic for guards. -- None is returned if the guard fails. Guards can modify the environment. -- This abstraction allows for "let x = expr", "x == 1" or "let (Cons x:xs) = list" guards. (tgrd_eval : TGrd → Env → option Env) -- Represents the type of variables that can be compared against bottom. (Var : Type) -- Checks whether a given var in env is bottom (is_bottom : Var → Env → bool) variable [GuardModule] open GuardModule attribute [instance] GuardModule.rhs_decidable -- # Guard Trees -- ## Syntax inductive Grd | tgrd (tgrd: TGrd) | bang (var: Var) inductive Gdt | rhs (rhs: Rhs) | branch (tr1: Gdt) (tr2: Gdt) | grd (grd: Grd) (tr: Gdt) def Gdt.branch_option : option Gdt → option Gdt → option Gdt | (some tr1) (some tr2) := some (Gdt.branch tr1 tr2) | (some tr1) none := some tr1 | none (some tr2) := some tr2 | none none := none def Gdt.grd_option : Grd → option Gdt → option Gdt | grd (some tr) := some (Gdt.grd grd tr) | _ none := none -- Removes a set of rhss from a guard tree. -- Returns `none` if the guard tree is empty. def Gdt.remove_rhss : finset Rhs → Gdt → option Gdt | rhss (Gdt.rhs rhs) := if rhs ∈ rhss then none else some (Gdt.rhs rhs) | rhss (Gdt.branch tr1 tr2) := Gdt.branch_option (tr1.remove_rhss rhss) (tr2.remove_rhss rhss) | rhss (Gdt.grd grd tr) := Gdt.grd_option grd (tr.remove_rhss rhss) -- Returns a set of all rhss that a guard tree contains. def Gdt.rhss: Gdt → finset Rhs | (Gdt.rhs rhs) := { rhs } | (Gdt.branch tr1 tr2) := tr1.rhss ∪ tr2.rhss | (Gdt.grd grd tr) := tr.rhss -- States that all rhss are different in a given guard tree. def Gdt.disjoint_rhss: Gdt → Prop | (Gdt.rhs rhs) := true | (Gdt.branch tr1 tr2) := tr1.disjoint_rhss ∧ tr2.disjoint_rhss ∧ disjoint tr1.rhss tr2.rhss | (Gdt.grd grd tr) := tr.disjoint_rhss -- ## Semantic inductive Result (α: Type) | value: α → Result | diverged: Result | no_match: Result def Grd.eval : Grd → Env → Result Env | (Grd.tgrd grd) env := match tgrd_eval grd env with | none := Result.no_match | some env' := Result.value env' end | (Grd.bang var) env := if is_bottom var env then Result.diverged else Result.value env def Result.bind { α β: Type } (f: α → Result β): Result α → Result β | (Result.value val) := f val | Result.diverged := Result.diverged | Result.no_match := Result.no_match def Gdt.eval : Gdt → Env → Result Rhs | (Gdt.rhs rhs) env := Result.value rhs | (Gdt.branch tr1 tr2) env := match tr1.eval env with | Result.no_match := tr2.eval env | r := r end | (Gdt.grd grd tr) env := (grd.eval env).bind tr.eval -- This continues `gdt_eval` to `option Gdt`. def Gdt.eval_option : option Gdt → Env → Result Rhs | (some gdt) env := gdt.eval env | none env := Result.no_match -- # Refinement Types -- ## Syntax inductive Φ | false | true | tgrd_in (tgrd: TGrd) (ty: Φ) | not_tgrd (tgrd: TGrd) | var_is_bottom (var: Var) | var_is_not_bottom (var: Var) | or (ty1: Φ) (ty2: Φ) | and (ty1: Φ) (ty2: Φ) -- ## Semantic def Φ.eval: Φ → Env → bool | Φ.false env := ff | Φ.true env := tt | (Φ.tgrd_in grd ty) env := match tgrd_eval grd env with | some env := ty.eval env | none := ff end | (Φ.not_tgrd grd) env := match tgrd_eval grd env with | some env := ff | none := tt end | (Φ.var_is_bottom var) env := is_bottom var env | (Φ.var_is_not_bottom var) env := !is_bottom var env | (Φ.or t1 t2) env := t1.eval env || t2.eval env | (Φ.and t1 t2) env := t1.eval env && t2.eval env -- ## Uncovered Refinement Types def 𝒰_acc : (Φ → Φ) → Gdt → Φ | acc (Gdt.rhs _) := Φ.false | acc (Gdt.branch tr1 tr2) := (𝒰_acc ((𝒰_acc acc tr1).and ∘ acc) tr2) | acc (Gdt.grd (Grd.bang var) tr) := 𝒰_acc (acc ∘ (Φ.var_is_not_bottom var).and) tr | acc (Gdt.grd (Grd.tgrd grd) tr) := (acc (Φ.not_tgrd grd)) .or (𝒰_acc (acc ∘ (Φ.tgrd_in grd)) tr) def 𝒰 : Gdt → Φ := 𝒰_acc id -- # Annotate inductive Ant (α: Type) | rhs (a: α) (rhs: Rhs): Ant | branch (tr1: Ant) (tr2: Ant): Ant | diverge (a: α) (tr: Ant): Ant def 𝒜_acc : (Φ → Φ) → Gdt → Ant Φ | acc (Gdt.rhs rhs) := Ant.rhs (acc Φ.true) rhs | acc (Gdt.branch tr1 tr2) := Ant.branch (𝒜_acc acc tr1) (𝒜_acc ((𝒰_acc acc tr1).and ∘ acc) tr2) | acc (Gdt.grd (Grd.bang var) tr) := Ant.diverge (acc (Φ.var_is_bottom var)) (𝒜_acc (acc ∘ ((Φ.var_is_not_bottom var).and)) tr) | acc (Gdt.grd (Grd.tgrd grd) tr) := (𝒜_acc (acc ∘ (Φ.tgrd_in grd)) tr) def 𝒜 : Gdt → Ant Φ := 𝒜_acc id -- # Empty Provers def Φ.is_empty (ty: Φ): Prop := ∀ env: Env, ¬(ty.eval env) variable can_prove_empty: Φ → bool def correct_can_prove_empty : Prop := ∀ ty: Φ, can_prove_empty ty = tt → ty.is_empty -- Represents all correct G functions from the paper. def CorrectCanProveEmpty := { g : Φ → bool // correct_can_prove_empty g } -- # Definition of ℛ -- returns (accessible, inaccessible, redundant) rhss, given that `can_prove_empty` is correct. def ℛ : Ant Φ → list Rhs × list Rhs × list Rhs | (Ant.rhs ty n) := if can_prove_empty ty then ([], [], [n]) else ([n], [], []) | (Ant.branch tr1 tr2) := match (ℛ tr1, ℛ tr2) with | ((k, n, m), (k', n', m')) := (k ++ k', n ++ n', m ++ m') end | (Ant.diverge ty tr) := match ℛ tr, can_prove_empty ty with | ([], [], m :: ms), ff := ([], [m], ms) | r, _ := r end def 𝒰𝒜_acc : (Φ → Φ) → Gdt → Φ × Ant Φ | acc (Gdt.rhs rhs) := (Φ.false, Ant.rhs (acc Φ.true) rhs) | acc (Gdt.branch tr1 tr2) := let (U1, A1) := 𝒰𝒜_acc acc tr1, (U2, A2) := 𝒰𝒜_acc (U1.and ∘ acc) tr2 in (U2, Ant.branch A1 A2) | acc (Gdt.grd (Grd.bang var) tr) := let (U, A) := 𝒰𝒜_acc (acc ∘ (Φ.var_is_not_bottom var).and) tr in (U, Ant.diverge (acc (Φ.var_is_bottom var)) A) | acc (Gdt.grd (Grd.tgrd grd) tr) := let (U, A) := 𝒰𝒜_acc (acc ∘ (Φ.tgrd_in grd)) tr in ((acc (Φ.not_tgrd grd)).or U, A)
53b92795d1fefbdd354a3d2e16aa7d2e64a33115
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/integral/divergence_theorem.lean
784550e81eab1d28b2387c9479b30fd92dcb1e7e
[ "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
6,468
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.divergence_theorem import analysis.box_integral.integrability import measure_theory.integral.interval_integral /-! # Divergence theorem for Bochner integral In this file we prove the Divergence theorem for Bochner integral on a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`. More precisely, we prove the following theorem. Let `E` be a complete normed space with second countably topology. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriat signs. Moreover, the same is true if the function is not differentiable but continuous at countably many points of `[a, b]`. ## Notations We use the following local notation to make the statement more readable. Note that the documentation website shows the actual terms, not those abbreviated using local notations. * `ℝⁿ`, `ℝⁿ⁺¹`, `Eⁿ⁺¹`: `fin n → ℝ`, `fin (n + 1) → ℝ`, `fin (n + 1) → E`; * `face i`: the `i`-th face of the box `[a, b]` as a closed segment in `ℝⁿ`, namely `[a ∘ fin.succ_above i, b ∘ fin.succ_above i]`; * `e i` : `i`-th basis vector `pi.single i 1`; * `front_face i`, `back_face i`: embeddings `ℝⁿ → ℝⁿ⁺¹` corresponding to the front face `{x | x i = b i}` and back face `{x | x i = a i}` of the box `[a, b]`, respectively. They are given by `fin.insert_nth i (b i)` and `fin.insert_nth i (a i)`. ## TODO * Deduce corollaries about integrals in `ℝ × ℝ` and interval integral. * Add a version that assumes existence and integrability of partial derivatives. ## Tags divergence theorem, Bochner integral -/ open set finset topological_space function box_integral open_locale big_operators classical namespace measure_theory universes u variables {E : Type u} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [second_countable_topology E] [complete_space E] section variables {n : ℕ} local notation `ℝⁿ` := fin n → ℝ local notation `ℝⁿ⁺¹` := fin (n + 1) → ℝ local notation `Eⁿ⁺¹` := fin (n + 1) → E variables (a b : ℝⁿ⁺¹) local notation `face` i := set.Icc (a ∘ fin.succ_above i) (b ∘ fin.succ_above i) local notation `e` i := pi.single i 1 local notation `front_face` i:2000 := fin.insert_nth i (b i) local notation `back_face` i:2000 := fin.insert_nth i (a i) /-- **Divergence theorem** for Bochner integral. If `f : ℝⁿ⁺¹ → Eⁿ⁺¹` is differentiable on a rectangular box `[a, b] : set ℝⁿ⁺¹`, `a ≤ b`, with derivative `f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹` and the divergence `λ x, ∑ i, f' x eᵢ i` is integrable on `[a, b]`, where `eᵢ = pi.single i 1` is the `i`-th basis vector, then its integral is equal to the sum of integrals of `f` over the faces of `[a, b]`, taken with appropriat signs. Moreover, the same is true if the function is not differentiable but continuous at countably many points of `[a, b]`. We represent both faces `x i = a i` and `x i = b i` as the box `face i = [a ∘ fin.succ_above i, b ∘ fin.succ_above i]` in `ℝⁿ`, where `fin.succ_above : fin n ↪o fin (n + 1)` is the order embedding with range `{i}ᶜ`. The restrictions of `f : ℝⁿ⁺¹ → Eⁿ⁺¹` to these faces are given by `f ∘ back_face i` and `f ∘ front_face i`, where `back_face i = fin.insert_nth i (a i)` and `front_face i = fin.insert_nth i (b i)` are embeddings `ℝⁿ → ℝⁿ⁺¹` that take `y : ℝⁿ` and insert `a i` (resp., `b i`) as `i`-th coordinate. -/ lemma integral_divergence_of_has_fderiv_within_at_off_countable (hle : a ≤ b) (f : ℝⁿ⁺¹ → Eⁿ⁺¹) (f' : ℝⁿ⁺¹ → ℝⁿ⁺¹ →L[ℝ] Eⁿ⁺¹) (s : set ℝⁿ⁺¹) (hs : countable s) (Hc : ∀ x ∈ s, continuous_within_at f (Icc a b) x) (Hd : ∀ x ∈ Icc a b \ s, has_fderiv_within_at f (f' x) (Icc a b) x) (Hi : integrable_on (λ x, ∑ i, f' x (pi.single i 1) i) (Icc a b)) : ∫ x in Icc a b, ∑ i, f' x (e i) i = ∑ i : fin (n + 1), ((∫ x in face i, f (front_face i x) i) - ∫ x in face i, f (back_face i x) i) := begin simp only [volume_pi, ← set_integral_congr_set_ae measure.univ_pi_Ioc_ae_eq_Icc], by_cases heq : ∃ i, a i = b i, { rcases heq with ⟨i, hi⟩, have hi' : Ioc (a i) (b i) = ∅ := Ioc_eq_empty hi.not_lt, have : pi set.univ (λ j, Ioc (a j) (b j)) = ∅, from univ_pi_eq_empty hi', rw [this, integral_empty, sum_eq_zero], rintro j -, rcases eq_or_ne i j with rfl|hne, { simp [hi] }, { rcases fin.exists_succ_above_eq hne with ⟨i, rfl⟩, have : pi set.univ (λ k : fin n, Ioc (a $ j.succ_above k) (b $ j.succ_above k)) = ∅, from univ_pi_eq_empty hi', rw [this, integral_empty, integral_empty, sub_self] } }, { push_neg at heq, obtain ⟨I, rfl, rfl⟩ : ∃ I : box_integral.box (fin (n + 1)), I.lower = a ∧ I.upper = b, from ⟨⟨a, b, λ i, (hle i).lt_of_ne (heq i)⟩, rfl, rfl⟩, simp only [← box.coe_eq_pi, ← box.face_lower, ← box.face_upper], have A := ((Hi.mono_set box.coe_subset_Icc).has_box_integral ⊥ rfl), have B := has_integral_bot_divergence_of_forall_has_deriv_within_at I f f' s hs Hc Hd, have Hc : continuous_on f I.Icc, { intros x hx, by_cases hxs : x ∈ s, exacts [Hc x hxs, (Hd x ⟨hx, hxs⟩).continuous_within_at] }, rw continuous_on_pi at Hc, refine (A.unique B).trans (sum_congr rfl $ λ i hi, _), refine congr_arg2 has_sub.sub _ _, { have := box.continuous_on_face_Icc (Hc i) (set.right_mem_Icc.2 (hle i)), have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc, exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance }, { have := box.continuous_on_face_Icc (Hc i) (set.left_mem_Icc.2 (hle i)), have := (this.integrable_on_compact (box.is_compact_Icc _)).mono_set box.coe_subset_Icc, exact (this.has_box_integral ⊥ rfl).integral_eq, apply_instance } } end end end measure_theory
42b650e3c8a5ff30c1170e00bbfbcf9d9dcdc294
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/combinatorics/composition.lean
dc4890c924673b424ac87d7fdd5a14102d8f948d
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,332
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 data.fintype.card import tactic.omega /-! # Compositions A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into non-empty blocks of consecutive integers, where the `iⱼ` are the lengths of the blocks. This notion is closely related to that of a partition of `n`, but in a composition of `n` the order of the `iⱼ`s matters. We implement two different structures covering these two viewpoints on compositions. The first one, made of a list of positive integers summing to `n`, is the main one and is called `composition n`. The second one is useful for combinatorial arguments (for instance to show that the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}` containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost points of each block. The main API is built on `composition n`, and we provide an equivalence between the two types. ## Main functions * `c : composition n` is a structure, made of a list of integers which are all positive and add up to `n`. * `composition_card` states that the cardinality of `composition n` is exactly `2^(n-1)`, which is proved by constructing an equiv with `composition_as_set n` (see below), which is itself in bijection with the subsets of `fin (n-1)` (this holds even for `n = 0`, where `-` is nat subtraction). Let `c : composition n` be a composition of `n`. Then * `c.blocks` is the list of blocks in `c`. * `c.length` is the number of blocks in the composition. * `c.blocks_fun : fin c.length → ℕ` is the realization of `c.blocks` as a function on `fin c.length`. This is the main object when using compositions to understand the composition of analytic functions. * `c.size_up_to : ℕ → ℕ` is the sum of the size of the blocks up to `i`.; * `c.embedding i : fin (c.blocks_fun i) → fin n` is the increasing embedding of the `i`-th block in `fin n`; * `c.index j`, for `j : fin n`, is the index of the block containing `j`. Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition of `n`. * `l.split_wrt_composition c` is a list of lists, made of the slices of `l` corresponding to the blocks of `c`. * `join_split_wrt_composition` states that splitting a list and then joining it gives back the original list. * `split_wrt_composition_join` states that joining a list of lists, and then splitting it back according to the right composition, gives back the original list of lists. We turn to the second viewpoint on compositions, that we realize as a finset of `fin (n+1)`. `c : composition_as_set n` is a structure made of a finset of `fin (n+1)` called `c.boundaries` and proofs that it contains `0` and `n`. (Taking a finset of `fin n` containing `0` would not make sense in the edge case `n = 0`, while the previous description works in all cases). The elements of this set (other than `n`) correspond to leftmost points of blocks. Thus, there is an equiv between `composition n` and `composition_as_set n`. We only construct basic API on `composition_as_set` (notably `c.length` and `c.blocks`) to be able to construct this equiv, called `composition_equiv n`. Since there is a straightforward equiv between `composition_as_set n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n` from a `composition_as_set` and called `composition_as_set_equiv n`), we deduce that `composition_as_set n` and `composition n` are both fintypes of cardinality `2^(n - 1)` (see `composition_as_set_card` and `composition_card`). ## Implementation details The main motivation for this structure and its API is in the construction of the composition of formal multilinear series, and the proof that the composition of analytic functions is analytic. The representation of a composition as a list is very handy as lists are very flexible and already have a well-developed API. ## Tags Composition, partition ## References <https://en.wikipedia.org/wiki/Composition_(combinatorics)> -/ open list open_locale classical variable {n : ℕ} /-- A composition of `n` is a list of positive integers summing to `n`. -/ @[ext] structure composition (n : ℕ) := (blocks : list ℕ) (blocks_pos : ∀ {i}, i ∈ blocks → 0 < i) (blocks_sum : blocks.sum = n) /-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure `composition_as_set n`. -/ @[ext] structure composition_as_set (n : ℕ) := (boundaries : finset (fin n.succ)) (zero_mem : (0 : fin n.succ) ∈ boundaries) (last_mem : (fin.last n ∈ boundaries)) instance {n : ℕ} : inhabited (composition_as_set n) := ⟨⟨finset.univ, finset.mem_univ _, finset.mem_univ _⟩⟩ /-! ### Compositions A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. -/ namespace composition variables (c : composition n) instance (n : ℕ) : has_to_string (composition n) := ⟨λ c, to_string c.blocks⟩ /-- The length of a composition, i.e., the number of blocks in the composition. -/ @[reducible] def length : ℕ := c.blocks.length lemma blocks_length : c.blocks.length = c.length := rfl /-- The blocks of a composition, seen as a function on `fin c.length`. When composing analytic functions using compositions, this is the main player. -/ def blocks_fun : fin c.length → ℕ := λ i, nth_le c.blocks i.1 i.2 lemma of_fn_blocks_fun : of_fn c.blocks_fun = c.blocks := of_fn_nth_le _ lemma sum_blocks_fun : finset.univ.sum c.blocks_fun = n := by conv_rhs { rw [← c.blocks_sum, ← of_fn_blocks_fun, sum_of_fn] } @[simp] lemma one_le_blocks {i : ℕ} (h : i ∈ c.blocks) : 1 ≤ i := c.blocks_pos h @[simp] lemma one_le_blocks' {i : ℕ} (h : i < c.length) : 1 ≤ nth_le c.blocks i h:= c.one_le_blocks (nth_le_mem (blocks c) i h) @[simp] lemma blocks_pos' (i : ℕ) (h : i < c.length) : 0 < nth_le c.blocks i h:= c.one_le_blocks' h lemma length_le : c.length ≤ n := begin conv_rhs { rw ← c.blocks_sum }, exact length_le_sum_of_one_le _ (λ i hi, c.one_le_blocks hi) end lemma length_pos_of_pos (h : 0 < n) : 0 < c.length := begin apply length_pos_of_sum_pos, convert h, exact c.blocks_sum end /-- The sum of the sizes of the blocks in a composition up to `i`. -/ def size_up_to (i : ℕ) : ℕ := (c.blocks.take i).sum @[simp] lemma size_up_to_zero : c.size_up_to 0 = 0 := by simp [size_up_to] lemma size_up_to_of_length_le (i : ℕ) (h : c.length ≤ i) : c.size_up_to i = n := begin dsimp [size_up_to], convert c.blocks_sum, exact take_all_of_le h end @[simp] lemma size_up_to_length : c.size_up_to c.length = n := c.size_up_to_of_length_le c.length (le_refl _) lemma size_up_to_le (i : ℕ) : c.size_up_to i ≤ n := begin conv_rhs { rw [← c.blocks_sum, ← sum_take_add_sum_drop _ i] }, exact nat.le_add_right _ _ end lemma size_up_to_succ {i : ℕ} (h : i < c.length) : c.size_up_to (i+1) = c.size_up_to i + c.blocks.nth_le i h := by { simp only [size_up_to], rw sum_take_succ _ _ h } lemma size_up_to_succ' (i : fin c.length) : c.size_up_to ((i : ℕ) + 1) = c.size_up_to i + c.blocks_fun i := c.size_up_to_succ i.2 lemma size_up_to_strict_mono {i : ℕ} (h : i < c.length) : c.size_up_to i < c.size_up_to (i+1) := by { rw c.size_up_to_succ h, simp } lemma monotone_size_up_to : monotone c.size_up_to := monotone_sum_take _ /-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundary : fin (c.length + 1) → fin (n+1) := λ i, ⟨c.size_up_to i, nat.lt_succ_of_le (c.size_up_to_le i)⟩ @[simp] lemma boundary_zero : c.boundary 0 = 0 := by simp [boundary, fin.ext_iff] @[simp] lemma boundary_last : c.boundary (fin.last c.length) = fin.last n := by simp [boundary, fin.ext_iff] lemma strict_mono_boundary : strict_mono c.boundary := begin apply fin.strict_mono_iff_lt_succ.2 (λ i hi, _), exact c.size_up_to_strict_mono ((add_lt_add_iff_right 1).mp hi) end /-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundaries : finset (fin (n+1)) := finset.univ.image c.boundary lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := begin dsimp [boundaries], rw finset.card_image_of_injective finset.univ c.strict_mono_boundary.injective, simp end /-- To `c : composition n`, one can associate a `composition_as_set n` by registering the leftmost point of each block, and adding a virtual point at the right of the last block. -/ def to_composition_as_set : composition_as_set n := { boundaries := c.boundaries, zero_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_image], exact ⟨0, rfl⟩, end, last_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_image], exact ⟨fin.last c.length, c.boundary_last⟩, end } /-- The canonical increasing bijection between `fin (c.length + 1)` and `c.boundaries` is exactly `c.boundary`. -/ lemma mono_of_fin_boundaries : c.boundary = finset.mono_of_fin c.boundaries c.card_boundaries_eq_succ_length := begin apply finset.mono_of_fin_unique' _ _ c.strict_mono_boundary, assume i hi, simp [boundaries, - set.mem_range, set.mem_range_self] end /-- Embedding the `i`-th block of a composition (identified with `fin (c.blocks_fun i)`) into `fin n` at the relevant position. -/ def embedding (i : fin c.length) : fin (c.blocks_fun i) → fin n := λ j, ⟨c.size_up_to i.1 + j.val, calc c.size_up_to i.1 + j.val < c.size_up_to i.1 + c.blocks.nth_le i.1 i.2 : add_lt_add_left j.2 _ ... = c.size_up_to (i.1 + 1) : (c.size_up_to_succ _).symm ... ≤ n : by { conv_rhs { rw ← c.size_up_to_length }, exact monotone_sum_take _ i.2 } ⟩ lemma embedding_inj (i : fin c.length) : function.injective (c.embedding i) := λ a b hab, by simpa [embedding, fin.ext_iff] using hab /-- `index_exists` asserts there is some `i` so `j < c.size_up_to (i+1)`. In the next definition we use `nat.find` to produce the minimal such index. -/ lemma index_exists {j : ℕ} (h : j < n) : ∃ i : ℕ, j < c.size_up_to i.succ ∧ i < c.length := begin have n_pos : 0 < n := lt_of_le_of_lt (zero_le j) h, have : 0 < c.blocks.sum, by rwa [← c.blocks_sum] at n_pos, have length_pos : 0 < c.blocks.length := length_pos_of_sum_pos (blocks c) this, refine ⟨c.length.pred, _, nat.pred_lt (ne_of_gt length_pos)⟩, have : c.length.pred.succ = c.length := nat.succ_pred_eq_of_pos length_pos, simp [this, h] end /-- `c.index j` is the index of the block in the composition `c` containing `j`. -/ def index (j : fin n) : fin c.length := ⟨nat.find (c.index_exists j.2), (nat.find_spec (c.index_exists j.2)).2⟩ lemma lt_size_up_to_index_succ (j : fin n) : j.val < c.size_up_to (c.index j).succ := (nat.find_spec (c.index_exists j.2)).1 lemma size_up_to_index_le (j : fin n) : c.size_up_to (c.index j) ≤ j := begin by_contradiction H, set i := c.index j with hi, push_neg at H, have i_pos : (0 : ℕ) < i, { by_contradiction i_pos, push_neg at i_pos, simp [le_zero_iff_eq.mp i_pos, c.size_up_to_zero] at H, exact nat.not_succ_le_zero j H }, let i₁ := (i : ℕ).pred, have i₁_lt_i : i₁ < i := nat.pred_lt (ne_of_gt i_pos), have i₁_succ : i₁.succ = i := nat.succ_pred_eq_of_pos i_pos, have := nat.find_min (c.index_exists j.2) i₁_lt_i, simp [lt_trans i₁_lt_i (c.index j).2, i₁_succ] at this, exact nat.lt_le_antisymm H this end /-- Mapping an element `j` of `fin n` to the element in the block containing it, identified with `fin (c.blocks_fun (c.index j))` through the canonical increasing bijection. -/ def inv_embedding (j : fin n) : fin (c.blocks_fun (c.index j)) := ⟨j - c.size_up_to (c.index j), begin rw [nat.sub_lt_right_iff_lt_add, add_comm, ← size_up_to_succ'], { exact lt_size_up_to_index_succ _ _ }, { exact size_up_to_index_le _ _ } end⟩ lemma embedding_comp_inv (j : fin n) : c.embedding (c.index j) (c.inv_embedding j) = j := begin rw fin.ext_iff, apply nat.add_sub_cancel' (c.size_up_to_index_le j), end lemma mem_range_embedding_iff {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ c.size_up_to i ≤ j ∧ (j : ℕ) < c.size_up_to (i : ℕ).succ := begin split, { assume h, rcases set.mem_range.2 h with ⟨k, hk⟩, rw fin.ext_iff at hk, change c.size_up_to i + k.val = (j : ℕ) at hk, rw ← hk, simp [size_up_to_succ', k.2] }, { assume h, apply set.mem_range.2, refine ⟨⟨j.val - c.size_up_to i, _⟩, _⟩, { rw [nat.sub_lt_left_iff_lt_add, ← size_up_to_succ'], { exact h.2 }, { exact h.1 } }, { rw fin.ext_iff, exact nat.add_sub_cancel' h.1 } } end /-- The embeddings of different blocks of a composition are disjoint. -/ lemma disjoint_range {i₁ i₂ : fin c.length} (h : i₁ ≠ i₂) : disjoint (set.range (c.embedding i₁)) (set.range (c.embedding i₂)) := begin classical, wlog h' : i₁ ≤ i₂ using i₁ i₂, by_contradiction d, obtain ⟨x, hx₁, hx₂⟩ : ∃ x : fin n, (x ∈ set.range (c.embedding i₁) ∧ x ∈ set.range (c.embedding i₂)) := set.not_disjoint_iff.1 d, have : i₁ < i₂ := lt_of_le_of_ne h' h, have A : (i₁ : ℕ).succ ≤ i₂ := nat.succ_le_of_lt this, apply lt_irrefl (x : ℕ), calc (x : ℕ) < c.size_up_to (i₁ : ℕ).succ : (c.mem_range_embedding_iff.1 hx₁).2 ... ≤ c.size_up_to (i₂ : ℕ) : monotone_sum_take _ A ... ≤ x : (c.mem_range_embedding_iff.1 hx₂).1 end lemma mem_range_embedding (j : fin n) : j ∈ set.range (c.embedding (c.index j)) := begin have : c.embedding (c.index j) (c.inv_embedding j) ∈ set.range (c.embedding (c.index j)) := set.mem_range_self _, rwa c.embedding_comp_inv j at this end lemma mem_range_embedding_iff' {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ i = c.index j := begin split, { rw ← not_imp_not, assume h, exact set.disjoint_right.1 (c.disjoint_range h) (c.mem_range_embedding j) }, { assume h, rw h, exact c.mem_range_embedding j } end lemma index_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) : c.index (c.embedding i j) = i := begin symmetry, rw ← mem_range_embedding_iff', apply set.mem_range_self end lemma inv_embedding_comp (i : fin c.length) (j : fin (c.blocks_fun i)) : (c.inv_embedding (c.embedding i j)).val = j.val := begin simp only [inv_embedding, index_embedding], simp [embedding, fin.coe_eq_val, index_embedding] end /-- Equivalence between the disjoint union of the blocks (each of them seen as `fin (c.blocks_fun i)`) with `fin n`. -/ def blocks_fin_equiv : (Σ i : fin c.length, fin (c.blocks_fun i)) ≃ fin n := { to_fun := λ x, c.embedding x.1 x.2, inv_fun := λ j, ⟨c.index j, c.inv_embedding j⟩, left_inv := λ x, begin rcases x with ⟨i, y⟩, dsimp, congr, { exact c.index_embedding _ _ }, rw fin.heq_ext_iff, { exact c.inv_embedding_comp _ _ }, { rw c.index_embedding } end, right_inv := λ j, c.embedding_comp_inv j } lemma blocks_fun_congr {n₁ n₂ : ℕ} (c₁ : composition n₁) (c₂ : composition n₂) (i₁ : fin c₁.length) (i₂ : fin c₂.length) (hn : n₁ = n₂) (hc : c₁.blocks = c₂.blocks) (hi : (i₁ : ℕ) = i₂) : c₁.blocks_fun i₁ = c₂.blocks_fun i₂ := by { cases hn, rw ← composition.ext_iff at hc, cases hc, congr, rwa fin.ext_iff } /-- Two compositions (possibly of different integers) coincide if and only if they have the same sequence of blocks. -/ lemma sigma_eq_iff_blocks_eq {c : Σ n, composition n} {c' : Σ n, composition n} : c = c' ↔ c.2.blocks = c'.2.blocks := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases c with ⟨n, c⟩, rcases c' with ⟨n', c'⟩, have : n = n', by { rw [← c.blocks_sum, ← c'.blocks_sum, H] }, induction this, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext1, exact H end /-- The composition made of blocks all of size `1`. -/ def ones (n : ℕ) : composition n := ⟨repeat (1 : ℕ) n, λ i hi, by simp [list.eq_of_mem_repeat hi], by simp⟩ instance {n : ℕ} : inhabited (composition n) := ⟨composition.ones n⟩ @[simp] lemma ones_length (n : ℕ) : (ones n).length = n := list.length_repeat 1 n @[simp] lemma ones_blocks (n : ℕ) : (ones n).blocks = repeat (1 : ℕ) n := by simp only [blocks, ones, map_repeat] @[simp] lemma ones_blocks_fun (n : ℕ) (i : fin (ones n).length) : (ones n).blocks_fun i = 1 := by simp [blocks_fun, ones, blocks, i.2] @[simp] lemma ones_size_up_to (n : ℕ) (i : ℕ) : (ones n).size_up_to i = min i n := by simp [size_up_to, ones_blocks, take_repeat] @[simp] lemma ones_embedding (i : fin (ones n).length) (h : 0 < (ones n).blocks_fun i) : (ones n).embedding i ⟨0, h⟩ = ⟨i.1, lt_of_lt_of_le i.2 (ones n).length_le⟩ := begin have : i.val < n, by { convert i.2, exact (ones_length n).symm }, simp [embedding, le_of_lt this] end lemma eq_ones_iff {c : composition n} : c = ones n ↔ ∀ i ∈ c.blocks, i = 1 := begin split, { assume H, rw [H, ones_blocks], exact λ i, eq_of_mem_repeat }, { assume H, ext1, have A : c.blocks = repeat 1 c.blocks.length := eq_repeat_of_mem H, have : c.blocks.length = n, by { conv_rhs { rw [← c.blocks_sum, A] }, simp }, rw [A, this, ones_blocks] }, end lemma ne_ones_iff {c : composition n} : c ≠ ones n ↔ ∃ i ∈ c.blocks, 1 < i := begin rw ← not_iff_not, push_neg, rw eq_ones_iff, have : ∀ j ∈ c.blocks, j = 1 ↔ j ≤ 1 := λ j hj, by simp [le_antisymm_iff, c.one_le_blocks hj], simp [this] {contextual := tt} end /-- The composition made of a single block of size `n`. -/ def single (n : ℕ) (h : 0 < n) : composition n := ⟨[n], by simp [h], by simp⟩ @[simp] lemma single_length {n : ℕ} (h : 0 < n) : (single n h).length = 1 := by simp [single, length] @[simp] lemma single_blocks {n : ℕ} (h : 0 < n) : (single n h).blocks = [n] := by simp [blocks, single] @[simp] lemma single_blocks_fun {n : ℕ} (h : 0 < n) (i : fin (single n h).length) : (single n h).blocks_fun i = n := by simp [blocks_fun, single, blocks, i.2] @[simp] lemma single_embedding {n : ℕ} (h : 0 < n) (i : fin n) : (single n h).embedding ⟨0, single_length h ▸ zero_lt_one⟩ i = i := by simp [embedding] lemma eq_single_iff {n : ℕ} {h : 0 < n} {c : composition n } : c = single n h ↔ c.length = 1 := begin split, { assume H, rw H, exact single_length h }, { assume H, ext1, have A : c.blocks.length = 1 := H ▸ c.blocks_length, have B : c.blocks.sum = n := c.blocks_sum, rw eq_cons_of_length_one A at B ⊢, simpa [single_blocks] using B } end end composition /-! ### Splitting a list Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists of respective lengths `c.blocks_fun 0`, ..., `c.blocks_fun (c.length-1)`. This is inverse to the join operation. -/ namespace list variable {α : Type*} /-- Auxiliary for `list.split_wrt_composition`. -/ def split_wrt_composition_aux : list α → list ℕ → list (list α) | l [] := [] | l (n :: ns) := let (l₁, l₂) := l.split_at n in l₁ :: split_wrt_composition_aux l₂ ns /-- Given a list of length `n` and a composition `[i₁, ..., iₖ]` of `n`, split `l` into a list of `k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iₖ`. This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/ def split_wrt_composition (l : list α) (c : composition n) : list (list α) := split_wrt_composition_aux l c.blocks local attribute [simp] split_wrt_composition_aux.equations._eqn_1 local attribute [simp] lemma split_wrt_composition_aux_cons (l : list α) (n ns) : l.split_wrt_composition_aux (n :: ns) = take n l :: (drop n l).split_wrt_composition_aux ns := by simp [split_wrt_composition_aux] lemma length_split_wrt_composition_aux (l : list α) (ns) : length (l.split_wrt_composition_aux ns) = ns.length := by induction ns generalizing l; simp * /-- When one splits a list along a composition `c`, the number of sublists thus created is `c.length`. -/ @[simp] lemma length_split_wrt_composition (l : list α) (c : composition n) : length (l.split_wrt_composition c) = c.length := length_split_wrt_composition_aux _ _ lemma map_length_split_wrt_composition_aux {ns : list ℕ} : ∀ {l : list α}, ns.sum ≤ l.length → map length (l.split_wrt_composition_aux ns) = ns := begin induction ns with n ns IH; intros l h; simp at h ⊢, have := le_trans (nat.le_add_right _ _) h, rw IH, {simp [this]}, rwa [length_drop, nat.le_sub_left_iff_add_le this] end /-- When one splits a list along a composition `c`, the lengths of the sublists thus created are given by the block sizes in `c`. -/ lemma map_length_split_wrt_composition (l : list α) (c : composition l.length) : map length (l.split_wrt_composition c) = c.blocks := map_length_split_wrt_composition_aux (le_of_eq c.blocks_sum) lemma length_pos_of_mem_split_wrt_composition {l l' : list α} {c : composition l.length} (h : l' ∈ l.split_wrt_composition c) : 0 < length l' := begin have : l'.length ∈ (l.split_wrt_composition c).map list.length := list.mem_map_of_mem list.length h, rw map_length_split_wrt_composition at this, exact c.blocks_pos this end lemma sum_take_map_length_split_wrt_composition (l : list α) (c : composition l.length) (i : ℕ) : (((l.split_wrt_composition c).map length).take i).sum = c.size_up_to i := by { congr, exact map_length_split_wrt_composition l c } lemma nth_le_split_wrt_composition_aux (l : list α) (ns : list ℕ) {i : ℕ} (hi) : nth_le (l.split_wrt_composition_aux ns) i hi = (l.take (ns.take (i+1)).sum).drop (ns.take i).sum := begin induction ns with n ns IH generalizing l i, {cases hi}, cases i; simp [IH], rw [add_comm n, drop_add, drop_take], end /-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l` between the indices `c.size_up_to i` and `c.size_up_to (i+1)`, i.e., the indices in the `i`-th block of the composition. -/ lemma nth_le_split_wrt_composition (l : list α) (c : composition n) {i : ℕ} (hi : i < (l.split_wrt_composition c).length) : nth_le (l.split_wrt_composition c) i hi = (l.take (c.size_up_to (i+1))).drop (c.size_up_to i) := nth_le_split_wrt_composition_aux _ _ _ theorem join_split_wrt_composition_aux {ns : list ℕ} : ∀ {l : list α}, ns.sum = l.length → (l.split_wrt_composition_aux ns).join = l := begin induction ns with n ns IH; intros l h; simp at h ⊢, { exact (length_eq_zero.1 h.symm).symm }, rw IH, {simp}, rwa [length_drop, ← h, nat.add_sub_cancel_left] end /-- If one splits a list along a composition, and then joins the sublists, one gets back the original list. -/ @[simp] theorem join_split_wrt_composition (l : list α) (c : composition l.length) : (l.split_wrt_composition c).join = l := join_split_wrt_composition_aux c.blocks_sum /-- If one joins a list of lists and then splits the join along the right composition, one gets back the original list of lists. -/ @[simp] theorem split_wrt_composition_join (L : list (list α)) (c : composition L.join.length) (h : map length L = c.blocks) : split_wrt_composition (join L) c = L := by simp only [eq_self_iff_true, and_self, eq_iff_join_eq, join_split_wrt_composition, map_length_split_wrt_composition, h] end list /-! ### Compositions as sets Combinatorial viewpoints on compositions, seen as finite subsets of `fin (n+1)` containing `0` and `n`, where the points of the set (other than `n`) correspond to the leftmost points of each block. -/ /-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/ def composition_as_set_equiv (n : ℕ) : composition_as_set n ≃ finset (fin (n - 1)) := { to_fun := λ c, {i : fin (n-1) | (⟨1 + i.val, by { have := i.2, omega }⟩ : fin n.succ) ∈ c.boundaries}.to_finset, inv_fun := λ s, { boundaries := {i : fin n.succ | (i = 0) ∨ (i = fin.last n) ∨ (∃ (j : fin (n-1)) (hj : j ∈ s), i.val = j.val + 1)}.to_finset, zero_mem := by simp, last_mem := by simp }, left_inv := begin assume c, ext i, simp only [exists_prop, add_comm, set.mem_to_finset, true_or, or_true, set.mem_set_of_eq, fin.last_val], split, { rintro (rfl | rfl | ⟨j, hj1, hj2⟩), { exact c.zero_mem }, { exact c.last_mem }, { convert hj1, rwa fin.ext_iff } }, { simp only [classical.or_iff_not_imp_left], assume i_mem i_ne_zero i_ne_last, simp [fin.ext_iff] at i_ne_zero i_ne_last, refine ⟨⟨i.val - 1, _⟩, _, _⟩, { have : i.val < n + 1 := i.2, omega }, { convert i_mem, rw fin.ext_iff, simp, omega }, { simp, omega } }, end, right_inv := begin assume s, ext i, have : 1 + i.val ≠ n, by { apply ne_of_lt, have := i.2, omega }, simp only [fin.ext_iff, this, exists_prop, fin.val_zero, false_or, add_left_inj, add_comm, set.mem_to_finset, true_or, add_eq_zero_iff, or_true, one_ne_zero, set.mem_set_of_eq, fin.last_val, false_and], split, { rintros ⟨j, js, hj⟩, convert js, exact (fin.ext_iff _ _).2 hj }, { assume h, exact ⟨i, h, rfl⟩ } end } instance composition_as_set_fintype (n : ℕ) : fintype (composition_as_set n) := fintype.of_equiv _ (composition_as_set_equiv n).symm lemma composition_as_set_card (n : ℕ) : fintype.card (composition_as_set n) = 2 ^ (n - 1) := begin have : fintype.card (finset (fin (n-1))) = 2 ^ (n - 1), by simp, rw ← this, exact fintype.card_congr (composition_as_set_equiv n) end namespace composition_as_set variables (c : composition_as_set n) lemma boundaries_nonempty : c.boundaries.nonempty := ⟨0, c.zero_mem⟩ lemma card_boundaries_pos : 0 < finset.card c.boundaries := finset.card_pos.mpr c.boundaries_nonempty /-- Number of blocks in a `composition_as_set`. -/ def length : ℕ := finset.card c.boundaries - 1 lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := (nat.sub_eq_iff_eq_add c.card_boundaries_pos).mp rfl lemma length_lt_card_boundaries : c.length < c.boundaries.card := by { rw c.card_boundaries_eq_succ_length, exact lt_add_one _ } lemma lt_length (i : fin c.length) : i.val + 1 < c.boundaries.card := nat.add_lt_of_lt_sub_right i.2 lemma lt_length' (i : fin c.length) : i.val < c.boundaries.card := lt_of_le_of_lt (nat.le_succ i.val) (c.lt_length i) /-- Canonical increasing bijection from `fin c.boundaries.card` to `c.boundaries`. -/ def boundary : fin c.boundaries.card → fin (n+1) := finset.mono_of_fin c.boundaries rfl @[simp] lemma boundary_zero : c.boundary ⟨0, c.card_boundaries_pos⟩ = 0 := begin rw [boundary, finset.mono_of_fin_zero rfl c.boundaries_nonempty c.card_boundaries_pos], exact le_antisymm (finset.min'_le _ _ _ c.zero_mem) (fin.zero_le _), end @[simp] lemma boundary_length : c.boundary ⟨c.length, c.length_lt_card_boundaries⟩ = fin.last n := begin convert finset.mono_of_fin_last rfl c.boundaries_nonempty c.card_boundaries_pos, exact le_antisymm (finset.le_max' _ _ _ c.last_mem) (fin.le_last _) end /-- Size of the `i`-th block in a `composition_as_set`, seen as a function on `fin c.length`. -/ def blocks_fun (i : fin c.length) : ℕ := (c.boundary ⟨i.val + 1, c.lt_length i⟩).val - (c.boundary ⟨i.val, c.lt_length' i⟩).val lemma blocks_fun_pos (i : fin c.length) : 0 < c.blocks_fun i := begin have : (⟨i.val, c.lt_length' i⟩ : fin c.boundaries.card) < ⟨i.val + 1, c.lt_length i⟩ := nat.lt_succ_self _, exact nat.lt_sub_left_of_add_lt (finset.mono_of_fin_strict_mono c.boundaries rfl this) end /-- List of the sizes of the blocks in a `composition_as_set`. -/ def blocks (c : composition_as_set n) : list ℕ := of_fn c.blocks_fun @[simp] lemma blocks_length : c.blocks.length = c.length := length_of_fn _ lemma blocks_partial_sum {i : ℕ} (h : i < c.boundaries.card) : (c.blocks.take i).sum = c.boundary ⟨i, h⟩ := begin induction i with i IH, { simp }, have A : i < c.blocks.length, { rw c.card_boundaries_eq_succ_length at h, simp [blocks, nat.lt_of_succ_lt_succ h] }, have B : i < c.boundaries.card := lt_of_lt_of_le A (by simp [blocks, length, nat.sub_le]), rw [sum_take_succ _ _ A, IH B], simp only [blocks, blocks_fun, fin.coe_eq_val, nth_le_of_fn'], rw nat.add_sub_cancel', refine le_of_lt (@finset.mono_of_fin_strict_mono _ _ c.boundaries _ rfl (⟨i, B⟩ : fin c.boundaries.card) _ _), exact nat.lt_succ_self _ end lemma mem_boundaries_iff_exists_blocks_sum_take_eq {j : fin (n+1)} : j ∈ c.boundaries ↔ ∃ i < c.boundaries.card, (c.blocks.take i).sum = j.val := begin split, { assume hj, rcases (c.boundaries.mono_of_fin_bij_on rfl).surj_on hj with ⟨i, _, hi⟩, refine ⟨i.1, i.2, _⟩, rw [← hi, c.blocks_partial_sum i.2], refl }, { rintros ⟨i, hi, H⟩, convert (c.boundaries.mono_of_fin_bij_on rfl).maps_to (set.mem_univ ⟨i, hi⟩), have : c.boundary ⟨i, hi⟩ = j, by rwa [fin.ext_iff, ← fin.coe_eq_val, ← c.blocks_partial_sum hi], exact this.symm } end lemma blocks_sum : c.blocks.sum = n := begin have : c.blocks.take c.length = c.blocks := take_all_of_le (by simp [blocks]), rw [← this, c.blocks_partial_sum c.length_lt_card_boundaries, c.boundary_length], refl end /-- Associating a `composition n` to a `composition_as_set n`, by registering the sizes of the blocks as a list of positive integers. -/ def to_composition : composition n := { blocks := c.blocks, blocks_pos := by simp only [blocks, forall_mem_of_fn_iff, blocks_fun_pos c, forall_true_iff], blocks_sum := c.blocks_sum } end composition_as_set /-! ### Equivalence between compositions and compositions as sets In this section, we explain how to go back and forth between a `composition` and a `composition_as_set`, by showing that their `blocks` and `length` and `boundaries` correspond to each other, and construct an equivalence between them called `composition_equiv`. -/ @[simp] lemma composition.to_composition_as_set_length (c : composition n) : c.to_composition_as_set.length = c.length := by simp [composition.to_composition_as_set, composition_as_set.length, c.card_boundaries_eq_succ_length] @[simp] lemma composition_as_set.to_composition_length (c : composition_as_set n) : c.to_composition.length = c.length := by simp [composition_as_set.to_composition, composition.length, composition.blocks] @[simp] lemma composition.to_composition_as_set_blocks (c : composition n) : c.to_composition_as_set.blocks = c.blocks := begin let d := c.to_composition_as_set, change d.blocks = c.blocks, have length_eq : d.blocks.length = c.blocks.length, { convert c.to_composition_as_set_length, simp [composition_as_set.blocks] }, suffices H : ∀ (i ≤ d.blocks.length), (d.blocks.take i).sum = (c.blocks.take i).sum, from eq_of_sum_take_eq length_eq H, assume i hi, have i_lt : i < d.boundaries.card, { convert nat.lt_succ_iff.2 hi, convert d.card_boundaries_eq_succ_length, exact length_of_fn _ }, have i_lt' : i < c.boundaries.card := i_lt, have i_lt'' : i < c.length + 1, by rwa c.card_boundaries_eq_succ_length at i_lt', have A : finset.mono_of_fin d.boundaries rfl ⟨i, i_lt⟩ = finset.mono_of_fin c.boundaries rfl ⟨i, i_lt'⟩ := rfl, have B : c.size_up_to i = c.boundary ⟨i, i_lt''⟩ := rfl, rw [d.blocks_partial_sum i_lt, composition_as_set.boundary, A, ← composition.size_up_to, B, fin.coe_eq_val, fin.coe_eq_val, ← fin.ext_iff, c.mono_of_fin_boundaries, finset.mono_of_fin_eq_mono_of_fin_iff] end @[simp] lemma composition_as_set.to_composition_blocks (c : composition_as_set n) : c.to_composition.blocks = c.blocks := rfl @[simp] lemma composition_as_set.to_composition_boundaries (c : composition_as_set n) : c.to_composition.boundaries = c.boundaries := begin ext j, simp [c.mem_boundaries_iff_exists_blocks_sum_take_eq, c.card_boundaries_eq_succ_length, composition.boundary, fin.ext_iff, composition.size_up_to, exists_prop, finset.mem_univ, take, exists_prop_of_true, finset.mem_image, composition_as_set.to_composition_blocks, composition.boundaries], split, { rintros ⟨i, hi⟩, refine ⟨i.1, _, hi⟩, convert i.2, simp }, { rintros ⟨i, i_lt, hi⟩, have : i < c.to_composition.length + 1, by simpa using i_lt, exact ⟨⟨i, this⟩, hi⟩ } end @[simp] lemma composition.to_composition_as_set_boundaries (c : composition n) : c.to_composition_as_set.boundaries = c.boundaries := rfl /-- Equivalence between `composition n` and `composition_as_set n`. -/ def composition_equiv (n : ℕ) : composition n ≃ composition_as_set n := { to_fun := λ c, c.to_composition_as_set, inv_fun := λ c, c.to_composition, left_inv := λ c, by { ext1, exact c.to_composition_as_set_blocks }, right_inv := λ c, by { ext1, exact c.to_composition_boundaries } } instance composition_fintype (n : ℕ) : fintype (composition n) := fintype.of_equiv _ (composition_equiv n).symm lemma composition_card (n : ℕ) : fintype.card (composition n) = 2 ^ (n - 1) := begin rw ← composition_as_set_card n, exact fintype.card_congr (composition_equiv n) end
5c1a86822017862cbaa192e979d55103aa8053e7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/artinian.lean
4ca5581b773754f92fe842c20487e30673d47608
[ "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
18,978
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import ring_theory.nakayama import data.set_like.fintype /-! # Artinian rings and modules A module satisfying these equivalent conditions is said to be an *Artinian* R-module if every decreasing chain of submodules is eventually constant, or equivalently, if the relation `<` on submodules is well founded. A ring is said to be left (or right) Artinian if it is Artinian as a left (or right) module over itself, or simply Artinian if it is both left and right Artinian. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `is_artinian R M` is the proposition that `M` is a Artinian `R`-module. It is a class, implemented as the predicate that the `<` relation on submodules is well founded. * `is_artinian_ring R` is the proposition that `R` is a left Artinian ring. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Artinian, artinian, Artinian ring, Artinian module, artinian ring, artinian module -/ open set open_locale big_operators pointwise /-- `is_artinian R M` is the proposition that `M` is an Artinian `R`-module, implemented as the well-foundedness of submodule inclusion. -/ class is_artinian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (well_founded_submodule_lt [] : well_founded ((<) : submodule R M → submodule R M → Prop)) section variables {R M P N : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] [add_comm_group N] variables [module R M] [module R P] [module R N] open is_artinian include R theorem is_artinian_of_injective (f : M →ₗ[R] P) (h : function.injective f) [is_artinian R P] : is_artinian R M := ⟨subrelation.wf (λ A B hAB, show A.map f < B.map f, from submodule.map_strict_mono_of_injective h hAB) (inv_image.wf (submodule.map f) (is_artinian.well_founded_submodule_lt R P))⟩ instance is_artinian_submodule' [is_artinian R M] (N : submodule R M) : is_artinian R N := is_artinian_of_injective N.subtype subtype.val_injective lemma is_artinian_of_le {s t : submodule R M} [ht : is_artinian R t] (h : s ≤ t) : is_artinian R s := is_artinian_of_injective (submodule.of_le h) (submodule.of_le_injective h) variable (M) theorem is_artinian_of_surjective (f : M →ₗ[R] P) (hf : function.surjective f) [is_artinian R M] : is_artinian R P := ⟨subrelation.wf (λ A B hAB, show A.comap f < B.comap f, from submodule.comap_strict_mono_of_surjective hf hAB) (inv_image.wf (submodule.comap f) (is_artinian.well_founded_submodule_lt _ _))⟩ variable {M} theorem is_artinian_of_linear_equiv (f : M ≃ₗ[R] P) [is_artinian R M] : is_artinian R P := is_artinian_of_surjective _ f.to_linear_map f.to_equiv.surjective theorem is_artinian_of_range_eq_ker [is_artinian R M] [is_artinian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf : function.injective f) (hg : function.surjective g) (h : f.range = g.ker) : is_artinian R N := ⟨well_founded_lt_exact_sequence (is_artinian.well_founded_submodule_lt _ _) (is_artinian.well_founded_submodule_lt _ _) f.range (submodule.map f) (submodule.comap f) (submodule.comap g) (submodule.map g) (submodule.gci_map_comap hf) (submodule.gi_map_comap hg) (by simp [submodule.map_comap_eq, inf_comm]) (by simp [submodule.comap_map_eq, h])⟩ instance is_artinian_prod [is_artinian R M] [is_artinian R P] : is_artinian R (M × P) := is_artinian_of_range_eq_ker (linear_map.inl R M P) (linear_map.snd R M P) linear_map.inl_injective linear_map.snd_surjective (linear_map.range_inl R M P) @[priority 100] instance is_artinian_of_finite [finite M] : is_artinian R M := ⟨finite.well_founded_of_trans_of_irrefl _⟩ local attribute [elab_as_eliminator] finite.induction_empty_option instance is_artinian_pi {R ι : Type*} [finite ι] : Π {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)], by exactI Π [Π i, module R (M i)], by exactI Π [∀ i, is_artinian R (M i)], is_artinian R (Π i, M i) := finite.induction_empty_option (begin introsI α β e hα M _ _ _ _, exact is_artinian_of_linear_equiv (linear_equiv.Pi_congr_left R M e) end) (by { introsI M _ _ _ _, apply_instance }) (begin introsI α _ ih M _ _ _ _, exact is_artinian_of_linear_equiv (linear_equiv.pi_option_equiv_prod R).symm, end) ι /-- A version of `is_artinian_pi` for non-dependent functions. We need this instance because sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to prove that `ι → ℝ` is finite dimensional over `ℝ`). -/ instance is_artinian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [finite ι] [is_artinian R M] : is_artinian R (ι → M) := is_artinian_pi end open is_artinian submodule function section ring variables {R M : Type*} [ring R] [add_comm_group M] [module R M] theorem is_artinian_iff_well_founded : is_artinian R M ↔ well_founded ((<) : submodule R M → submodule R M → Prop) := ⟨λ h, h.1, is_artinian.mk⟩ variables {R M} lemma is_artinian.finite_of_linear_independent [nontrivial R] [is_artinian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_lt R M)).elim' _), have f : ℕ ↪ s, from set.infinite.nat_embedding s hf, have : ∀ n, (coe ∘ f) '' {m | n ≤ m} ⊆ s, { rintros n x ⟨y, hy₁, rfl⟩, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | b ≤ m}) ≤ span R ((coe ∘ f) '' {m | a ≤ m}), { assume a b, rw [span_le_span_iff hs (this b) (this a), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], simp only [set.mem_set_of_eq], exact ⟨λ hab x, le_trans hab, λ h, (h _ le_rfl)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | n ≤ m}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, begin intros a b, conv_rhs { rw [gt, lt_iff_le_not_le, this, this, ← lt_iff_le_not_le] }, simp end⟩ end /-- A module is Artinian iff every nonempty set of submodules has a minimal submodule among them. -/ theorem set_has_minimal_iff_artinian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M') ↔ is_artinian R M := by rw [is_artinian_iff_well_founded, well_founded.well_founded_iff_has_min'] theorem is_artinian.set_has_minimal [is_artinian R M] (a : set $ submodule R M) (ha : a.nonempty) : ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M' := set_has_minimal_iff_artinian.mpr ‹_› a ha /-- A module is Artinian iff every decreasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_artinian : (∀ (f : ℕ →o (submodule R M)ᵒᵈ), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_artinian R M := by { rw is_artinian_iff_well_founded, exact well_founded.monotone_chain_condition.symm } namespace is_artinian variables [is_artinian R M] theorem monotone_stabilizes (f : ℕ →o (submodule R M)ᵒᵈ) : ∃ n, ∀ m, n ≤ m → f n = f m := monotone_stabilizes_iff_artinian.mpr ‹_› f /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma induction {P : submodule R M → Prop} (hgt : ∀ I, (∀ J < I, P J) → P I) (I : submodule R M) : P I := (well_founded_submodule_lt R M).recursion I hgt /-- For any endomorphism of a Artinian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem exists_endomorphism_iterate_ker_sup_range_eq_top (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊔ (f ^ n).range = ⊤ := begin obtain ⟨n, w⟩ := monotone_stabilizes (f.iterate_range.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w ((n + 1) + n) (by linarith), dsimp at w, refine ⟨n + 1, nat.succ_ne_zero _, _⟩, simp_rw [eq_top_iff', mem_sup], intro x, have : (f^(n + 1)) x ∈ (f ^ ((n + 1) + n + 1)).range, { rw ← w, exact mem_range_self _ }, rcases this with ⟨y, hy⟩, use x - (f ^ (n+1)) y, split, { rw [linear_map.mem_ker, linear_map.map_sub, ← hy, sub_eq_zero, pow_add], simp [iterate_add_apply], }, { use (f^ (n+1)) y, simp } end /-- Any injective endomorphism of an Artinian module is surjective. -/ theorem surjective_of_injective_endomorphism (f : M →ₗ[R] M) (s : injective f) : surjective f := begin obtain ⟨n, ne, w⟩ := exists_endomorphism_iterate_ker_sup_range_eq_top f, rw [linear_map.ker_eq_bot.mpr (linear_map.iterate_injective s n), bot_sup_eq, linear_map.range_eq_top] at w, exact linear_map.surjective_of_iterate_surjective ne w, end /-- Any injective endomorphism of an Artinian module is bijective. -/ theorem bijective_of_injective_endomorphism (f : M →ₗ[R] M) (s : injective f) : bijective f := ⟨s, surjective_of_injective_endomorphism f s⟩ /-- A sequence `f` of submodules of a artinian module, with the supremum `f (n+1)` and the infinum of `f 0`, ..., `f n` being ⊤, is eventually ⊤. -/ lemma disjoint_partial_infs_eventually_top (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups (order_dual.to_dual ∘ f) n) (order_dual.to_dual (f (n+1)))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊤ := begin -- A little off-by-one cleanup first: rsuffices ⟨n, w⟩ : ∃ n : ℕ, ∀ m, n ≤ m → order_dual.to_dual f (m+1) = ⊤, { use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes (partial_sups (order_dual.to_dual ∘ f)), refine ⟨n, λ m p, _⟩, exact (h m).eq_bot_of_ge (sup_eq_left.1 $ (w (m + 1) $ le_add_right p).symm.trans $ w m p) end end is_artinian end ring section comm_ring variables {R : Type*} (M : Type*) [comm_ring R] [add_comm_group M] [module R M] [is_artinian R M] namespace is_artinian lemma range_smul_pow_stabilizes (r : R) : ∃ n : ℕ, ∀ m, n ≤ m → (r^n • linear_map.id : M →ₗ[R] M).range = (r^m • linear_map.id : M →ₗ[R] M).range := monotone_stabilizes ⟨λ n, (r^n • linear_map.id : M →ₗ[R] M).range, λ n m h x ⟨y, hy⟩, ⟨r ^ (m - n) • y, by { dsimp at ⊢ hy, rw [←smul_assoc, smul_eq_mul, ←pow_add, ←hy, add_tsub_cancel_of_le h] }⟩⟩ variables {M} lemma exists_pow_succ_smul_dvd (r : R) (x : M) : ∃ (n : ℕ) (y : M), r ^ n.succ • y = r ^ n • x := begin obtain ⟨n, hn⟩ := is_artinian.range_smul_pow_stabilizes M r, simp_rw [set_like.ext_iff] at hn, exact ⟨n, by simpa using hn n.succ n.le_succ (r ^ n • x)⟩, end end is_artinian end comm_ring -- TODO: Prove this for artinian modules -- /-- -- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -- -/ -- universe w -- variables {N : Type w} [add_comm_group N] [module R N] -- noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] -- (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := -- begin -- apply nonempty.some, -- obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) -- (f.tailings_disjoint_tailing i), -- specialize w n (le_refl n), -- apply nonempty.intro, -- refine (f.tailing_linear_equiv i n).symm.trans _, -- rw w, -- exact submodule.bot_equiv_punit, -- end /-- A ring is Artinian if it is Artinian as a module over itself. Strictly speaking, this should be called `is_left_artinian_ring` but we omit the `left_` for convenience in the commutative case. For a right Artinian ring, use `is_artinian Rᵐᵒᵖ R`. -/ @[reducible] def is_artinian_ring (R) [ring R] := is_artinian R R theorem is_artinian_ring_iff {R} [ring R] : is_artinian_ring R ↔ is_artinian R R := iff.rfl theorem ring.is_artinian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_artinian_ring R := have _ := subsingleton_of_zero_eq_one h01, by exactI infer_instance theorem is_artinian_of_submodule_of_artinian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_artinian R M) : is_artinian R N := by apply_instance theorem is_artinian_of_quotient_of_artinian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_artinian R M) : is_artinian R (M ⧸ N) := is_artinian_of_surjective M (submodule.mkq N) (submodule.quotient.mk_surjective N) /-- If `M / S / R` is a scalar tower, and `M / R` is Artinian, then `M / S` is also Artinian. -/ theorem is_artinian_of_tower (R) {S M} [comm_ring R] [ring S] [add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_artinian R M) : is_artinian S M := begin rw is_artinian_iff_well_founded at h ⊢, refine (submodule.restrict_scalars_embedding R S M).well_founded h end theorem is_artinian_of_fg_of_artinian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_artinian_ring R] (hN : N.fg) : is_artinian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_artinian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_artinian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_artinian_of_fg_of_artinian' {R M} [ring R] [add_comm_group M] [module R M] [is_artinian_ring R] (h : (⊤ : submodule R M).fg) : is_artinian R M := have is_artinian R (⊤ : submodule R M), from is_artinian_of_fg_of_artinian _ h, by exactI is_artinian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a artinian ring, the submodule generated by finitely many vectors is artinian. -/ theorem is_artinian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_artinian_ring R] {A : set M} (hA : A.finite) : is_artinian R (submodule.span R A) := is_artinian_of_fg_of_artinian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem function.surjective.is_artinian_ring {R} [ring R] {S} [ring S] {F} [ring_hom_class F R S] {f : F} (hf : function.surjective f) [H : is_artinian_ring R] : is_artinian_ring S := begin rw [is_artinian_ring_iff, is_artinian_iff_well_founded] at H ⊢, exact (ideal.order_embedding_of_surjective f hf).well_founded H, end instance is_artinian_ring_range {R} [ring R] {S} [ring S] (f : R →+* S) [is_artinian_ring R] : is_artinian_ring f.range := f.range_restrict_surjective.is_artinian_ring namespace is_artinian_ring open is_artinian variables {R : Type*} [comm_ring R] [is_artinian_ring R] lemma is_nilpotent_jacobson_bot : is_nilpotent (ideal.jacobson (⊥ : ideal R)) := begin let Jac := ideal.jacobson (⊥ : ideal R), let f : ℕ →o (ideal R)ᵒᵈ := ⟨λ n, Jac ^ n, λ _ _ h, ideal.pow_le_pow h⟩, obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → Jac ^ n = Jac ^ m := is_artinian.monotone_stabilizes f, refine ⟨n, _⟩, let J : ideal R := annihilator (Jac ^ n), suffices : J = ⊤, { have hJ : J • Jac ^ n = ⊥ := annihilator_smul (Jac ^ n), simpa only [this, top_smul, ideal.zero_eq_bot] using hJ }, by_contradiction hJ, change J ≠ ⊤ at hJ, rcases is_artinian.set_has_minimal {J' : ideal R | J < J'} ⟨⊤, hJ.lt_top⟩ with ⟨J', hJJ' : J < J', hJ' : ∀ I, J < I → I ≤ J' → I = J'⟩, rcases set_like.exists_of_lt hJJ' with ⟨x, hxJ', hxJ⟩, obtain rfl : J ⊔ ideal.span {x} = J', { refine hJ' (J ⊔ ideal.span {x}) _ _, { rw set_like.lt_iff_le_and_exists, exact ⟨le_sup_left, ⟨x, mem_sup_right (mem_span_singleton_self x), hxJ⟩⟩ }, { exact (sup_le hJJ'.le (span_le.2 (singleton_subset_iff.2 hxJ'))) } }, have : J ⊔ Jac • ideal.span {x} ≤ J ⊔ ideal.span {x}, from sup_le_sup_left (smul_le.2 (λ _ _ _, submodule.smul_mem _ _)) _, have : Jac * ideal.span {x} ≤ J, --Need version 4 of Nakayamas lemma on Stacks { classical, by_contradiction H, refine H (smul_sup_le_of_le_smul_of_le_jacobson_bot (fg_span_singleton _) le_rfl (hJ' _ _ this).ge), exact lt_of_le_of_ne le_sup_left (λ h, H $ h.symm ▸ le_sup_right) }, have : ideal.span {x} * Jac ^ (n + 1) ≤ ⊥, calc ideal.span {x} * Jac ^ (n + 1) = ideal.span {x} * Jac * Jac ^ n : by rw [pow_succ, ← mul_assoc] ... ≤ J * Jac ^ n : mul_le_mul (by rwa mul_comm) le_rfl ... = ⊥ : by simp [J], refine hxJ (mem_annihilator.2 (λ y hy, (mem_bot R).1 _)), refine this (mul_mem_mul (mem_span_singleton_self x) _), rwa [← hn (n + 1) (nat.le_succ _)] end section localization variables (S : submonoid R) (L : Type*) [comm_ring L] [algebra R L] [is_localization S L] include S /-- Localizing an artinian ring can only reduce the amount of elements. -/ theorem localization_surjective : function.surjective (algebra_map R L) := begin intro r', obtain ⟨r₁, s, rfl⟩ := is_localization.mk'_surjective S r', obtain ⟨r₂, h⟩ : ∃ r : R, is_localization.mk' L 1 s = algebra_map R L r, swap, { exact ⟨r₁ * r₂, by rw [is_localization.mk'_eq_mul_mk'_one, map_mul, h]⟩ }, obtain ⟨n, r, hr⟩ := is_artinian.exists_pow_succ_smul_dvd (s : R) (1 : R), use r, rw [smul_eq_mul, smul_eq_mul, pow_succ', mul_assoc] at hr, apply_fun algebra_map R L at hr, simp only [map_mul, ←submonoid.coe_pow] at hr, rw [←is_localization.mk'_one L, is_localization.mk'_eq_iff_eq, one_mul, submonoid.coe_one, ←(is_localization.map_units L (s ^ n)).mul_left_cancel hr, map_mul, mul_comm], end lemma localization_artinian : is_artinian_ring L := (localization_surjective S L).is_artinian_ring /-- `is_artinian_ring.localization_artinian` can't be made an instance, as it would make `S` + `R` into metavariables. However, this is safe. -/ instance : is_artinian_ring (localization S) := localization_artinian S _ end localization end is_artinian_ring
e947bd9b9673a9e73b84b7657b430b7e2c8cd83e
0ddf2dd8409bcb923d11603846800bd9699616ea
/chapter8.lean
3694a9c31c2103fa318c8be395fbb7d78eab8140
[]
no_license
tounaishouta/Lean
0cbaaa9340e7f8f884504ea170243e07a54f0566
1d75311f5506ca2bfd8b7ccec0b7d70c3319d555
refs/heads/master
1,610,229,383,935
1,459,950,226,000
1,459,950,226,000
50,836,185
0
0
null
null
null
null
UTF-8
Lean
false
false
15,943
lean
import standard namespace chapter8 /- Chapter 8. Building Theories and Proofs 実際的な Lean の機能について議論します。 Section 8.1. More on Coercions 前回、議論した coercion についてより詳しい説明をします。 まずは coercion の復習 -/ namespace coercion0 -- 現在定義されている coercion を確認する。 print coercions -- num ↣ int : int.of_num open bool nat -- 新しく定義する関数に coercion attribute を付与する。 definition foo [coercion] : bool → nat | foo ff := 0 | foo tt := 1 -- 既に定義された関数に coercion attribute を付与する。 attribute int.of_nat [coercion] -- local attribute int.of_nat [coercion] -- local にもできる。 print coercions -- num ↣ int : int.of_num -- bool ↣ int : int._trans_to_of_nat -- bool ↣ nat : foo -- nat ↣ int : int.of_nat -- int が必要なところに bool を与えると coercion で変換される。 eval (ff : int) --> 0 eval (tt : int) --> 1 -- coercion は推移的に生成される。(命名規則はよくわからない) -- 適用可能な coercion が複数ある場合は最も新しく定義されたものが使われる? -- coercion は attribute が付与された namespace で有効 -- その namespace を open した後も有効 -- local attribute ... を使うと付与した namespace で有効だが -- open しても有効にならない。 -- pp.coercions オプションにより print されるメッセージに -- coercion を明示的に表示させることができる。 check (ff : nat) --> ff : ℕ set_option pp.coercions true check (ff : nat) --> foo ff : ℕ end coercion0 /- 今回の話 coercion attribute を付与できるのは次の型を持つ項に対してだけ 1. Pi (x_1 : A_1) ... (x_n : A_n) (y: C x_1 ... x_n), D t_1 ... t_m 2. Pi (x_1 : A_1) ... (x_n : A_n) (y: C x_1 ... x_n), Type 3. Pi (x_1 : A_1) ... (x_n : A_n) (y: C x_1 ... x_n), (Pi x : A, B x) 個別に見ていこう。 1. Pi (x_1 : A_1) ... (x_n : A_n) (y: C x_1 ... x_n), D t_1 ... t_m i.e パラメータを持つ型 C からパラメータを持つ型 D へ (t_1, ..., t_m は x_1, ..., x_n, y に依存してよい。) 例 C := list, D := set のとき -/ namespace coercion1 open list print list print set --> : Type → Type := λ (X : Type), X → Prop definition contains {A : Type} : list A → A → Prop | contains nil _ := false | contains (x :: xs) y := x = y ∨ contains xs y definition set_of_list [coercion] {A : Type} : list A → set A := contains check λ (A : Type) (xs : set A) (y : A), xs y --> OK check λ (A : Type) (xs : list A) (y : A), xs y --> Error! check λ (A : Type) (xs : list A) (y : A), (xs : set A) y --> OK (use set_of_list) -- 次の話 attribute contains [coercion] check λ (A : Type) (xs : list A) (y : A), xs y --> OK (use contains) end coercion1 /- 2. Pi (x_1 : A_1) ... (x_n : A_n) (y: C x_1 ... x_n), Type i.e. パラメータを持つ型 C から Type へ 例 C := Semigroup -/ namespace coercion2 structure Semigroup := (carrier : Type) -- underlying set に相当 (mul : carrier → carrier → carrier) (mul_assoc : ∀ a b c : carrier, mul (mul a b) c = mul a (mul b c)) check Semigroup.carrier --> : Semigroup → Type attribute Semigroup.carrier [coercion] notation a `*` b := Semigroup.mul _ a b example (S : Semigroup) (a b c : S) : (a * b) * c = a * (b * c) := calc (a * b) * c = a * (b * c) : Semigroup.mul_assoc -- coercion により ... (a b c : Semigroup.carrier S) ... に変換される。 -- 数学で代数構造などを持った対象 (S, *) と underlying set S を同じ記号で表す感覚 end coercion2 /- 3. Pi (x_1 : A_1) ... (x_n : A_n) (y: C x_1 ... x_n), (Pi x : A, B x) i.e. パラメータを持つ型 C から関数型へ A, B は x1, ..., x_n, y に依存してよい。 例 C := Semigroup.morphism, A := S1, B x := S2 -/ namespace coercion3 open coercion2 structure morphism (S1 S2 : Semigroup) := (mor : S1 → S2) -- coercion により (mor : Semigroup.carrier S1 → Semigroup.carrier S2) に (resp_mul : ∀ a b : S1, mor (a * b) = mor a * mor b) -- 上にも coercion が隠れています。 check @morphism.mor --> Π {S1 : Semigroup} {S2 : Semigroup}, morphism S1 S2 → S1 → S2 attribute morphism.mor [coercion] example (S1 S2 : Semigroup) (f : morphism S1 S2) (a b : S1) : f (a * b) = f a * f b := calc f (a * b) = f a * f b : morphism.resp_mul -- f は structure だが”写像”として扱える。 end coercion3 /- -------------------------------------------------------------------------------- Section 8.2. More on Implicit Argument 復習しながら見ていく。 -/ namespace implicit1 open bool nat definition foo {A : Type} : A → A | foo a := a -- brace { } で囲むと implicit argument になる。 -- λ {...}, ... や variable {...} の形でも check foo check @foo -- foo の explicit version check @foo _ -- foo は”常に” @foo _ に展開される。 check foo ff -- は check @foo _ ff -- に展開されて check @foo bool ff -- underscore は bool に substitute される。 check nat.mul_assoc check !nat.mul_assoc -- は check nat.mul_assoc _ _ _ -- に展開される。 -- アンダースコアは次の引数が残りの引数と結果の型から推論される限り -- つけ加えられる。 -- 特に、補完されるアンダースコアの数は ! をつけた対象の型だけできまり、 -- 文脈によらない。 definition T (A B : Type) (a : A) (b : B) : Type := sorry check !T -- T _ _ に展開される。 -- 第3、第4の引数の型から第1、第2引数は推論される。 definition t (A B : Type) (a : A) (b : B) : T A B a b := sorry check !t -- t _ _ _ _ に展開される。 -- 結果の型から全ての引数が推論される。 -- variable を使う場合、途中から implicit にできる。 section variable A : Type variable a : A definition baz : A := a variable {A} definition qux : A := a end check baz check qux end implicit1 namespace implicit2 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 check @reflexive --> Π {A : Type} (A → A → Prop) → Prop check @symmetric --> Π {A : Type} (A → A → Prop) → Prop check @transitive --> Π {A : Type} (A → A → Prop) → Prop check @euclidean --> Π {A : Type} (A → A → Prop) → Prop variable {R} theorem th1 (refl : reflexive R) (eucl : euclidean R) : symmetric R := take a b : A, suppose R a b, have R a a, from !refl, show R b a, from eucl `R a b` `R a a` check @th1 -- ∀ {A : Type} {R : A → A → Prop}, reflexive R → euclidean R → symmetric R theorem th2 (symm : symmetric R) (eucl : euclidean R) : transitive R := take a b c : A, suppose R a b, suppose R b c, have R b a, from symm `R a b`, show R a c, from eucl `R b a` `R b c` check @th2 -- ∀ {A : Type} {R : A → A → Prop}, symmetric R → euclidean R → transitive R theorem th3 (refl : reflexive R) (eucl : euclidean R) : transitive R := -- th2 (th1 refl eucl) eucl -- Error! /- type mismatch at application th1 refl eucl term eucl has type R ?M_2 ?M_3 → R ?M_2 ?M_4 → R ?M_3 ?M_4 but is expected to have type euclidean ?M_1 -/ -- @(th2 @(th1 refl @eucl) @eucl) -- あるいは、 @th2 _ _ (@th1 _ _ @refl @eucl) @eucl end implicit2 /- implicit argument を持つ関数を引数として渡したときに、 @eucl _ _ _ のように 展開されてしまい、上手くいかない。 このような問題を解決するのに便利なのが weaker implicit argument ⦃ と ⦄ (\{{ \}} で入力) あるいは {{ }}で囲むことで weaker implicit argument になる。 wekar implicit argument を持つ関数 t は、 関数として使用した(関数適用の左側に来た)ときのみ、 @t _ の形に展開されるが、 それ以外のときは @t のまま 先程の例を weaker implicit argument で書き直してみる。 -/ namespace implicit3 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 check @reflexive --> Π {A : Type} (A → A → Prop) → Prop check @symmetric --> Π {A : Type} (A → A → Prop) → Prop check @transitive --> Π {A : Type} (A → A → Prop) → Prop check @euclidean --> Π {A : Type} (A → A → Prop) → Prop variable {R} theorem th1 (refl : reflexive R) (eucl : euclidean R) : symmetric R := take a b : A, suppose R a b, have R a a, from !refl, show R b a, from eucl `R a b` `R a a` check @th1 -- ∀ {A : Type} {R : A → A → Prop}, reflexive R → euclidean R → symmetric R theorem th2 (symm : symmetric R) (eucl : euclidean R) : transitive R := take a b c : A, suppose R a b, suppose R b c, have R b a, from symm `R a b`, show R a c, from eucl `R b a` `R b c` check @th2 -- ∀ {A : Type} {R : A → A → Prop}, symmetric R → euclidean R → transitive R theorem th3 (refl : reflexive R) (eucl : euclidean R) : transitive R := th2 (th1 refl eucl) eucl end implicit3 /- まとめ(と次回予告) 引数には次の4種類ある。 1. explicit argument (a : A) or a : A 明示的に引数を与える必要がある。 2. implicit argument {a : A} @t _ の形に展開される。 3. wekaer implicit argument ⦃a : A⦄ or {{a : A}} 関数として使用したときのみ @t _ の形に展開される。 4. Type Class に関するもの [a : A] 次の章で扱う。 -------------------------------------------------------------------------------- Section 8.3 Elaboration and Unification λ x y z, f (x + y) z のような "不完全" な式を受け取り implicit な情報を推論する処理を elaboration という? implicit な情報には * 省略された型 * overload された notation の内どれを採用するか (どのように parse するか?) * implicit argument を何で埋めるか * どこにどの coercion を適用するか などがある。 結論からいうと Lean の elaboration algorithm は o powerful x subtle x complex x not complete x potentially nonterminating o performs quite well in ordinary situations らしい。 * elaborator が省略した情報をどれくらい確実に推論できるか * error message にどのように対応すべきか を知るためにこのあたりの理解が必要? (この節だけ読んでもいまいち分かりませんでしたが。。。) 以下、Lean の elaboration プロセスを順を追って説明する。 1. implicit argument のための "hole" を挿入する。 先程の節でみたように、 t : Π {a : A}, T a のとき、t は @t _ に置き換えられる。 2. instantiate metavariables 入力された _ や上のステップで付け加えられた _ に メタ変数 ?M1, ?M2, ... を割り当てる。 (error message でたまに出る ?M1 みたいなのはここで付与されたもの) 3. overload された(複数の意味を持つ)notation e.g. -/ namespace elaboration0 open sum print notation + -- print result: -- _ `+`:65 _:65 := -- | add #1 #0 -- | sum #1 #0 end elaboration0 /- についてありうる解釈を列挙する。 (notation の parse の問題もここで?) 4. coercion が必要となるかもしれない関数適用 s t に ついて、適用されうる coercion を列挙する。 * t の型が s の引数の型になるように t に coercion を適用する * s が t に適用できる関数になるように coercion を適用する * 適用必要がない ↔ identity を coercion として適用する 5. 型制約条件を列挙し、制約問題を解く。 型制約条件は次の二種類 * 関数適用 t1 t2 が行われていて、 t1 : T1 かつ t2 : T2 (T1, T2 はメタ変数を含みうる)のとき T1 は T2 を引数にとる関数型でなければならない。i.e. T1 = Π x : T2, T3 x * definition foo : T := t のように宣言されている場合、 t : T でなければならない。 すべての関数適用と(あれば)全体の型から 制約条件を列挙する。 式 t1, t2, ... であって、 メタ変数 ?M1, ?M2, ... に代入することで 全ての制約条件をみたすものを見つける (unification problem) 典型的な問題 (first-order) は簡単に解ける。 制約条件 f t_1 ... t_m = g s_1 ... s_m を考える。 * f = g のときは、より小さいいくつかの制約条件 t_1 = s_1, ..., t_m = s_m を解けばいい。 * f ≠ g のときは解なし 最終的に ?M = t の形になれば、そのメタ変数については解けたことになる。 しかし higher-order unification problem は大変 例) ?M a b = f (g a) b b の解は? * ?M = λ x y, f (g x) y y * ?M = λ x y, f (g x) y b * ?M = λ x y, f (g a) b y ... このような推論の問題は容易に発生しうる。 -/ check @sigma.mk check @nat.rec check @eq.subst /- 上の関数は関数を implicit argument に持つ。 このような問題を Lean は backtracking search で解く。 second-order でも undecidable であることが知られているらしい。 Lean の algorithm は x not complete (解がある場合でも失敗しうる) x potentailly nonterminating o performs quite well in ordinary situations さらに困ったことに、 制約問題を解くために "計算" が必要になる場合がある。 e.g. f M1? M2? = (λ x, f x x) M3? (β簡約を行わないと解けない) 必要な計算の量はいくらでも大きくなりうる。 ので、全ての簡約を試すのは現実的でない。 ので、Lean は higher-order な制約を解くために 簡約計算を行うことを避ける。 これをさせない(Lean に簡約させる)ために、 reducible attribute が使えるらしいが、 これは Section 8.4 で説明する。 Lean は制約条件を簡単なものから解いていくらしい。 (確かにその方が効率が良さそう) 6. global backtracking search overload された notation や coercion についても選択の余地があるので、 これらについても backtracking search を行う。 まず、最初の候補(どれが最初?)で 5. を試し、 失敗したら、その結果を解析し、 次に試す選択肢を決める。 etc. 他にも制約問題を解くための "わざ" があるらしい。 tactic とか(あまり説明はない) あと class iference とか(これは次の章) このあたりはあまり理解できていません。 (The elaborator relies on ... の段落) まとめ. backtracking search で何から試すか、 どの順番で試すかはこの tutorial では明らかにされてない。 多分、実装依存というかこれから仕様変わる可能性がある。 また、明示的に書かれていないが、探索の中でひとつ解が見つかれば、 他の解の探索はしないようである。 よって、Lean に複数の解釈の可能性を与える場合は 型注釈をつける方が賢明 -/ end chapter8
f6e5688510be1fe60611c90d79383c27293cc44e
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/listDecEq.lean
f55fdb32803fb89dbd20775383e0485534efe03f
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
777
lean
-- List decidable equality using `withPtrEqDecEq` def listDecEqAux {α} [s : DecidableEq α] : ∀ (as bs : List α), Decidable (as = bs) | [], [] => isTrue rfl | [], b::bs => isFalse $ fun h => List.noConfusion h | a::as, [] => isFalse $ fun h => List.noConfusion h | a::as, b::bs => match s a b with | isTrue h₁ => match withPtrEqDecEq as bs (fun _ => listDecEqAux as bs) with | isTrue h₂ => isTrue $ h₁ ▸ h₂ ▸ rfl | isFalse h₂ => isFalse $ fun h => List.noConfusion h $ fun _ h₃ => absurd h₃ h₂ | isFalse h₁ => isFalse $ fun h => List.noConfusion h $ fun h₂ _ => absurd h₂ h₁ instance List.optimizedDecEq {α} [DecidableEq α] : DecidableEq (List α) := fun a b => withPtrEqDecEq a b (fun _ => listDecEqAux a b)
3ed9ad18e1fd6488e9fe2417be45617202f6f710
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/recInfo1.lean
fc00da5188e0ae6e7695a58c7ad72a4f8471c30e
[ "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
635
lean
import Lean.Meta open Lean open Lean.Meta def print (msg : MessageData) : MetaM Unit := trace[Meta.debug] msg def showRecInfo (declName : Name) (majorPos? : Option Nat := none) : MetaM Unit := do let info ← mkRecursorInfo declName majorPos? print (toString info) theorem Iff.elim {a b c} (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c := h₁ h₂.1 h₂.2 set_option trace.Meta true set_option trace.Meta.isDefEq false #eval showRecInfo `Acc.recOn #eval showRecInfo `Prod.casesOn #eval showRecInfo `List.recOn #eval showRecInfo `List.casesOn #eval showRecInfo `List.brecOn #eval showRecInfo `Iff.elim (some 4)
1ba73c798ed33362ce132198f2917d7811fd6786
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/compiler/t2.lean
3791e8f44c4f03920144f82049c4a65ac11d3fd4
[ "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
2,872
lean
/- Benchmark for new code generator -/ inductive Expr | Val : Int → Expr | Var : String → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr | Pow : Expr → Expr → Expr | Ln : Expr → Expr open Expr partial def pown : Int → Int → Int | a 0 := 1 | a 1 := a | a n := let b := pown a (n / 2) in b * b * (if n % 2 = 0 then 1 else a) partial def add : Expr → Expr → Expr | (Val n) (Val m) := Val (n + m) | (Val 0) f := f | f (Val 0) := f | f (Val n) := add (Val n) f | (Val n) (Add (Val m) f) := add (Val (n+m)) f | f (Add (Val n) g) := add (Val n) (add f g) | (Add f g) h := add f (add g h) | f g := Add f g partial def mul : Expr → Expr → Expr | (Val n) (Val m) := Val (n*m) | (Val 0) _ := Val 0 | _ (Val 0) := Val 0 | (Val 1) f := f | f (Val 1) := f | f (Val n) := mul (Val n) f | (Val n) (Mul (Val m) f) := mul (Val (n*m)) f | f (Mul (Val n) g) := mul (Val n) (mul f g) | (Mul f g) h := mul f (mul g h) | f g := Mul f g def pow : Expr → Expr → Expr | (Val m) (Val n) := Val (pown m n) | _ (Val 0) := Val 1 | f (Val 1) := f | (Val 0) _ := Val 0 | f g := Pow f g def ln : Expr → Expr | (Val 1) := Val 0 | f := Ln f def d (x : String) : Expr → Expr | (Val _) := Val 0 | (Var y) := if x = y then Val 1 else Val 0 | (Add f g) := add (d f) (d g) | (Mul f g) := add (mul f (d g)) (mul g (d f)) | (Pow f g) := mul (pow f g) (add (mul (mul g (d f)) (pow f (Val (-1)))) (mul (ln f) (d g))) | (Ln f) := mul (d f) (pow f (Val (-1))) def count : Expr → Nat | (Val _) := 1 | (Var _) := 1 | (Add f g) := count f + count g | (Mul f g) := count f + count g | (Pow f g) := count f + count g | (Ln f) := count f def Expr.toString : Expr → String | (Val n) := toString n | (Var x) := x | (Add f g) := "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")" | (Mul f g) := "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")" | (Pow f g) := "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")" | (Ln f) := "ln(" ++ Expr.toString f ++ ")" instance : HasToString Expr := ⟨Expr.toString⟩ def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr | 0 x := pure x | m@(n+1) x := f (s - m) x >>= nestAux n def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr := nestAux n f n e def deriv (i : Nat) (f : Expr) : IO Expr := do let d := d "x" f; IO.println (toString (i+1) ++ " count: " ++ (toString $ count d)); pure d def main (xs : List String) : IO UInt32 := do let x := Var "x"; let f := pow x x; nest deriv 9 f; pure 0 -- setOption profiler True -- #eval main []
658a691f392f769dc53019fcc1d66d81bdb93a48
bae21755a4a03bbe0a5c22e258db8633407711ad
/library/init/meta/exceptional.lean
5f29155d87f48e807672076ed0bf8783c1ff4628
[ "Apache-2.0" ]
permissive
nor-code/lean
f437357a8f85db0f06f186fa50fcb1bc75f6b122
aa306af3d7c47de3c7937c98d3aa919eb8da6f34
refs/heads/master
1,662,613,329,886
1,586,696,014,000
1,586,696,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,615
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.category.monad init.meta.format init.util /- Remark: we use a function that produces a format object as the exception information. Motivation: the formatting object may be big, and we may create it on demand. -/ /-- An exceptional is similar to `Result` in Haskell.-/ meta inductive exceptional (α : Type) | success : α → exceptional | exception : (options → format) → exceptional section open exceptional variables {α : Type} variables [has_to_string α] protected meta def exceptional.to_string : exceptional α → string | (success a) := to_string a | (exception e) := "Exception: " ++ to_string (e options.mk) meta instance : has_to_string (exceptional α) := has_to_string.mk exceptional.to_string end namespace exceptional variables {α β : Type} protected meta def to_bool : exceptional α → bool | (success _) := tt | (exception _) := ff protected meta def to_option : exceptional α → option α | (success a) := some a | (exception _) := none @[inline] protected meta def bind (e₁ : exceptional α) (e₂ : α → exceptional β) : exceptional β := exceptional.cases_on e₁ (λ a, e₂ a) (λ f, exception f) @[inline] protected meta def return (a : α) : exceptional α := success a @[inline] meta def fail (f : format) : exceptional α := exception (λ u, f) end exceptional meta instance : monad exceptional := {pure := @exceptional.return, bind := @exceptional.bind}
3ed6e53e3becfdf2f0636172f28c4776d177f3a5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/setoid/partition.lean
4ef684c2c67a94d94b5e26a0e2812e938ac944e0
[ "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
16,737
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen, Patrick Massot -/ import data.fintype.basic import data.set.finite import data.setoid.basic import order.partition.finpartition /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. There are two implementations of partitions here: * A collection `c : set (set α)` of sets is a partition of `α` if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. This is expressed as `is_partition c` * An indexed partition is a map `s : ι → α` whose image is a partition. This is expressed as `indexed_partition s`. Of course both implementations are related to `quotient` and `setoid`. `setoid.is_partition.partition` and `finpartition.is_partition_parts` furnish a link between `setoid.is_partition` and `finpartition`. ## TODO Could the design of `finpartition` inform the one of `setoid.is_partition`? Maybe bundling it and changing it from `set (set α)` to `set α` where `[lattice α] [order_bot α]` would make it more usable. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace setoid variables {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique2 hc hb hc' hb' /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : setoid α := ⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx, λ x y h s hs hy, (H x).elim2 $ λ t ht hx _, have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx), this.symm ▸ hx, λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _, have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy, have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz, (hst.trans htt').symm ▸ hz⟩⟩ /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩ lemma classes_ker_subset_fiber_set {β : Type*} (f : α → β) : (setoid.ker f).classes ⊆ set.range (λ y, {x | f x = y}) := by { rintro s ⟨x, rfl⟩, rw set.mem_range, exact ⟨f x, rfl⟩ } lemma finite_classes_ker {α β : Type*} [finite β] (f : α → β) : finite (setoid.ker f).classes := by { classical, exact finite.set.subset _ (classes_ker_subset_fiber_set f) } lemma card_classes_ker_le {α β : Type*} [fintype β] (f : α → β) [fintype (setoid.ker f).classes] : fintype.card (setoid.ker f).classes ≤ fintype.card β := begin classical, exact le_trans (set.card_le_of_subset (classes_ker_subset_fiber_set f)) (fintype.card_range_le _) end /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ lemma eq_iff_classes_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} := ⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩ lemma rel_iff_exists_classes (r : setoid α) {x y} : r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩, λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ lemma classes_inj {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩ /-- The empty set is not an equivalence class. -/ lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes := λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $ begin rintros _ ⟨y, rfl⟩ ha, ext x, exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩ end /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ lemma eq_eqv_class_of_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = {x | (mk_classes c H).rel x y} := set.ext $ λ x, ⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs', λ hx, (H x).elim2 $ λ b' hc' hb' h', (eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩ /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : {x | (mk_classes c H).rel x y} ∈ c := (H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc lemma eqv_class_mem' {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x} : {y : α | (mk_classes c H).rel x y} ∈ c := by { convert setoid.eqv_class_mem H, ext, rw setoid.comm' } /-- Distinct elements of a set of sets partitioning α are disjoint. -/ lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : c.pairwise_disjoint id := λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $ λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ lemma eqv_classes_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : c.pairwise_disjoint id) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim_set hc' hc a ha' ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : c.pairwise_disjoint id) : setoid α := setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mk_classes_classes (r : setoid α) : mk_classes r.classes classes_eqv_classes = r := ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x), λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : setoid α) : ⋃₀ r.classes = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 ⟨{ y | r.rel y x }, ⟨x, rfl⟩, setoid.refl _⟩ section partition /-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def is_partition (c : set (set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) : s.nonempty := set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h lemma is_partition_classes (r : setoid α) : is_partition r.classes := ⟨empty_not_mem_classes, classes_eqv_classes⟩ lemma is_partition.pairwise_disjoint {c : set (set α)} (hc : is_partition c) : c.pairwise_disjoint id := eqv_classes_disjoint hc.2 lemma is_partition.sUnion_eq_univ {c : set (set α)} (hc : is_partition c) : ⋃₀ c = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 $ let ⟨t, ht⟩ := hc.2 x in ⟨t, by { simp only [exists_unique_iff_exists] at ht, tauto }⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) : ∃ y, s = {x | (mk_classes c hc.2).rel x y} := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) : (mk_classes c hc.2).classes = c := set.ext $ λ s, ⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy, by rwa (show s = b, from hs.symm ▸ set.ext (λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb, λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)), exists_of_mem_partition hc⟩ /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance partition.le : has_le (subtype (@is_partition α)) := ⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance partition.partial_order : partial_order (subtype (@is_partition α)) := { le := (≤), lt := λ x y, x ≤ y ∧ ¬y ≤ x, le_refl := λ _, @le_refl (setoid α) _ _, le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] } variables (α) /-- The order-preserving bijection between equivalence relations on a type `α`, and partitions of `α` into subsets. -/ protected def partition.order_iso : setoid α ≃o {C : set (set α) // is_partition C} := { to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩, inv_fun := λ C, mk_classes C.1 C.2.2, left_inv := mk_classes_classes, right_inv := λ C, by rw [subtype.ext_iff_val, ←classes_mk_classes C.1 C.2], map_rel_iff' := λ r s, by { conv_rhs { rw [←mk_classes_classes r, ←mk_classes_classes s] }, refl } } variables {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) := galois_insertion.lift_complete_lattice $ @order_iso.to_galois_insertion _ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.order_iso α end partition /-- A finite setoid partition furnishes a finpartition -/ @[simps] def is_partition.finpartition {c : finset (set α)} (hc : setoid.is_partition (c : set (set α))) : finpartition (set.univ : set α) := { parts := c, sup_indep := finset.sup_indep_iff_pairwise_disjoint.mpr $ eqv_classes_disjoint hc.2, sup_parts := c.sup_id_set_eq_sUnion.trans hc.sUnion_eq_univ, not_bot_mem := hc.left } end setoid /-- A finpartition gives rise to a setoid partition -/ theorem finpartition.is_partition_parts {α} (f : finpartition (set.univ : set α)) : setoid.is_partition (f.parts : set (set α)) := ⟨f.not_bot_mem, setoid.eqv_classes_of_disjoint_union (f.parts.sup_id_set_eq_sUnion.symm.trans f.sup_parts) f.sup_indep.pairwise_disjoint⟩ /-- Constructive information associated with a partition of a type `α` indexed by another type `ι`, `s : ι → set α`. `indexed_partition.index` sends an element to its index, while `indexed_partition.some` sends an index to an element of the corresponding set. This type is primarily useful for definitional control of `s` - if this is not needed, then `setoid.ker index` by itself may be sufficient. -/ structure indexed_partition {ι α : Type*} (s : ι → set α) := (eq_of_mem : ∀ {x i j}, x ∈ s i → x ∈ s j → i = j) (some : ι → α) (some_mem : ∀ i, some i ∈ s i) (index : α → ι) (mem_index : ∀ x, x ∈ s (index x)) /-- The non-constructive constructor for `indexed_partition`. -/ noncomputable def indexed_partition.mk' {ι α : Type*} (s : ι → set α) (dis : ∀ i j, i ≠ j → disjoint (s i) (s j)) (nonempty : ∀ i, (s i).nonempty) (ex : ∀ x, ∃ i, x ∈ s i) : indexed_partition s := { eq_of_mem := λ x i j hxi hxj, classical.by_contradiction $ λ h, dis _ _ h ⟨hxi, hxj⟩, some := λ i, (nonempty i).some, some_mem := λ i, (nonempty i).some_spec, index := λ x, (ex x).some, mem_index := λ x, (ex x).some_spec } namespace indexed_partition open set variables {ι α : Type*} {s : ι → set α} (hs : indexed_partition s) /-- On a unique index set there is the obvious trivial partition -/ instance [unique ι] [inhabited α] : inhabited (indexed_partition (λ i : ι, (set.univ : set α))) := ⟨{ eq_of_mem := λ x i j hi hj, subsingleton.elim _ _, some := default, some_mem := set.mem_univ, index := default, mem_index := set.mem_univ }⟩ attribute [simp] some_mem mem_index include hs lemma exists_mem (x : α) : ∃ i, x ∈ s i := ⟨hs.index x, hs.mem_index x⟩ lemma Union : (⋃ i, s i) = univ := by { ext x, simp [hs.exists_mem x] } lemma disjoint : ∀ {i j}, i ≠ j → disjoint (s i) (s j) := λ i j h x ⟨hxi, hxj⟩, h (hs.eq_of_mem hxi hxj) lemma mem_iff_index_eq {x i} : x ∈ s i ↔ hs.index x = i := ⟨λ hxi, (hs.eq_of_mem hxi (hs.mem_index x)).symm, λ h, h ▸ hs.mem_index _⟩ lemma eq (i) : s i = {x | hs.index x = i} := set.ext $ λ _, hs.mem_iff_index_eq /-- The equivalence relation associated to an indexed partition. Two elements are equivalent if they belong to the same set of the partition. -/ protected abbreviation setoid (hs : indexed_partition s) : setoid α := setoid.ker hs.index @[simp] lemma index_some (i : ι) : hs.index (hs.some i) = i := (mem_iff_index_eq _).1 $ hs.some_mem i lemma some_index (x : α) : hs.setoid.rel (hs.some (hs.index x)) x := hs.index_some (hs.index x) /-- The quotient associated to an indexed partition. -/ protected def quotient := quotient hs.setoid /-- The projection onto the quotient associated to an indexed partition. -/ def proj : α → hs.quotient := quotient.mk' instance [inhabited α] : inhabited (hs.quotient) := ⟨hs.proj default⟩ lemma proj_eq_iff {x y : α} : hs.proj x = hs.proj y ↔ hs.index x = hs.index y := quotient.eq_rel @[simp] lemma proj_some_index (x : α) : hs.proj (hs.some (hs.index x)) = hs.proj x := quotient.eq'.2 (hs.some_index x) /-- The obvious equivalence between the quotient associated to an indexed partition and the indexing type. -/ def equiv_quotient : ι ≃ hs.quotient := (setoid.quotient_ker_equiv_of_right_inverse hs.index hs.some $ hs.index_some).symm @[simp] lemma equiv_quotient_index_apply (x : α) : hs.equiv_quotient (hs.index x) = hs.proj x := hs.proj_eq_iff.mpr (some_index hs x) @[simp] lemma equiv_quotient_symm_proj_apply (x : α) : hs.equiv_quotient.symm (hs.proj x) = hs.index x := rfl lemma equiv_quotient_index : hs.equiv_quotient ∘ hs.index = hs.proj := funext hs.equiv_quotient_index_apply /-- A map choosing a representative for each element of the quotient associated to an indexed partition. This is a computable version of `quotient.out'` using `indexed_partition.some`. -/ def out : hs.quotient ↪ α := hs.equiv_quotient.symm.to_embedding.trans ⟨hs.some, function.left_inverse.injective hs.index_some⟩ /-- This lemma is analogous to `quotient.mk_out'`. -/ @[simp] lemma out_proj (x : α) : hs.out (hs.proj x) = hs.some (hs.index x) := rfl /-- The indices of `quotient.out'` and `indexed_partition.out` are equal. -/ lemma index_out' (x : hs.quotient) : hs.index (x.out') = hs.index (hs.out x) := quotient.induction_on' x $ λ x, (setoid.ker_apply_mk_out' x).trans (hs.index_some _).symm /-- This lemma is analogous to `quotient.out_eq'`. -/ @[simp] lemma proj_out (x : hs.quotient) : hs.proj (hs.out x) = x := quotient.induction_on' x $ λ x, quotient.sound' $ hs.some_index x lemma class_of {x : α} : set_of (hs.setoid.rel x) = s (hs.index x) := set.ext $ λ y, eq_comm.trans hs.mem_iff_index_eq.symm lemma proj_fiber (x : hs.quotient) : hs.proj ⁻¹' {x} = s (hs.equiv_quotient.symm x) := quotient.induction_on' x $ λ x, begin ext y, simp only [set.mem_preimage, set.mem_singleton_iff, hs.mem_iff_index_eq], exact quotient.eq', end end indexed_partition
2ab6b103aef75e453c47ea39320060932695d9ce
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/pointwise/list_of_fn.lean
cba70055c1b77eae7794ced5c3f39d525a976a00
[ "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,925
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import data.set.pointwise.basic import data.list.of_fn /-! # Pointwise operations with lists of sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves some lemmas about pointwise algebraic operations with lists of sets. -/ namespace set variables {F α β γ : Type*} variables [monoid α] {s t : set α} {a : α} {m n : ℕ} open_locale pointwise @[to_additive] lemma mem_prod_list_of_fn {a : α} {s : fin n → set α} : a ∈ (list.of_fn s).prod ↔ ∃ f : (Π i : fin n, s i), (list.of_fn (λ i, (f i : α))).prod = a := begin induction n with n ih generalizing a, { simp_rw [list.of_fn_zero, list.prod_nil, fin.exists_fin_zero_pi, eq_comm, set.mem_one] }, { simp_rw [list.of_fn_succ, list.prod_cons, fin.exists_fin_succ_pi, fin.cons_zero, fin.cons_succ, mem_mul, @ih, exists_and_distrib_left, exists_exists_eq_and, set_coe.exists, subtype.coe_mk, exists_prop] } end @[to_additive] lemma mem_list_prod {l : list (set α)} {a : α} : a ∈ l.prod ↔ ∃ l' : list (Σ s : set α, ↥s), list.prod (l'.map (λ x, (sigma.snd x : α))) = a ∧ l'.map sigma.fst = l := begin induction l using list.of_fn_rec with n f, simp_rw [list.exists_iff_exists_tuple, list.map_of_fn, list.of_fn_inj', and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, function.comp, mem_prod_list_of_fn], split, { rintros ⟨fi, rfl⟩, exact ⟨λ i, ⟨_, fi i⟩, rfl, rfl⟩, }, { rintros ⟨fi, rfl, rfl⟩, exact ⟨λ i, _, rfl⟩, }, end @[to_additive] lemma mem_pow {a : α} {n : ℕ} : a ∈ s ^ n ↔ ∃ f : fin n → s, (list.of_fn (λ i, (f i : α))).prod = a := by rw [←mem_prod_list_of_fn, list.of_fn_const, list.prod_replicate] end set
2afe3d448b18765ba8bdac832ef63769ca27e274
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world06/level04.lean
f48e7bbd3e989a924f5d1af83ce0f205615b0939
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
162
lean
lemma maze (P Q R S T U: Prop) (p : P) (h : P → Q) (i : Q → R) (j : Q → T) (k : S → T) (l : T → U) : U := begin apply l, apply j, apply h, exact p, end
a5da4288bb1cb856b3442a83c454ddbfdf2afaf3
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/ring_theory/ideal/over.lean
0b8f544410ed6468dcec4663c43523f671cbb661
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
10,672
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import ring_theory.algebraic import ring_theory.localization /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end end comm_ring section integral_domain variables {S : Type*} [integral_domain S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_ne_bot_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd ((mem_bot _).mp (eq_bot_iff.mp h mem)) hi lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map _ _) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma is_maximal_of_is_integral_of_is_maximal_comap (hRS : ∀ (x : S), is_integral R x) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨ mt comap_eq_top_iff.mpr hI.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.mp (hI.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))) ⟩ lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS_integral : ∀ (x : S), is_integral R x) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS_integral) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (integral_closure.is_integral x) lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ integral_closure.comap_ne_bot lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map _ _) := let ⟨I_le_J, x, hxJ, hxI⟩ := lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (integral_closure.is_integral x) lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, integral_closure.is_integral x) I hI /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : ∀ x : S, is_integral R x) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ P = Q.comap (algebra_map R S) := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let f := localization.of P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), let g := localization.of (algebra.algebra_map_submonoid S P.prime_compl), letI : integral_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := localization_map.integral_domain_localization (le_non_zero_divisors_of_domain hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := @exists_maximal Sₚ _ (by apply_instance), haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl f g) (is_integral_localization f g H) _ Qₚ_maximal, refine ⟨comap g.to_map Qₚ, ⟨comap_is_prime g.to_map Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal.symm, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← f.map_comp _], refl end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : ∀ x : S, is_integral R x) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ P = Q.comap (algebra_map R S) := begin obtain ⟨Q' : ideal I.quotient, ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' (I.comap (algebra_map R S)).quotient _ I.quotient _ ideal.quotient_algebra (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { refine trans ((sup_eq_left.2 _).symm) (comap_map_of_surjective _ quotient.mk_surjective _).symm, simpa [← ring_hom.ker_eq_comap_bot] using hIP}, { simpa [comap_comap] }, end end integral_domain end ideal
c363485559a9dd78725dce0b5218dffacd826dd8
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Parser/Do.lean
6a72c625d519d1030409c8e1c760d1e60efc02b4
[ "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,074
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtin_doElem_parser ``Category.doElem builtin_initialize registerBuiltinDynamicParserAttribute `doElem_parser `doElem @[inline] def doElemParser (rbp : Nat := 0) : Parser := categoryParser `doElem rbp namespace Term def leftArrow : Parser := unicodeSymbol "← " "<- " @[builtin_term_parser] def liftMethod := leading_parser:minPrec leftArrow >> termParser def doSeqItem := leading_parser ppLine >> doElemParser >> optional "; " def doSeqIndent := leading_parser many1Indent doSeqItem def doSeqBracketed := leading_parser "{" >> withoutPosition (many1 doSeqItem) >> ppLine >> "}" def doSeq := withAntiquot (mkAntiquot "doSeq" decl_name% (isPseudoKind := true)) <| doSeqBracketed <|> doSeqIndent def termBeforeDo := withForbidden "do" termParser attribute [run_builtin_parser_attribute_hooks] doSeq termBeforeDo builtin_initialize register_parser_alias doSeq register_parser_alias termBeforeDo def notFollowedByRedefinedTermToken := -- Remark: we don't currently support `open` and `set_option` in `do`-blocks, -- but we include them in the following list to fix the ambiguity where -- an "open" command follows the `do`-block. -- If we don't add `do`, then users would have to indent `do` blocks or use `{ ... }`. notFollowedBy ("set_option" <|> "open" <|> "if" <|> "match" <|> "let" <|> "have" <|> "do" <|> "dbg_trace" <|> "assert!" <|> "for" <|> "unless" <|> "return" <|> symbol "try") "token at 'do' element" @[builtin_doElem_parser] def doLet := leading_parser "let " >> optional "mut " >> letDecl @[builtin_doElem_parser] def doLetElse := leading_parser "let " >> optional "mut " >> termParser >> " := " >> termParser >> checkColGt >> " | " >> doSeq @[builtin_doElem_parser] def doLetRec := leading_parser group ("let " >> nonReservedSymbol "rec ") >> letRecDecls def doIdDecl := leading_parser atomic (ident >> optType >> ppSpace >> leftArrow) >> doElemParser def doPatDecl := leading_parser atomic (termParser >> ppSpace >> leftArrow) >> doElemParser >> optional (checkColGt >> " | " >> doSeq) @[builtin_doElem_parser] def doLetArrow := leading_parser withPosition ("let " >> optional "mut " >> (doIdDecl <|> doPatDecl)) -- We use `letIdDeclNoBinders` to define `doReassign`. -- Motivation: we do not reassign functions, and avoid parser conflict def letIdDeclNoBinders := node ``letIdDecl <| atomic (ident >> pushNone >> optType >> " := ") >> termParser @[builtin_doElem_parser] def doReassign := leading_parser notFollowedByRedefinedTermToken >> (letIdDeclNoBinders <|> letPatDecl) @[builtin_doElem_parser] def doReassignArrow := leading_parser notFollowedByRedefinedTermToken >> withPosition (doIdDecl <|> doPatDecl) @[builtin_doElem_parser] def doHave := leading_parser "have " >> Term.haveDecl /- In `do` blocks, we support `if` without an `else`. Thus, we use indentation to prevent examples such as ``` if c_1 then if c_2 then action_1 else action_2 ``` from being parsed as ``` if c_1 then { if c_2 then { action_1 } else { action_2 } } ``` We also have special support for `else if` because we don't want to write ``` if c_1 then action_1 else if c_2 then action_2 else action_3 ``` -/ def elseIf := atomic (group (withPosition ("else " >> checkLineEq >> " if "))) -- ensure `if $e then ...` still binds to `e:term` def doIfLetPure := leading_parser " := " >> termParser def doIfLetBind := leading_parser " ← " >> termParser def doIfLet := leading_parser (withAnonymousAntiquot := false) "let " >> termParser >> (doIfLetPure <|> doIfLetBind) def doIfProp := leading_parser (withAnonymousAntiquot := false) optIdent >> termParser def doIfCond := withAntiquot (mkAntiquot "doIfCond" decl_name% (anonymous := false) (isPseudoKind := true)) <| doIfLet <|> doIfProp -- must reset cache as `withPositionAfterLinebreak` will look at syntax not produced by this parser (or even -- current category call) @[builtin_doElem_parser] def doIf := leading_parser withResetCache <| withPositionAfterLinebreak <| ppRealGroup <| ppRealFill (ppIndent ("if " >> doIfCond >> " then") >> ppSpace >> doSeq) >> many (checkColGe "'else if' in 'do' must be indented" >> group (ppDedent ppSpace >> ppRealFill (elseIf >> doIfCond >> " then " >> doSeq))) >> optional (checkColGe "'else' in 'do' must be indented" >> ppDedent ppSpace >> ppRealFill ("else " >> doSeq)) @[builtin_doElem_parser] def doUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq def doForDecl := leading_parser optional (atomic (ident >> " : ")) >> termParser >> " in " >> withForbidden "do" termParser /-- `for x in e do s` iterates over `e` assuming `e`'s type has an instance of the `ForIn` typeclass. `break` and `continue` are supported inside `for` loops. `for x in e, x2 in e2, ... do s` iterates of the given collections in parallel, until at least one of them is exhausted. The types of `e2` etc. must implement the `ToStream` typeclass. -/ @[builtin_doElem_parser] def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq def doMatchAlts := ppDedent <| matchAlts (rhsParser := doSeq) @[builtin_doElem_parser] def doMatch := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> optional Term.motive >> sepBy1 matchDiscr ", " >> " with " >> doMatchAlts def doCatch := leading_parser atomic ("catch " >> binderIdent) >> optional (" : " >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq @[builtin_doElem_parser] def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally /-- `break` exits the surrounding `for` loop. -/ @[builtin_doElem_parser] def doBreak := leading_parser "break" /-- `continue` skips to the next iteration of the surrounding `for` loop. -/ @[builtin_doElem_parser] def doContinue := leading_parser "continue" /-- `return e` inside of a `do` block makes the surrounding block evaluate to `pure e`, skipping any further statements. Note that uses of the `do` keyword in other syntax like in `for _ in _ do` do not constitute a surrounding block in this sense; in supported editors, the corresponding `do` keyword of the surrounding block is highlighted when hovering over `return`. `return` not followed by a term starting on the same line is equivalent to `return ()`. -/ @[builtin_doElem_parser] def doReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) @[builtin_doElem_parser] def doDbgTrace := leading_parser:leadPrec "dbg_trace " >> ((interpolatedStr termParser) <|> termParser) @[builtin_doElem_parser] def doAssert := leading_parser:leadPrec "assert! " >> termParser /- We use `notFollowedBy` to avoid counterintuitive behavior. For example, the `if`-term parser doesn't enforce indentation restrictions, but we don't want it to be used when `doIf` fails. Note that parser priorities would not solve this problem since the `doIf` parser is failing while the `if` parser is succeeding. The first `notFollowedBy` prevents this problem. Consider the `doElem` `x := (a, b⟩`. It contains an error since we are using `⟩` instead of `)`. Thus, `doReassign` parser fails. However, `doExpr` would succeed consuming just `x`, and cryptic error message is generated after that. The second `notFollowedBy` prevents this problem. -/ @[builtin_doElem_parser] def doExpr := leading_parser notFollowedByRedefinedTermToken >> termParser >> notFollowedBy (symbol ":=" <|> symbol "←" <|> symbol "<-") "unexpected token after 'expr' in 'do' block" @[builtin_doElem_parser] def doNested := leading_parser "do " >> doSeq @[builtin_term_parser] def «do» := leading_parser:argPrec ppAllowUngrouped >> "do " >> doSeq /- macros for using `unless`, `for`, `try`, `return` as terms. They expand into `do unless ...`, `do for ...`, `do try ...`, and `do return ...` -/ /-- `unless e do s` is a nicer way to write `if !e do s`. -/ @[builtin_term_parser] def termUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq @[builtin_term_parser] def termFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq @[builtin_term_parser] def termTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally /-- `return` used outside of `do` blocks creates an implicit block around it and thus is equivalent to `pure e`, but helps with avoiding parentheses. -/ @[builtin_term_parser] def termReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) end Term end Parser end Lean
6a0ce870dde68fc322e4c7cec582ff25c9c0cb75
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/limits/over.lean
e4da1bd1aa7b195102a436b9f2b4959b23f55fbe
[ "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
13,729
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import category_theory.comma import category_theory.pempty import category_theory.limits.connected import category_theory.limits.creates import category_theory.limits.shapes.constructions.limits_of_products_and_equalizers import category_theory.limits.shapes.constructions.equalizers universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory category_theory.limits variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variable {X : C} namespace category_theory.functor @[simps] def to_cocone (F : J ⥤ over X) : cocone (F ⋙ over.forget) := { X := X, ι := { app := λ j, (F.obj j).hom } } @[simps] def to_cone (F : J ⥤ under X) : cone (F ⋙ under.forget) := { X := X, π := { app := λ j, (F.obj j).hom } } end category_theory.functor namespace category_theory.over @[simps] def colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : cocone F := { X := mk $ colimit.desc (F ⋙ forget) F.to_cocone, ι := { app := λ j, hom_mk $ colimit.ι (F ⋙ forget) j, naturality' := begin intros j j' f, have := colimit.w (F ⋙ forget) f, tidy end } } def forget_colimit_is_colimit (F : J ⥤ over X) [has_colimit (F ⋙ forget)] : is_colimit (forget.map_cocone (colimit F)) := is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ forget)) (cocones.ext (iso.refl _) (by tidy)) instance : reflects_colimits (forget : over X ⥤ C) := { reflects_colimits_of_shape := λ J 𝒥, { reflects_colimit := λ F, by constructor; exactI λ t ht, { desc := λ s, hom_mk (ht.desc (forget.map_cocone s)) begin apply ht.hom_ext, intro j, rw [←category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.ι.app j), -- TODO: How to write (s.ι.app j).w? exact (w (t.ι.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac (forget.map_cocone s) j -- TODO: Ask Simon about multiple ext lemmas for defeq types (comma_morphism & over.category.hom) end, uniq' := begin intros s m w, ext1 j, exact ht.uniq (forget.map_cocone s) m.left (λ j, congr_arg comma_morphism.left (w j)) end } } } instance has_colimit {F : J ⥤ over X} [has_colimit (F ⋙ forget)] : has_colimit F := { cocone := colimit F, is_colimit := reflects_colimit.reflects (forget_colimit_is_colimit F) } instance has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (over X) := { has_colimit := λ F, by apply_instance } instance has_colimits [has_colimits.{v} C] : has_colimits.{v} (over X) := { has_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_colimits [has_colimits.{v} C] {X : C} : preserves_colimits (forget : over X ⥤ C) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (forget_colimit_is_colimit F) } } namespace construct_products /-- (Impl) Given a product shape in `C/B`, construct the corresponding wide pullback diagram in `C`. -/ @[reducible] def wide_pullback_diagram_of_diagram_over (B : C) {J : Type v} (F : discrete J ⥤ over B) : wide_pullback_shape J ⥤ C := wide_pullback_shape.wide_cospan B (λ j, (F.obj j).left) (λ j, (F.obj j).hom) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse_obj (B : C) {J : Type v} (F : discrete J ⥤ over B) (c : cone F) : cone (wide_pullback_diagram_of_diagram_over B F) := { X := c.X.left, π := { app := λ X, option.cases_on X c.X.hom (λ (j : J), (c.π.app j).left), -- `tidy` can do this using `case_bash`, but let's try to be a good `-T50000` citizen: naturality' := λ X Y f, begin dsimp, cases X; cases Y; cases f, { rw [category.id_comp, category.comp_id], }, { rw [over.w, category.id_comp], }, { rw [category.id_comp, category.comp_id], }, end } } /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_inverse (B : C) {J : Type v} (F : discrete J ⥤ over B) : cone F ⥤ cone (wide_pullback_diagram_of_diagram_over B F) := { obj := cones_equiv_inverse_obj B F, map := λ c₁ c₂ f, { hom := f.hom.left, w' := λ j, begin cases j, { simp }, { dsimp, rw ← f.w j, refl } end } } /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simps] def cones_equiv_functor (B : C) {J : Type v} (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ⥤ cone F := { obj := λ c, { X := over.mk (c.π.app none), π := { app := λ j, over.hom_mk (c.π.app (some j)) (by apply c.w (wide_pullback_shape.hom.term j)) } }, map := λ c₁ c₂ f, { hom := over.hom_mk f.hom } } local attribute [tidy] tactic.case_bash /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_unit_iso (B : C) {J : Type v} (F : discrete J ⥤ over B) : 𝟭 (cone (wide_pullback_diagram_of_diagram_over B F)) ≅ cones_equiv_functor B F ⋙ cones_equiv_inverse B F := nat_iso.of_components (λ _, cones.ext {hom := 𝟙 _, inv := 𝟙 _} (by tidy)) (by tidy) /-- (Impl) A preliminary definition to avoid timeouts. -/ @[simp] def cones_equiv_counit_iso (B : C) {J : Type v} (F : discrete J ⥤ over B) : cones_equiv_inverse B F ⋙ cones_equiv_functor B F ≅ 𝟭 (cone F) := nat_iso.of_components (λ _, cones.ext {hom := over.hom_mk (𝟙 _), inv := over.hom_mk (𝟙 _)} (by tidy)) (by tidy) -- TODO: Can we add `. obviously` to the second arguments of `nat_iso.of_components` and `cones.ext`? /-- (Impl) Establish an equivalence between the category of cones for `F` and for the "grown" `F`. -/ @[simps] def cones_equiv (B : C) {J : Type v} (F : discrete J ⥤ over B) : cone (wide_pullback_diagram_of_diagram_over B F) ≌ cone F := { functor := cones_equiv_functor B F, inverse := cones_equiv_inverse B F, unit_iso := cones_equiv_unit_iso B F, counit_iso := cones_equiv_counit_iso B F, } /-- Use the above equivalence to prove we have a limit. -/ def has_over_limit_discrete_of_wide_pullback_limit {B : C} {J : Type v} (F : discrete J ⥤ over B) [has_limit (wide_pullback_diagram_of_diagram_over B F)] : has_limit F := { cone := _, is_limit := is_limit.of_cone_equiv (cones_equiv B F).symm (limit.is_limit (wide_pullback_diagram_of_diagram_over B F)) } /-- Given a wide pullback in `C`, construct a product in `C/B`. -/ def over_product_of_wide_pullback {J : Type v} [has_limits_of_shape.{v} (wide_pullback_shape J) C] {B : C} : has_limits_of_shape.{v} (discrete J) (over B) := { has_limit := λ F, has_over_limit_discrete_of_wide_pullback_limit F } /-- Given a pullback in `C`, construct a binary product in `C/B`. -/ def over_binary_product_of_pullback [has_pullbacks.{v} C] {B : C} : has_binary_products.{v} (over B) := { has_limits_of_shape := over_product_of_wide_pullback } /-- Given all wide pullbacks in `C`, construct products in `C/B`. -/ def over_products_of_wide_pullbacks [has_wide_pullbacks.{v} C] {B : C} : has_products.{v} (over B) := { has_limits_of_shape := λ J, over_product_of_wide_pullback } /-- Given all finite wide pullbacks in `C`, construct finite products in `C/B`. -/ def over_finite_products_of_finite_wide_pullbacks [has_finite_wide_pullbacks.{v} C] {B : C} : has_finite_products.{v} (over B) := { has_limits_of_shape := λ J 𝒥₁ 𝒥₂, by exactI over_product_of_wide_pullback } end construct_products /-- Construct terminal object in the over category. -/ instance (B : C) : has_terminal.{v} (over B) := { has_limits_of_shape := { has_limit := λ F, { cone := { X := over.mk (𝟙 _), π := { app := λ p, pempty.elim p } }, is_limit := { lift := λ s, over.hom_mk _, fac' := λ _ j, j.elim, uniq' := λ s m _, begin ext, rw over.hom_mk_left, have := m.w, dsimp at this, rwa [category.comp_id, category.comp_id] at this end } } } } namespace creates_connected /-- (Impl) Given a diagram in the over category, produce a natural transformation from the diagram legs to the specific object. -/ def nat_trans_in_over {B : C} (F : J ⥤ over B) : F ⋙ forget ⟶ (category_theory.functor.const J).obj B := { app := λ j, (F.obj j).hom } local attribute [tidy] tactic.case_bash /-- (Impl) Given a cone in the base category, raise it to a cone in the over category. Note this is where the connected assumption is used. -/ @[simps] def raise_cone [connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget)) : cone F := { X := over.mk (c.π.app (default J) ≫ (F.obj (default J)).hom), π := { app := λ j, over.hom_mk (c.π.app j) (nat_trans_from_connected (c.π ≫ nat_trans_in_over F) j) } } lemma raised_cone_lowers_to_original [connected J] {B : C} {F : J ⥤ over B} (c : cone (F ⋙ forget)) (t : is_limit c) : forget.map_cone (raise_cone c) = c := by tidy /-- (Impl) Show that the raised cone is a limit. -/ def raised_cone_is_limit [connected J] {B : C} {F : J ⥤ over B} {c : cone (F ⋙ forget)} (t : is_limit c) : is_limit (raise_cone c) := { lift := λ s, over.hom_mk (t.lift (forget.map_cone s)) (by { dsimp, simp }), uniq' := λ s m K, by { ext1, apply t.hom_ext, intro j, simp [← K j] } } end creates_connected /-- The forgetful functor from the over category creates any connected limit. -/ instance forget_creates_connected_limits [connected J] {B : C} : creates_limits_of_shape J (forget : over B ⥤ C) := { creates_limit := λ K, creates_limit_of_reflects_iso (λ c t, { lifted_cone := creates_connected.raise_cone c, valid_lift := eq_to_iso (creates_connected.raised_cone_lowers_to_original c t), makes_limit := creates_connected.raised_cone_is_limit t } ) } /-- The over category has any connected limit which the original category has. -/ instance has_connected_limits {B : C} [connected J] [has_limits_of_shape J C] : has_limits_of_shape J (over B) := { has_limit := λ F, has_limit_of_created F (forget : over B ⥤ C) } /-- Make sure we can derive pullbacks in `over B`. -/ example {B : C} [has_pullbacks.{v} C] : has_pullbacks.{v} (over B) := { has_limits_of_shape := infer_instance } /-- Make sure we can derive equalizers in `over B`. -/ example {B : C} [has_equalizers.{v} C] : has_equalizers.{v} (over B) := { has_limits_of_shape := infer_instance } instance has_finite_limits {B : C} [has_finite_wide_pullbacks.{v} C] : has_finite_limits.{v} (over B) := begin apply @finite_limits_from_equalizers_and_finite_products _ _ _ _, { exact construct_products.over_finite_products_of_finite_wide_pullbacks }, { apply @has_equalizers_of_pullbacks_and_binary_products _ _ _ _, { haveI: has_pullbacks.{v} C := ⟨infer_instance⟩, exact construct_products.over_binary_product_of_pullback }, { split, apply_instance} } end instance has_limits {B : C} [has_wide_pullbacks.{v} C] : has_limits.{v} (over B) := begin apply @limits_from_equalizers_and_products _ _ _ _, { exact construct_products.over_products_of_wide_pullbacks }, { apply @has_equalizers_of_pullbacks_and_binary_products _ _ _ _, { haveI: has_pullbacks.{v} C := ⟨infer_instance⟩, exact construct_products.over_binary_product_of_pullback }, { split, apply_instance } } end end category_theory.over namespace category_theory.under @[simps] def limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : cone F := { X := mk $ limit.lift (F ⋙ forget) F.to_cone, π := { app := λ j, hom_mk $ limit.π (F ⋙ forget) j, naturality' := begin intros j j' f, have := (limit.w (F ⋙ forget) f).symm, tidy end } } def forget_limit_is_limit (F : J ⥤ under X) [has_limit (F ⋙ forget)] : is_limit (forget.map_cone (limit F)) := is_limit.of_iso_limit (limit.is_limit (F ⋙ forget)) (cones.ext (iso.refl _) (by tidy)) instance : reflects_limits (forget : under X ⥤ C) := { reflects_limits_of_shape := λ J 𝒥, { reflects_limit := λ F, by constructor; exactI λ t ht, { lift := λ s, hom_mk (ht.lift (forget.map_cone s)) begin apply ht.hom_ext, intro j, rw [category.assoc, ht.fac], transitivity (F.obj j).hom, exact w (s.π.app j), exact (w (t.π.app j)).symm, end, fac' := begin intros s j, ext, exact ht.fac (forget.map_cone s) j end, uniq' := begin intros s m w, ext1 j, exact ht.uniq (forget.map_cone s) m.right (λ j, congr_arg comma_morphism.right (w j)) end } } } instance has_limit {F : J ⥤ under X} [has_limit (F ⋙ forget)] : has_limit F := { cone := limit F, is_limit := reflects_limit.reflects (forget_limit_is_limit F) } instance has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (under X) := { has_limit := λ F, by apply_instance } instance has_limits [has_limits.{v} C] : has_limits.{v} (under X) := { has_limits_of_shape := λ J 𝒥, by resetI; apply_instance } instance forget_preserves_limits [has_limits.{v} C] {X : C} : preserves_limits (forget : under X ⥤ C) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (forget_limit_is_limit F) } } end category_theory.under
5829588b7afc088431510f32083aba93d585872f
ff5230333a701471f46c57e8c115a073ebaaa448
/tests/lean/run/1797.lean
cdd45d979dab7ee3b7c26651bfc5f890620babf3
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
144
lean
example (n : nat) : true := begin cases h : n with m, { guard_hyp h := n = nat.zero, admit }, { guard_hyp h := n = nat.succ m, admit} end
8045980ba7b47b7ccd6b6aa88bb712b823198815
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/ring_theory/ideals.lean
48a4d4e76cbd96f679108ce540bd27c4494fbd1a
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
21,262
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.basic import order.zorn universes u v variables {α : Type u} {β : Type v} {a b : α} open set function open_locale classical big_operators namespace ideal variables [comm_ring α] (I : ideal α) @[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⟩ := is_unit_iff_exists_inv'.1 h 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 /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s 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_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton 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} [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_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] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, singleton_one, span_singleton_one, eq_top_iff] 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 mul_dvd_of_is_unit_right 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] /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ @[class] def is_prime (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I 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.2 (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, { exact (mt (eq_top_iff_one _).2 hI.1).elim H }, exact or.cases_on (hI.mem_or_mem H) id ih 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 theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton] /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ @[class] def is_maximal (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤ theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := 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.2 _ h)⟩ theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I := 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, hy⟩, rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy, exact ⟨-y, hy⟩ end theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin cases H.exists_inv hx with z hz, have := I.mul_mem_left hz, rw [mul_sub, mul_one, mul_comm, mul_assoc] at this, exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this) 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 theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := begin rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩, { refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩, cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ }, { intros S SC cC I IS, refine ⟨Sup S, λ H, _, λ _, le_Sup⟩, obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J, from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H), exact SC JS ((eq_top_iff_one _).2 J0) } 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_ring 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] lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ y ≠ 0 ∧ ∃ d : β, ¬ is_unit d ∧ x = y * d := 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 [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] /-- The quotient `R/I` of a ring `R` by an ideal `I`. -/ 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 refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _ ... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂), rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] 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⟩ 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⟩⟩ 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.comm_ring I, .. quotient.nontrivial hI.1 } lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb, rw [mul_comm] at hb, exact ⟨mk _ b, quot.sound hb⟩ end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ 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.integral_domain I } 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 end quotient section lattice variables {R : Type u} [comm_ring R] 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⟩ end lattice /-- All ideals in a field are trivial. -/ lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) : I = ⊥ ∨ I = ⊤ := begin rw classical.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 submodule.smul_mem I r⁻¹ hr, end lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] : I = ⊥ := classical.or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal {K : Type u} [field K] : 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 /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [comm_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 [comm_ring α] {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_ring α] (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 section prio set_option default_priority 100 -- see Note [default priority] /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (α : Type u) [comm_ring α] extends nontrivial α : Prop := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) end prio namespace local_ring variables [comm_ring α] [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal α := { carrier := nonunits α, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.smul_mem ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨maximal_ideal α, maximal_ideal.is_maximal α, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal α).1 $ λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} lemma eq_maximal_ideal {I : ideal α} (hI : I.is_maximal) : I = maximal_ideal α := unique_of_exists_unique (maximal_ideal_unique α) hI $ maximal_ideal.is_maximal α lemma le_maximal_ideal {J : ideal α} (hJ : J ≠ ⊤) : J ≤ maximal_ideal α := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring lemma local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨hPnot_top, _⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end section prio set_option default_priority 100 -- see Note [default priority] /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) end prio @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring α] [semiring β] (f : α →+* β) [h : is_local_ring_hom f] {x : α} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.1 $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.2 _ _ $ f.map_mul p q ▸ congr_arg f hx⟩ section open local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ maximal_ideal α) : f a ∈ maximal_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variable (α) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := (maximal_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (maximal_ideal α) noncomputable instance : inhabited (residue_field α) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk _ namespace residue_field variables {α β} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (maximal_ideal α) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h } end field