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
55d24fa87e6290f4c5c95e2ed948ee190879fecf
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/casesUsing.lean
0dbe9edda3fedf76a38ba4435ab95ba439dcbbb8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
4,713
lean
import Lean open Lean open Lean.Meta open Lean.Elab.Tactic universe u axiom elimEx (motive : Nat → Nat → Sort u) (x y : Nat) (diag : (a : Nat) → motive a a) (upper : (delta a : Nat) → motive a (a + delta.succ)) (lower : (delta a : Nat) → motive (a + delta.succ) a) : motive y x theorem ex1 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => apply Or.inl; apply Nat.le_refl | lower d => apply Or.inl; show p ≤ p + d.succ; admit | upper d => apply Or.inr; show q + d.succ > q; admit theorem ex2 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx case lower => admit case upper => admit case diag => apply Or.inl; apply Nat.le_refl axiom Nat.parityElim (motive : Nat → Sort u) (even : (n : Nat) → motive (2*n)) (odd : (n : Nat) → motive (2*n+1)) (n : Nat) : motive n theorem time2Eq (n : Nat) : 2*n = n + n := by rw [Nat.mul_comm] show (0 + n) + n = n+n simp theorem ex3 (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by cases n using Nat.parityElim with | even i => apply Exists.intro i apply Or.inl rw [time2Eq] | odd i => apply Exists.intro i apply Or.inr rw [time2Eq] open Nat in theorem ex3b (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by cases n using parityElim with | even i => apply Exists.intro i apply Or.inl rw [time2Eq] | odd i => apply Exists.intro i apply Or.inr rw [time2Eq] def ex4 {α} (xs : List α) (h : xs = [] → False) : α := by cases he:xs with | nil => contradiction | cons x _ => exact x def ex5 {α} (xs : List α) (h : xs = [] → False) : α := by cases he:xs using List.casesOn with | nil => contradiction | cons x _ => exact x theorem ex6 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := match he:f xs with | true => False.elim (h₂ (h₁ he)) | false => rfl theorem ex7 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by cases he:f xs with | true => exact False.elim (h₂ (h₁ he)) | false => rfl theorem ex8 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by cases he:f xs using Bool.casesOn with | true => exact False.elim (h₂ (h₁ he)) | false => rfl theorem ex9 (xs : List α) (h : xs = [] → False) : Nonempty α := by cases xs using List.rec with | nil => contradiction | cons x _ => apply Nonempty.intro; assumption theorem modLt (x : Nat) {y : Nat} (h : y > 0) : x % y < y := by induction x, y using Nat.mod.inductionOn with | ind x y h₁ ih => rw [Nat.mod_eq_sub_mod h₁.2] exact ih h | base x y h₁ => match Iff.mp (Decidable.not_and_iff_or_not ..) h₁ with | Or.inl h₁ => contradiction | Or.inr h₁ => have hgt := Nat.gt_of_not_le h₁ have heq := Nat.mod_eq_of_lt hgt rw [← heq] at hgt assumption theorem ex11 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using Or.casesOn with | inr h => ?myright | inl h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem ex12 {p q : Prop } (h : p ∨ q) : q ∨ p := by cases h using Or.casesOn with | inr h => ?myright | inl h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem ex13 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => ?hlower | upper d => ?hupper case hdiag => apply Or.inl; apply Nat.le_refl case hlower => apply Or.inl; show p ≤ p + d.succ; admit case hupper => apply Or.inr; show q + d.succ > q; admit theorem ex14 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => _ | upper d => ?hupper case hdiag => apply Or.inl; apply Nat.le_refl case lower => apply Or.inl; show p ≤ p + d.succ; admit case hupper => apply Or.inr; show q + d.succ > q; admit theorem ex15 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => _ | upper d => ?hupper { apply Or.inl; apply Nat.le_refl } { apply Or.inr; show q + d.succ > q; admit } { apply Or.inl; show p ≤ p + d.succ; admit } theorem ex16 {p q : Prop} (h : p ∨ q) : q ∨ p := by induction h case inl h' => exact Or.inr h' case inr h' => exact Or.inl h' theorem ex17 (n : Nat) : 0 + n = n := by induction n case zero => rfl case succ m ih => show Nat.succ (0 + m) = Nat.succ m rw [ih]
25c9937b7a71433f20a180f50d9e6379e812f676
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/tests/lean/match3.lean
38f35af958e48a00695fe1cc807a87ed53df41a0
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,015
lean
def f (x : Nat) : Nat := match x with | 30 => 31 | y+1 => y | 0 => 10 #eval f 20 #eval f 0 #eval f 30 universes u theorem ex1 {α : Sort u} {a b : α} (h : a ≅ b) : a = b := match α, a, b, h with | _, _, _, HEq.refl _ => rfl theorem ex2 {α : Sort u} {a b : α} (h : a ≅ b) : a = b := match a, b, h with | _, _, HEq.refl _ => rfl theorem ex3 {α : Sort u} {a b : α} (h : a ≅ b) : a = b := match b, h with | _, HEq.refl _ => rfl theorem ex4 {α β : Sort u} {b : β} {a a' : α} (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := match β, a', b, h₁, h₂ with | _, _, _, rfl, HEq.refl _ => HEq.refl _ theorem ex5 {α β : Sort u} {b : β} {a a' : α} (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := match a', h₁, h₂ with | _, rfl, h₂ => h₂ theorem ex6 {α β : Sort u} {b : β} {a a' : α} (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := by { subst h₁; assumption } theorem ex7 (a : Bool) (p q : Prop) (h₁ : a = true → p) (h₂ : a = false → q) : p ∨ q := match h:a with | true => Or.inl $ h₁ h | false => Or.inr $ h₂ h def head {α} (xs : List α) (h : xs = [] → False) : α := match he:xs with | [] => False.elim $ h he | x::_ => x variables {α : Type u} {p : α → Prop} theorem ex8 {a1 a2 : {x // p x}} (h : a1.val = a2.val) : a1 = a2 := match a1, a2, h with | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl universes v variables {β : α → Type v} theorem ex9 {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1) (h : p₁.2 ≅ p₂.2) : p₁ = p₂ := match p₁, p₂, h₁, h with | ⟨_, _⟩, ⟨_, _⟩, rfl, HEq.refl _ => rfl inductive F : Nat → Type | z : {n : Nat} → F (n+1) | s : {n : Nat} → F n → F (n+1) def f0 {α : Sort u} (x : F 0) : α := nomatch x def f1 {α : Sort u} (x : F 0 × Bool) : α := nomatch x def f2 {α : Sort u} (x : Sum (F 0) (F 0)) : α := nomatch x def f3 {α : Sort u} (x : Bool × F 0) : α := nomatch x def f4 (x : Sum (F 0 × Bool) Nat) : Nat := match x with | Sum.inr x => x #eval f4 $ Sum.inr 100
e99f935a738b25b98f78d430194807c0a32d5bbf
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/big_operators/fin.lean
6ecf74c21daaa37b5044e2dde7b3dcd88a5de861
[ "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
11,623
lean
/- Copyright (c) 2020 Yury Kudryashov, Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Anne Baanen -/ import data.fintype.card import data.fintype.fin import logic.equiv.fin /-! # Big operators and `fin` Some results about products and sums over the type `fin`. The most important results are the induction formulas `fin.prod_univ_cast_succ` and `fin.prod_univ_succ`, and the formula `fin.prod_const` for the product of a constant function. These results have variants for sums instead of products. -/ open_locale big_operators open finset variables {α : Type*} {β : Type*} namespace finset @[to_additive] theorem prod_range [comm_monoid β] {n : ℕ} (f : ℕ → β) : ∏ i in finset.range n, f i = ∏ i : fin n, f i := prod_bij' (λ k w, ⟨k, mem_range.mp w⟩) (λ a ha, mem_univ _) (λ a ha, congr_arg _ (fin.coe_mk _).symm) (λ a m, a) (λ a m, mem_range.mpr a.prop) (λ a ha, fin.coe_mk _) (λ a ha, fin.eta _ _) end finset namespace fin @[to_additive] theorem prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) : ∏ i, f i = ((list.fin_range n).map f).prod := by simp [univ_def] @[to_additive] theorem prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) : (list.of_fn f).prod = ∏ i, f i := by rw [list.of_fn_eq_map, prod_univ_def] /-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/ @[to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"] theorem prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/ @[to_additive /- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/] theorem prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) := by rw [univ_succ_above, prod_cons, finset.prod_map, rel_embedding.coe_fn_to_embedding] /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f 0` plus the remaining product -/ @[to_additive /- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f 0` plus the remaining product -/] theorem prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := prod_univ_succ_above f 0 /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f (fin.last n)` plus the remaining product -/ @[to_additive /- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f (fin.last n)` plus the remaining sum -/] theorem prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (last n) := by simpa [mul_comm] using prod_univ_succ_above f (last n) @[to_additive] lemma prod_cons [comm_monoid β] {n : ℕ} (x : β) (f : fin n → β) : ∏ i : fin n.succ, (cons x f : fin n.succ → β) i = x * ∏ i : fin n, f i := by simp_rw [prod_univ_succ, cons_zero, cons_succ] @[to_additive sum_univ_one] theorem prod_univ_one [comm_monoid β] (f : fin 1 → β) : ∏ i, f i = f 0 := by simp @[simp, to_additive] theorem prod_univ_two [comm_monoid β] (f : fin 2 → β) : ∏ i, f i = f 0 * f 1 := by simp [prod_univ_succ] @[to_additive] theorem prod_univ_three [comm_monoid β] (f : fin 3 → β) : ∏ i, f i = f 0 * f 1 * f 2 := by { rw [prod_univ_cast_succ, prod_univ_two], refl } @[to_additive] theorem prod_univ_four [comm_monoid β] (f : fin 4 → β) : ∏ i, f i = f 0 * f 1 * f 2 * f 3 := by { rw [prod_univ_cast_succ, prod_univ_three], refl } @[to_additive] theorem prod_univ_five [comm_monoid β] (f : fin 5 → β) : ∏ i, f i = f 0 * f 1 * f 2 * f 3 * f 4 := by { rw [prod_univ_cast_succ, prod_univ_four], refl } @[to_additive] theorem prod_univ_six [comm_monoid β] (f : fin 6 → β) : ∏ i, f i = f 0 * f 1 * f 2 * f 3 * f 4 * f 5 := by { rw [prod_univ_cast_succ, prod_univ_five], refl } @[to_additive] theorem prod_univ_seven [comm_monoid β] (f : fin 7 → β) : ∏ i, f i = f 0 * f 1 * f 2 * f 3 * f 4 * f 5 * f 6 := by { rw [prod_univ_cast_succ, prod_univ_six], refl } @[to_additive] theorem prod_univ_eight [comm_monoid β] (f : fin 8 → β) : ∏ i, f i = f 0 * f 1 * f 2 * f 3 * f 4 * f 5 * f 6 * f 7 := by { rw [prod_univ_cast_succ, prod_univ_seven], refl } lemma sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b lemma prod_const [comm_monoid α] (n : ℕ) (x : α) : ∏ i : fin n, x = x ^ n := by simp lemma sum_const [add_comm_monoid α] (n : ℕ) (x : α) : ∑ i : fin n, x = n • x := by simp @[to_additive] lemma prod_Ioi_zero {M : Type*} [comm_monoid M] {n : ℕ} {v : fin n.succ → M} : ∏ i in Ioi 0, v i = ∏ j : fin n, v j.succ := by rw [Ioi_zero_eq_map, finset.prod_map, rel_embedding.coe_fn_to_embedding, coe_succ_embedding] @[to_additive] lemma prod_Ioi_succ {M : Type*} [comm_monoid M] {n : ℕ} (i : fin n) (v : fin n.succ → M) : ∏ j in Ioi i.succ, v j = ∏ j in Ioi i, v j.succ := by rw [Ioi_succ, finset.prod_map, rel_embedding.coe_fn_to_embedding, coe_succ_embedding] @[to_additive] lemma prod_congr' {M : Type*} [comm_monoid M] {a b : ℕ} (f : fin b → M) (h : a = b) : ∏ (i : fin a), f (cast h i) = ∏ (i : fin b), f i := by { subst h, congr, ext, congr, ext, rw coe_cast, } @[to_additive] lemma prod_univ_add {M : Type*} [comm_monoid M] {a b : ℕ} (f : fin (a+b) → M) : ∏ (i : fin (a+b)), f i = (∏ (i : fin a), f (cast_add b i)) * ∏ (i : fin b), f (nat_add a i) := begin rw fintype.prod_equiv fin_sum_fin_equiv.symm f (λ i, f (fin_sum_fin_equiv.to_fun i)), swap, { intro x, simp only [equiv.to_fun_as_coe, equiv.apply_symm_apply], }, apply prod_on_sum, end @[to_additive] lemma prod_trunc {M : Type*} [comm_monoid M] {a b : ℕ} (f : fin (a+b) → M) (hf : ∀ (j : fin b), f (nat_add a j) = 1) : ∏ (i : fin (a+b)), f i = ∏ (i : fin a), f (cast_le (nat.le.intro rfl) i) := by simpa only [prod_univ_add, fintype.prod_eq_one _ hf, mul_one] section partial_prod variables [monoid α] {n : ℕ} /-- For `f = (a₁, ..., aₙ)` in `αⁿ`, `partial_prod f` is `(1, a₁, a₁a₂, ..., a₁...aₙ)` in `αⁿ⁺¹`. -/ @[to_additive "For `f = (a₁, ..., aₙ)` in `αⁿ`, `partial_sum f` is `(0, a₁, a₁ + a₂, ..., a₁ + ... + aₙ)` in `αⁿ⁺¹`."] def partial_prod (f : fin n → α) (i : fin (n + 1)) : α := ((list.of_fn f).take i).prod @[simp, to_additive] lemma partial_prod_zero (f : fin n → α) : partial_prod f 0 = 1 := by simp [partial_prod] @[to_additive] lemma partial_prod_succ (f : fin n → α) (j : fin n) : partial_prod f j.succ = partial_prod f j.cast_succ * (f j) := by simp [partial_prod, list.take_succ, list.of_fn_nth_val, dif_pos j.is_lt, ←option.coe_def] @[to_additive] lemma partial_prod_succ' (f : fin (n + 1) → α) (j : fin (n + 1)) : partial_prod f j.succ = f 0 * partial_prod (fin.tail f) j := by simpa [partial_prod] @[to_additive] lemma partial_prod_left_inv {G : Type*} [group G] (f : fin (n + 1) → G) : f 0 • partial_prod (λ i : fin n, (f i)⁻¹ * f i.succ) = f := funext $ λ x, fin.induction_on x (by simp) (λ x hx, begin simp only [coe_eq_cast_succ, pi.smul_apply, smul_eq_mul] at hx ⊢, rw [partial_prod_succ, ←mul_assoc, hx, mul_inv_cancel_left], end) @[to_additive] lemma partial_prod_right_inv {G : Type*} [group G] (g : G) (f : fin n → G) (i : fin n) : ((g • partial_prod f) i)⁻¹ * (g • partial_prod f) i.succ = f i := begin cases i with i hn, induction i with i hi generalizing hn, { simp [←fin.succ_mk, partial_prod_succ] }, { specialize hi (lt_trans (nat.lt_succ_self i) hn), simp only [mul_inv_rev, fin.coe_eq_cast_succ, fin.succ_mk, fin.cast_succ_mk, smul_eq_mul, pi.smul_apply] at hi ⊢, rw [←fin.succ_mk _ _ (lt_trans (nat.lt_succ_self _) hn), ←fin.succ_mk], simp only [partial_prod_succ, mul_inv_rev, fin.cast_succ_mk], assoc_rw [hi, inv_mul_cancel_left] } end end partial_prod end fin namespace list section comm_monoid variables [comm_monoid α] @[to_additive] lemma prod_take_of_fn {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ ((j : ℕ) < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), ((j : ℕ) < i.succ) = ((j : ℕ) < i), { assume j, have : (j : ℕ) < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end @[to_additive] lemma prod_of_fn {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), (j : ℕ) < n := λ j, j.is_lt, simp [this] } end end comm_monoid lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.is_lt | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := by simp | (g :: h :: L) := calc g + -h + L.alternating_sum = g + -h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) • list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
e1775726c5d47f72c2a981b2cc612456d074fd8c
618003631150032a5676f229d13a079ac875ff77
/src/algebra/gcd_domain.lean
f72d7d692851eeefb058a951ddecf5528df07562
[ "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
26,328
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker GCD domain and integral domains with normalization functions TODO: abstract the domains to to semi domains (i.e. domains on semirings) to include ℕ and ℕ[X] etc. -/ import algebra.associated import data.nat.basic import data.int.gcd variables {α : Type*} set_option old_structure_cmd true section prio set_option default_priority 100 -- see Note [default priority] /-- Normalization domain: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_domain (α : Type*) extends integral_domain α := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) end prio export normalization_domain (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_domain variable [normalization_domain α] def normalize (x : α) : α := x * norm_unit x theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by rw [normalize, zero_mul] @[simp] lemma normalize_one : normalize (1 : α) = 1 := by rw [normalize, norm_unit_one, units.coe_one, mul_one] lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by rw [normalize, norm_unit_coe_units, ← units.coe_mul, mul_inv_self, units.coe_one] theorem normalize_mul (x y : α) : normalize (x * y) = normalize x * normalize y := classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, normalize_zero, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, normalize_zero, mul_zero]) $ λ hy, by simp only [normalize, norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y] lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.coe_ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by rw [normalize, normalize, norm_unit_mul_norm_unit, units.coe_one, mul_one] theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize, mul_assoc, norm_unit_mul ha u.coe_ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨dvd_mul_unit_iff.1 ⟨_, h.symm⟩, dvd_mul_unit_iff.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba @[simp] lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := dvd_mul_unit_iff @[simp] lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := mul_unit_dvd_iff end normalization_domain namespace associates variable [normalization_domain α] local attribute [instance] associated.setoid protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (mul_unit_dvd_iff.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates section prio set_option default_priority 100 -- see Note [default priority] /-- GCD domain: an integral domain with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the correpsonding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_domain (α : Type*) extends normalization_domain α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) end prio export gcd_domain (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_domain variables [gcd_domain α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_domain.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_domain.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.coe_ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize_mul, normalize_gcd, one_mul, domain.mul_right_inj h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd (units.coe_dvd _ _) (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) end lcm end gcd_domain namespace int section normalization_domain instance : normalization_domain ℤ := { norm_unit := λa:ℤ, if 0 ≤ a then 1 else -1, norm_unit_zero := if_pos (le_refl _), norm_unit_mul := assume a b hna hnb, begin by_cases ha : 0 ≤ a; by_cases hb : 0 ≤ b; simp [ha, hb], exact if_pos (mul_nonneg ha hb), exact if_neg (assume h, hb $ nonneg_of_mul_nonneg_left h $ lt_of_le_of_ne ha hna.symm), exact if_neg (assume h, ha $ nonneg_of_mul_nonneg_right h $ lt_of_le_of_ne hb hnb.symm), exact if_pos (mul_nonneg_of_nonpos_of_nonpos (le_of_not_ge ha) (le_of_not_ge hb)) end, norm_unit_coe_units := assume u, (units_eq_one_or u).elim (assume eq, eq.symm ▸ if_pos zero_le_one) (assume eq, eq.symm ▸ if_neg (not_le_of_gt $ show (-1:ℤ) < 0, by simp [@neg_lt ℤ _ 1 0])), .. (infer_instance : integral_domain ℤ) } lemma normalize_of_nonneg {z : ℤ} (h : 0 ≤ z) : normalize z = z := show z * ↑(ite _ _ _) = z, by rw [if_pos h, units.coe_one, mul_one] lemma normalize_of_neg {z : ℤ} (h : z < 0) : normalize z = -z := show z * ↑(ite _ _ _) = -z, by rw [if_neg (not_le_of_gt h), units.coe_neg, units.coe_one, mul_neg_one] lemma normalize_coe_nat (n : ℕ) : normalize (n : ℤ) = n := normalize_of_nonneg (coe_nat_le_coe_nat_of_le $ nat.zero_le n) theorem coe_nat_abs_eq_normalize (z : ℤ) : (z.nat_abs : ℤ) = normalize z := begin by_cases 0 ≤ z, { simp [nat_abs_of_nonneg h, normalize_of_nonneg h] }, { simp [of_nat_nat_abs_of_nonpos (le_of_not_ge h), normalize_of_neg (lt_of_not_ge h)] } end end normalization_domain /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl section gcd_domain theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] instance : gcd_domain ℤ := { gcd := λa b, int.gcd a b, lcm := λa b, int.lcm a b, gcd_dvd_left := assume a b, int.gcd_dvd_left _ _, gcd_dvd_right := assume a b, int.gcd_dvd_right _ _, dvd_gcd := assume a b c, dvd_gcd, normalize_gcd := assume a b, normalize_coe_nat _, gcd_mul_lcm := by intros; rw [← int.coe_nat_mul, gcd_mul_lcm, coe_nat_abs_eq_normalize], lcm_zero_left := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_left _, lcm_zero_right := assume a, coe_nat_eq_zero.2 $ nat.lcm_zero_right _, .. int.normalization_domain } lemma coe_gcd (i j : ℤ) : ↑(int.gcd i j) = gcd_domain.gcd i j := rfl lemma coe_lcm (i j : ℤ) : ↑(int.lcm i j) = gcd_domain.lcm i j := rfl lemma nat_abs_gcd (i j : ℤ) : nat_abs (gcd_domain.gcd i j) = int.gcd i j := rfl lemma nat_abs_lcm (i j : ℤ) : nat_abs (gcd_domain.lcm i j) = int.lcm i j := rfl end gcd_domain theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_gcd, coe_nat_abs_eq_normalize] theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := by rw [← int.coe_nat_eq_coe_nat_iff, int.coe_nat_zero, coe_gcd, gcd_eq_zero_iff] theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] /- lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_comm] theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, lcm_assoc] @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm] @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by simp [(int.coe_nat_eq_coe_nat_iff _ _).symm, coe_lcm, coe_nat_abs_eq_normalize] theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_left _ _ theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by rw [coe_lcm]; exact dvd_lcm_right _ _ theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := by rw [coe_lcm]; exact lcm_dvd end int theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_right_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt nat.is_unit_iff.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ def associates_int_equiv_nat : associates ℤ ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on' a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), show normalize a = int.nat_abs (normalize a), rw [int.coe_nat_abs_eq_normalize, normalize_idem] }, { assume n, show int.nat_abs (normalize n) = n, rw [← int.coe_nat_abs_eq_normalize, int.nat_abs_of_nat, int.nat_abs_of_nat] } end
ca326bc1a62557291b227169b1a5cc839a6548ec
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/subst_tac1.lean
22a681465ca3713d48879c79bd9516edae69cf8f
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
371
lean
constant p : nat → Prop open tactic set_option pp.all true definition ex (a b c : nat) (H : p c) : a = b → p a → p b := by do intro `H1, intro `H2, get_local `a >>= subst, trace_state, assumption print ex example (a b c : nat) (H : p c) : a = b → p a → p b := by do intros, get_local `b >>= subst, trace_state, assumption
0efa94d6efba3a78f31db48f9ac10d5262657f0f
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/PointedTimesZeroMagma.lean
e3a2a4d4115feb4ddc0615f47b13ff54134e32c9
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
7,530
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section PointedTimesZeroMagma structure PointedTimesZeroMagma (A : Type) : Type := (zero : A) (times : (A → (A → A))) open PointedTimesZeroMagma structure Sig (AS : Type) : Type := (zeroS : AS) (timesS : (AS → (AS → AS))) structure Product (A : Type) : Type := (zeroP : (Prod A A)) (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) structure Hom {A1 : Type} {A2 : Type} (Po1 : (PointedTimesZeroMagma A1)) (Po2 : (PointedTimesZeroMagma A2)) : Type := (hom : (A1 → A2)) (pres_zero : (hom (zero Po1)) = (zero Po2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Po1) x1 x2)) = ((times Po2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Po1 : (PointedTimesZeroMagma A1)) (Po2 : (PointedTimesZeroMagma A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_zero : (interp (zero Po1) (zero Po2))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Po1) x1 x2) ((times Po2) y1 y2)))))) inductive PointedTimesZeroMagmaTerm : Type | zeroL : PointedTimesZeroMagmaTerm | timesL : (PointedTimesZeroMagmaTerm → (PointedTimesZeroMagmaTerm → PointedTimesZeroMagmaTerm)) open PointedTimesZeroMagmaTerm inductive ClPointedTimesZeroMagmaTerm (A : Type) : Type | sing : (A → ClPointedTimesZeroMagmaTerm) | zeroCl : ClPointedTimesZeroMagmaTerm | timesCl : (ClPointedTimesZeroMagmaTerm → (ClPointedTimesZeroMagmaTerm → ClPointedTimesZeroMagmaTerm)) open ClPointedTimesZeroMagmaTerm inductive OpPointedTimesZeroMagmaTerm (n : ℕ) : Type | v : ((fin n) → OpPointedTimesZeroMagmaTerm) | zeroOL : OpPointedTimesZeroMagmaTerm | timesOL : (OpPointedTimesZeroMagmaTerm → (OpPointedTimesZeroMagmaTerm → OpPointedTimesZeroMagmaTerm)) open OpPointedTimesZeroMagmaTerm inductive OpPointedTimesZeroMagmaTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpPointedTimesZeroMagmaTerm2) | sing2 : (A → OpPointedTimesZeroMagmaTerm2) | zeroOL2 : OpPointedTimesZeroMagmaTerm2 | timesOL2 : (OpPointedTimesZeroMagmaTerm2 → (OpPointedTimesZeroMagmaTerm2 → OpPointedTimesZeroMagmaTerm2)) open OpPointedTimesZeroMagmaTerm2 def simplifyCl {A : Type} : ((ClPointedTimesZeroMagmaTerm A) → (ClPointedTimesZeroMagmaTerm A)) | zeroCl := zeroCl | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpPointedTimesZeroMagmaTerm n) → (OpPointedTimesZeroMagmaTerm n)) | zeroOL := zeroOL | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpPointedTimesZeroMagmaTerm2 n A) → (OpPointedTimesZeroMagmaTerm2 n A)) | zeroOL2 := zeroOL2 | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((PointedTimesZeroMagma A) → (PointedTimesZeroMagmaTerm → A)) | Po zeroL := (zero Po) | Po (timesL x1 x2) := ((times Po) (evalB Po x1) (evalB Po x2)) def evalCl {A : Type} : ((PointedTimesZeroMagma A) → ((ClPointedTimesZeroMagmaTerm A) → A)) | Po (sing x1) := x1 | Po zeroCl := (zero Po) | Po (timesCl x1 x2) := ((times Po) (evalCl Po x1) (evalCl Po x2)) def evalOpB {A : Type} {n : ℕ} : ((PointedTimesZeroMagma A) → ((vector A n) → ((OpPointedTimesZeroMagmaTerm n) → A))) | Po vars (v x1) := (nth vars x1) | Po vars zeroOL := (zero Po) | Po vars (timesOL x1 x2) := ((times Po) (evalOpB Po vars x1) (evalOpB Po vars x2)) def evalOp {A : Type} {n : ℕ} : ((PointedTimesZeroMagma A) → ((vector A n) → ((OpPointedTimesZeroMagmaTerm2 n A) → A))) | Po vars (v2 x1) := (nth vars x1) | Po vars (sing2 x1) := x1 | Po vars zeroOL2 := (zero Po) | Po vars (timesOL2 x1 x2) := ((times Po) (evalOp Po vars x1) (evalOp Po vars x2)) def inductionB {P : (PointedTimesZeroMagmaTerm → Type)} : ((P zeroL) → ((∀ (x1 x2 : PointedTimesZeroMagmaTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : PointedTimesZeroMagmaTerm) , (P x)))) | p0l ptimesl zeroL := p0l | p0l ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB p0l ptimesl x1) (inductionB p0l ptimesl x2)) def inductionCl {A : Type} {P : ((ClPointedTimesZeroMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P zeroCl) → ((∀ (x1 x2 : (ClPointedTimesZeroMagmaTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClPointedTimesZeroMagmaTerm A)) , (P x))))) | psing p0cl ptimescl (sing x1) := (psing x1) | psing p0cl ptimescl zeroCl := p0cl | psing p0cl ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing p0cl ptimescl x1) (inductionCl psing p0cl ptimescl x2)) def inductionOpB {n : ℕ} {P : ((OpPointedTimesZeroMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P zeroOL) → ((∀ (x1 x2 : (OpPointedTimesZeroMagmaTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpPointedTimesZeroMagmaTerm n)) , (P x))))) | pv p0ol ptimesol (v x1) := (pv x1) | pv p0ol ptimesol zeroOL := p0ol | pv p0ol ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv p0ol ptimesol x1) (inductionOpB pv p0ol ptimesol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpPointedTimesZeroMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P zeroOL2) → ((∀ (x1 x2 : (OpPointedTimesZeroMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpPointedTimesZeroMagmaTerm2 n A)) , (P x)))))) | pv2 psing2 p0ol2 ptimesol2 (v2 x1) := (pv2 x1) | pv2 psing2 p0ol2 ptimesol2 (sing2 x1) := (psing2 x1) | pv2 psing2 p0ol2 ptimesol2 zeroOL2 := p0ol2 | pv2 psing2 p0ol2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 p0ol2 ptimesol2 x1) (inductionOp pv2 psing2 p0ol2 ptimesol2 x2)) def stageB : (PointedTimesZeroMagmaTerm → (Staged PointedTimesZeroMagmaTerm)) | zeroL := (Now zeroL) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClPointedTimesZeroMagmaTerm A) → (Staged (ClPointedTimesZeroMagmaTerm A))) | (sing x1) := (Now (sing x1)) | zeroCl := (Now zeroCl) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpPointedTimesZeroMagmaTerm n) → (Staged (OpPointedTimesZeroMagmaTerm n))) | (v x1) := (const (code (v x1))) | zeroOL := (Now zeroOL) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpPointedTimesZeroMagmaTerm2 n A) → (Staged (OpPointedTimesZeroMagmaTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | zeroOL2 := (Now zeroOL2) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (zeroT : (Repr A)) (timesT : ((Repr A) → ((Repr A) → (Repr A)))) end PointedTimesZeroMagma
61dd1d047704c74c4cf33a51e078a607c4d0476e
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/bvm.lean
2bb60e9890f49e62039f9dcf4ab91b1991347d40
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
127,107
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import order.complete_boolean_algebra order.zorn .pSet_ordinal .bv_tauto local infix ` ⟹ `:65 := lattice.imp local infix ` ⇔ `:50 := lattice.biimp -- uncomment in case of emergency -- @[tidy] meta def big_bertha : tactic unit := `[finish] namespace lattice section natded variables {𝔹 : Type*} [complete_boolean_algebra 𝔹] lemma supr_imp_eq {ι : Type*} {s : ι → 𝔹} {b : 𝔹} : (⨆(i:ι), s i) ⟹ b = (⨅(i:ι), s i ⟹ b) := by {unfold imp, rw[neg_supr, infi_sup_eq]} lemma imp_infi_eq {ι : Type*} {s : ι → 𝔹} {b : 𝔹} : (b ⟹ (⨅i, s i)) = (⨅i, b ⟹ s i) := by {unfold imp, rw[sup_infi_eq]} lemma bv_Or_elim {ι : Type*} {s : ι → 𝔹} {c : 𝔹} : (∀ i : ι, (s i ≤ c)) → ((⨆(i:ι), s i) ≤ c) := λ H, by apply supr_le; from H lemma bv_And_intro {ι : Type*} {s : ι → 𝔹} {b c : 𝔹} : (∀ i : ι, (c ≤ s i)) → (c ≤ ⨅(i:ι), s i) := λ H, by {apply le_infi, from H} -- this is superceded by tactic.interactive.bv_intro lemma bv_or_elim {b₁ b₂ c : 𝔹} {h : b₁ ≤ c} {h' : b₂ ≤ c} : b₁ ⊔ b₂ ≤ c := by apply sup_le; assumption lemma bv_or_elim_left {b₁ b₂ c d : 𝔹} {h₁ : b₁ ⊓ d ≤ c} {h₂ : b₂ ⊓ d ≤ c} : (b₁ ⊔ b₂) ⊓ d ≤ c := by {rw[deduction], apply bv_or_elim; rw[<-deduction]; from ‹_›} lemma bv_or_elim_right {b₁ b₂ c d : 𝔹} {h₁ : d ⊓ b₁ ≤ c} {h₂ : d ⊓ b₂ ≤ c} : d ⊓ (b₁ ⊔ b₂) ≤ c := by {rw[inf_comm] at ⊢ h₁ h₂; apply bv_or_elim_left; assumption} lemma bv_exfalso {a b : 𝔹} (h : a ≤ ⊥) : a ≤ b := le_trans h bot_le lemma bv_cases_left {ι : Type*} {s : ι → 𝔹} {c b : 𝔹} {h : ∀ i : ι, (s i ⊓ c ≤ b)} : ((⨆(i:ι), s i) ⊓ c) ≤ b := by {rw[deduction], apply supr_le, intro i, rw[<-deduction], revert i, from ‹_›} lemma bv_cases_right {ι : Type*} {s : ι → 𝔹} {c b : 𝔹} {h : ∀ i : ι, (c ⊓ s i ≤ b)} : (c ⊓ (⨆(i:ι), s i)) ≤ b := by {rw[inf_comm], apply bv_cases_left, simpa only [inf_comm]} lemma bv_specialize {ι : Type*} {s : ι → 𝔹} (i : ι) {b : 𝔹} {h : s i ≤ b} : (⨅(i:ι), s i) ≤ b := infi_le_of_le i h --TODO(jesse) write the version of this for an arbitrary list of instantiations lemma bv_specialize_twice {ι : Type*} {s : ι → 𝔹} (i j : ι) {b : 𝔹} {h : s i ⊓ s j ≤ b} : (⨅(i:ι), s i) ≤ b := begin apply le_trans', apply infi_le, from i, apply le_trans', apply inf_le_left_of_le, apply infi_le, from j, apply le_trans _ h, apply inf_le_inf, apply inf_le_right, refl end lemma bv_specialize_left {ι : Type*} {s : ι → 𝔹} {c b : 𝔹} (i : ι) {h : s i ⊓ c ≤ b} : (⨅(i:ι), s i) ⊓ c ≤ b := by {rw[deduction], apply bv_specialize i, rwa[<-deduction]} lemma bv_specialize_left_twice {ι : Type*} {s : ι → 𝔹} {c b : 𝔹} (i j : ι) {h : s i ⊓ s j ⊓ c ≤ b} : (⨅(i:ι), s i) ⊓ c ≤ b := begin rw[deduction], apply bv_specialize_twice i j, rwa[<-deduction] end lemma bv_specialize_right {ι : Type*} {s :ι → 𝔹} {c b : 𝔹} (i : ι) {h : c ⊓ s i ≤ b} : c ⊓ (⨅(i:ι), s i) ≤ b := by {rw[inf_comm], apply bv_specialize_left i, rwa[inf_comm]} lemma bv_specialize_right_twice {ι : Type*} {s : ι → 𝔹} {c b : 𝔹} (i j : ι) {h : c ⊓ (s i ⊓ s j) ≤ b} : c ⊓ (⨅(i:ι), s i) ≤ b := begin rw[inf_comm], apply bv_specialize_left_twice i j, rwa[<-inf_comm] end lemma bv_imp_elim {a b : 𝔹} : (a ⟹ b) ⊓ a ≤ b := by simp[imp, inf_sup_right] lemma bv_imp_elim' {a b : 𝔹} : (a ⟹ b) ⊓ a ≤ a ⊓ b := by {simp[imp, inf_sup_right]} lemma bv_cancel_antecedent {a b c : 𝔹} (h : b ≤ c) : a ⟹ b ≤ a ⟹ c := by {rw[<-deduction], apply le_trans, apply bv_imp_elim, from ‹_›} lemma bv_imp_iff {Γ b₁ b₂ : 𝔹} : Γ ≤ b₁ ⟹ b₂ ↔ (∀ {Γ'} (H_le : Γ' ≤ Γ), Γ' ≤ b₁ → Γ' ≤ b₂) := begin refine ⟨_,_⟩; intro H, { intros Γ' H_le H', rw ←deduction at H, exact le_trans (le_inf ‹_› ‹_›) H }, { bv_imp_intro H', apply H, { dsimp[Γ_1], from inf_le_right }, { from ‹_› } } end lemma bv_biimp_iff {b₁ b₂ : 𝔹} {Γ : 𝔹} : (Γ ≤ (b₁ ⇔ b₂)) ↔ (∀ {Γ'} (H_le : Γ' ≤ Γ), Γ' ≤ b₁ ↔ Γ' ≤ b₂) := begin refine ⟨_,_⟩; intro H, { bv_split_at H, intros Γ' H_le, refine ⟨_,_⟩, { rw bv_imp_iff at *, solve_by_elim }, { rw bv_imp_iff at *, solve_by_elim }}, { refine le_inf _ _, { rw bv_imp_iff, intros, exact (H ‹_›).mp ‹_› }, { rw bv_imp_iff, intros, exact (H ‹_›).mpr ‹_› }} end -- example {a b c : 𝔹} (h : b ≤ c) : a ⟹ b ≤ a ⟹ c := -- by {tidy_context, bv_imp_intro, apply (poset_yoneda_inv _ h), from a_1 ‹_›} lemma bv_and_intro {a b₁ b₂ : 𝔹} (h₁ : a ≤ b₁) (h₂ : a ≤ b₂) : a ≤ b₁ ⊓ b₂ := le_inf h₁ h₂ lemma bv_or_left {a b₁ b₂ : 𝔹} (h₁ : a ≤ b₁) : a ≤ b₁ ⊔ b₂ := le_sup_left_of_le h₁ lemma bv_or_right {a b₁ b₂ : 𝔹} (h₂ : a ≤ b₂) : a ≤ b₁ ⊔ b₂ := le_sup_right_of_le h₂ lemma bv_and.left {a b : 𝔹} {Γ} (H : Γ ≤ a ⊓ b) : Γ ≤ a := le_trans H inf_le_left lemma bv_and.right {a b : 𝔹} {Γ} (H : Γ ≤ a ⊓ b) : Γ ≤ b := le_trans H inf_le_right lemma from_empty_context {a b : 𝔹} (h : ⊤ ≤ b) : a ≤ b := by refine le_trans _ h; apply le_top lemma bv_imp_intro {a b c : 𝔹} {h : a ⊓ b ≤ c} : a ≤ b ⟹ c := by rwa[deduction] at h lemma bv_have {a b c : 𝔹} (h : a ≤ b) {h' : a ⊓ b ≤ c} : a ≤ c := by {rw[(inf_self.symm : a = _)], apply le_trans, apply inf_le_inf, refl, exact h, exact h'} lemma bv_have_true {a b c : 𝔹} (h₁ : ⊤ ≤ b) (h₂ : a ⊓ b ≤ c) : a ≤ c := by {rw[top_le_iff] at h₁, rw[h₁] at h₂, from le_trans (by rw[inf_top_eq]) h₂} lemma bv_use {ι} (i : ι) {s : ι → 𝔹} {b : 𝔹} {h : b ≤ s i} : b ≤ ⨆(j:ι), s j := le_supr_of_le i h lemma bv_context_apply {β : Type*} [complete_boolean_algebra β] {Γ a₁ a₂ : β} (h₁ : Γ ≤ a₁ ⟹ a₂) (h₂ : Γ ≤ a₁) : Γ ≤ a₂ := h₁ ‹_› lemma bv_Or_imp {Γ : 𝔹} {ι} {ϕ₁ ϕ₂ : ι → 𝔹} (H_sub : Γ ≤ ⨅ x, ϕ₁ x ⟹ ϕ₂ x) (H : Γ ≤ ⨆x, ϕ₁ x) : Γ ≤ ⨆x, ϕ₂ x := by {bv_cases_at H x, apply bv_use x, from H_sub x ‹_›} lemma bv_iff.neg {b₁ b₂ : 𝔹} (H : ∀{Γ}, Γ ≤ b₁ ↔ Γ ≤ b₂) : ∀ {Γ}, Γ ≤ -(b₁) ↔ Γ ≤ -(b₂) := begin intro Γ, refine ⟨_,_⟩; intro H', { apply bv_by_contra, bv_imp_intro H_contra, rw lattice.neg_neg at H_contra, rw ←imp_bot at H', refine H' _, rwa H }, { apply bv_by_contra, bv_imp_intro H_contra, rw lattice.neg_neg at H_contra, rw ←imp_bot at H', refine H' _, rwa ←H } end end natded end lattice open lattice universe u namespace pSet /-- If two pre-sets `x` and `y` are not equivalent, then either there exists a member of x which is not equivalent to any member of y, or there exists a member of y which is not equivalent to any member of x -/ lemma not_equiv {x y : pSet} (h_neq : ¬ pSet.equiv x y) : (∃ a : x.type, ∀ a' : y.type, ¬ pSet.equiv (x.func a) (y.func a')) ∨ (∃ a' : y.type, ∀ a : x.type, ¬ pSet.equiv (x.func a) (y.func a')) := begin cases x, cases y, unfold equiv, safe, suffices : equiv (mk x_α x_A) (mk y_α y_A), by contradiction, constructor; assumption end end pSet /- A 𝔹-valued model of ZFC -/ -- τ is a B-name if and only if τ is a set of pairs of the form ⟨σ, b⟩, where σ is -- a B-name and b ∈ B. inductive bSet (𝔹 : Type u) [complete_boolean_algebra 𝔹] : Type (u+1) | mk (α : Type u) (A : α → bSet) (B : α → 𝔹) : bSet namespace bSet variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] noncomputable instance decidable_eq_𝔹 : decidable_eq 𝔹 := λ _ _, classical.prop_decidable _ run_cmd mk_simp_attr `cleanup /-- The underlying type of a bSet -/ @[simp, cleanup]def type : bSet 𝔹 → Type u | ⟨α, _, _⟩ := α @[simp, cleanup]lemma type_infi {α : Type*} {A : α → bSet 𝔹} {B C : α → 𝔹} : (⨅(a : type (mk α A B)), C a) = ⨅(a : α), C a := rfl @[simp, cleanup]lemma type_supr {α : Type*} {A : α → bSet 𝔹} {B C : α → 𝔹} : (⨆(a : type (mk α A B)), C a) = ⨆(a : α), C a := rfl /-- The indexing function of a bSet -/ @[simp, cleanup]def func : ∀ x : bSet 𝔹, x.type → bSet 𝔹 | ⟨_, A, _⟩ := A /-- The boolean truth-value function of a bSet -/ @[simp, cleanup]def bval : ∀ x : bSet 𝔹, x.type → 𝔹 | ⟨_, _, B⟩ := B @[simp, cleanup]def mk_type_func_bval : ∀ x : bSet 𝔹, mk x.type x.func x.bval = x := λ x, by cases x; refl def empty : bSet 𝔹 := ⟨ulift empty, empty.elim ∘ ulift.down, empty.elim ∘ ulift.down⟩ instance nonempty_bSet : nonempty $ @bSet 𝔹 _ := ⟨empty⟩ instance has_empty_bSet : has_emptyc (bSet 𝔹) := ⟨empty⟩ @[simp]lemma forall_over_empty (ϕ : (type (∅ : bSet 𝔹)) → 𝔹) : (⨅a, ϕ a) = ⊤ := by {apply top_unique, bv_intro a, repeat{cases a}} @[simp]lemma exists_over_empty (ϕ : (type (∅ : bSet 𝔹)) → 𝔹) : (⨆a, ϕ a) = ⊥ := by {apply bot_unique, apply bv_Or_elim, intro i, repeat{cases i}} /-- Two Boolean-valued pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def bv_eq : ∀ (x y : bSet 𝔹), 𝔹 | ⟨α, A, B⟩ ⟨α', A', B'⟩ := (⨅a : α, B a ⟹ ⨆a', B' a' ⊓ bv_eq (A a) (A' a')) ⊓ (⨅a' : α', B' a' ⟹ ⨆a, B a ⊓ bv_eq (A a) (A' a')) infix ` =ᴮ `:79 := bv_eq -- note: for every Γ : 𝔹, λ x y, Γ ≤ x =ᴮ y is an equivalence relation def bv_eq' (Γ : 𝔹) : bSet 𝔹 → bSet 𝔹 → Prop := λ x y, Γ ≤ x=ᴮ y example : (@bv_eq 𝔹 _) (empty) (empty) = ⊤ := by unfold empty bv_eq; {simp only [lattice.inf_eq_top_iff, lattice.infi_eq_top], fsplit; intros i; cases i; cases i} open lattice @[simp]theorem bv_eq_refl : ∀ x, @bv_eq 𝔹 _ x x = ⊤ := begin intro x, induction x, simp[bv_eq, -imp_top_iff_le], split; intros; {apply top_unique, simp only [lattice.top_le_iff, lattice.imp_top_iff_le], apply le_supr_of_le i, have := x_ih i, simp[this]} end @[simp]lemma bv_refl {Γ : 𝔹} {x} : Γ ≤ x =ᴮ x := le_trans le_top (by simp) @[simp]lemma bv_eq_top_of_eq {x y : bSet 𝔹} (h_eq : x = y) : x =ᴮ y = ⊤ := by simp* /- empty' is the singleton bSet {⟨∅, ⊥⟩}, i.e. a set whose only member is ∅ which has a zero probability of actually being an element. It should be equivalent to ∅. -/ @[reducible]def empty' : bSet 𝔹 := mk punit (λ _, ∅) (λ _, ⊥) example : empty =ᴮ empty = (⊤ : 𝔹) := by simp example : ⊤ ≤ empty =ᴮ (empty' : bSet 𝔹) := by simp[empty, empty', bv_eq]; exact dec_trivial /-- `x ∈ y` as Boolean-valued pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ def mem : bSet 𝔹 → bSet 𝔹 → 𝔹 | a (mk α' A' B') := ⨆a', B' a' ⊓ a =ᴮ A' a' @[reducible]def empty'' : bSet 𝔹 := mk (ulift bool) (λ x, ∅) (λ x, by {repeat{cases x}, exact ⊥, exact ⊤}) infix ` ∈ᴮ `:80 := mem lemma mem_unfold {u v : bSet 𝔹} : u ∈ᴮ v = ⨆(i : v.type), v.bval i ⊓ u =ᴮ v.func i := by cases v; simp[mem,bv_eq] /-- ∅ appears in empty'' with probability 0 and 1, with the higher probability winning the vote of membership. This demonstrates why the inequality in the following theorem is necessary. -/ example : ∅ ∈ᴮ empty'' = (⊤ : 𝔹) := by {apply top_unique, apply le_supr_of_le ⊤, swap, exact ⟨⟨(tt)⟩⟩, simp} theorem mem.mk {α : Type*} (A : α → bSet 𝔹) (B : α → 𝔹) (a : α) : B a ≤ A a ∈ᴮ mk α A B := le_supr_of_le a $ by simp theorem mem.mk' (x : bSet 𝔹) (a : x.type) : x.bval a ≤ x.func a ∈ᴮ x := by cases x; from mem.mk _ _ _ -- the Γ-generalized version of mem.mk uses two primes because mem.mk' already existed @[simp]theorem mem.mk'' {x : bSet 𝔹} {a : x.type} {Γ} : Γ ≤ x.bval a → Γ ≤ x.func a ∈ᴮ x := poset_yoneda_inv Γ (mem.mk' x a) @[reducible]protected def subset : bSet 𝔹 → bSet 𝔹 → 𝔹 | (mk α A B) b := ⨅a:α, B a ⟹ (A a ∈ᴮ b) infix ` ⊆ᴮ `:80 := bSet.subset lemma subset_unfold {x u : bSet 𝔹} : x ⊆ᴮ u = (⨅(j : x.type), x.bval j ⟹ x.func j ∈ᴮ u) := by induction x; dsimp[bSet.subset]; congr @[simp]protected def insert : bSet 𝔹 → 𝔹 → bSet 𝔹 → bSet 𝔹 | u b ⟨α, A, B⟩ := ⟨option α, λo, option.rec u A o, λo, option.rec b B o⟩ protected def insert' : bSet 𝔹 → 𝔹 → bSet 𝔹 → bSet 𝔹 | u b ⟨α, A, B⟩ := ⟨unit ⊕ α, λ o, sum.rec (λ_, u) A o, λ o, sum.rec (λ_, b) B o⟩ @[reducible]protected def insert1 : bSet 𝔹 → bSet 𝔹 → bSet 𝔹 | u v := bSet.insert u ⊤ v lemma insert1_unfold {u v : bSet 𝔹} : bSet.insert1 u v = ⟨option v.type, λo, option.rec u v.func o, λ o, option.rec ⊤ v.bval o⟩ := by {induction v, simp[bSet.insert1]} -- @[simp]lemma insert1_type {u v : bSet 𝔹} : (bSet.insert1 u v).type = option v.type := by simp[insert1_unfold] instance insert_bSet : has_insert (bSet 𝔹) (bSet 𝔹) := ⟨λ u v, bSet.insert1 u v⟩ @[simp]lemma insert_unfold {y z : bSet 𝔹} : insert y z = bSet.insert y ⊤ z := by refl @[simp]theorem mem_insert {x y z : bSet 𝔹} {b : 𝔹} : x ∈ᴮ bSet.insert y b z = (b ⊓ x =ᴮ y) ⊔ x ∈ᴮ z := by induction y; induction z; simp[bv_eq,mem] @[simp]theorem mem_insert1 {x y z : bSet 𝔹} : x ∈ᴮ insert y z = x =ᴮ y ⊔ x ∈ᴮ z := by simp @[simp]theorem mem_insert1' { x y z : bSet 𝔹 } { Γ : 𝔹 } : Γ ≤ x ∈ᴮ insert y z ↔ Γ ≤ x =ᴮ y ⊔ x ∈ᴮ z := by simp -- example : {∅} =ᴮ empty'' = (⊤ : 𝔹) := -- begin -- simp[empty'', singleton, insert, has_insert.insert,mem,bv_eq], -- simp[has_emptyc.emptyc, empty,bSet.insert1], -- refine ⟨_, by intro i; repeat{cases i}⟩, apply top_unique, -- have : ⊤ = (ulift.rec (bool.rec ⊥ ⊤) : ulift bool → 𝔹) (ulift.up tt), -- by refl, -- rw[this], apply le_supr -- end theorem bv_eq_symm {x y : bSet 𝔹} : x =ᴮ y = y =ᴮ x := begin induction x with α A B generalizing y, induction y with α' A' B', suffices : ∀ a : α, ∀ a' : α', A' a' =ᴮ A a = A a =ᴮ A' a', by {simp[bv_eq, this, inf_comm]}, from λ _ _, by simp[x_ih ‹α›] end theorem bv_eq_unfold (x y : bSet 𝔹) : x =ᴮ y = (⨅(a : x.type), x.bval a ⟹ (x.func a ∈ᴮ y)) ⊓ (⨅(a' : y.type), (y.bval a' ⟹ (y.func a' ∈ᴮ x))) := by induction x; induction y; simp[mem,bv_eq,bv_eq_symm] theorem bSet_axiom_of_extensionality (x y : bSet 𝔹) : (⨅(z : bSet 𝔹), (z ∈ᴮ x ⟹ z ∈ᴮ y) ⊓ (z ∈ᴮ y ⟹ z ∈ᴮ x)) ≤ x =ᴮ y := begin rw[bv_eq_unfold], apply le_inf; apply le_infi; intro i, {fapply infi_le_of_le (x.func i), apply inf_le_left_of_le, induction x, unfold mem, simp only with cleanup, by apply imp_le_of_left_le; apply le_supr_of_le i; exact le_inf (by refl) (by rw[bv_eq_refl]; apply le_top)}, {fapply infi_le_of_le (y.func i), apply inf_le_right_of_le, induction y, unfold mem, simp only with cleanup, by apply imp_le_of_left_le; apply le_supr_of_le i; exact le_inf (by refl) (by rw[bv_eq_refl]; apply le_top)}, end lemma eq_of_subset_subset (x y : bSet 𝔹) : x ⊆ᴮ y ⊓ y ⊆ᴮ x ≤ x =ᴮ y := begin simp[subset_unfold, bv_eq_unfold], tidy; [apply inf_le_left_of_le, apply inf_le_right_of_le]; apply bv_specialize i; refl end lemma subset_subset_of_eq (x y : bSet 𝔹) : x =ᴮ y ≤ x ⊆ᴮ y ⊓ y ⊆ᴮ x := begin simp[subset_unfold, bv_eq_unfold], tidy; [apply inf_le_left_of_le, apply inf_le_right_of_le]; apply bv_specialize i; refl end theorem eq_iff_subset_subset {x y : bSet 𝔹} : x =ᴮ y = x ⊆ᴮ y ⊓ y ⊆ᴮ x := by apply le_antisymm; [apply subset_subset_of_eq, apply eq_of_subset_subset] lemma subset_subset_of_eq' {x y : bSet 𝔹} {Γ} (H : Γ ≤ x =ᴮ y) : Γ ≤ x ⊆ᴮ y ∧ Γ ≤ y ⊆ᴮ x := by {rw[eq_iff_subset_subset] at H, bv_split, exact ⟨‹_›,‹_›⟩} lemma subset_of_eq {x y} {Γ : 𝔹} (H : Γ ≤ x =ᴮ y) : Γ ≤ x ⊆ᴮ y := (subset_subset_of_eq' H).left @[simp]lemma subset_self {x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ x ⊆ᴮ x := by { apply le_trans, apply le_top, rw[show ⊤ = x =ᴮ x, by simp[bv_eq_refl]], rw[eq_iff_subset_subset], exact inf_le_left } theorem subset_ext {x y : bSet 𝔹} {Γ : 𝔹} (h₁ : Γ ≤ x ⊆ᴮ y) (h₂ : Γ ≤ y ⊆ᴮ x) : Γ ≤ x =ᴮ y := begin apply bv_have h₂, rw[deduction], apply bv_have h₁, rw[<-deduction], ac_change Γ ⊓ (x ⊆ᴮ y ⊓ y ⊆ᴮ x) ≤ x =ᴮ y, apply inf_le_right_of_le, apply eq_of_subset_subset end theorem bv_eq_trans {x y z : bSet 𝔹} : (x =ᴮ y ⊓ y =ᴮ z) ≤ x =ᴮ z := begin induction x with α A B generalizing y z, cases y with α' A' B', induction z with α'' A'' B'', have H1 : ∀ a : α, ∀ a' : α', ∀ a'' : α'', (((A a =ᴮ A' a') ⊓ (A' a' =ᴮ A'' a'')) ⊓ B'' a'') ≤ (A a =ᴮ A'' a'' ⊓ B'' a''), by {intros a a' a'', refine inf_le_inf _ (by refl), exact @x_ih a (A' a') (A'' a'')}, have H2 : ∀ i'' : α'', ∀ a' : α', ∀ a : α, A'' i'' =ᴮ A' a' ⊓ A' a' =ᴮ A a ⊓ B a ≤ A'' i'' =ᴮ A a ⊓ B a, by {intros a'' a' a, refine inf_le_inf _ (by refl), convert @x_ih a (A' a') (A'' a'') using 1; simp[bv_eq_symm], ac_refl}, apply le_inf, {bv_intro i, apply deduction.mp, change _ ≤ (A i) ∈ᴮ ⟨α'', A'', B''⟩, have this1 : ⟨α, A, B⟩ =ᴮ ⟨α', A', B'⟩ ⊓ B i ≤ A i ∈ᴮ ⟨α', A', B'⟩, by {rw[deduction], from inf_le_left_of_le (infi_le _ _)}, suffices : A i ∈ᴮ ⟨α', A', B'⟩ ⊓ ⟨α', A', B'⟩ =ᴮ ⟨α'', A'', B''⟩ ≤ A i ∈ᴮ ⟨α'', A'', B''⟩, by {have := le_trans (inf_le_inf this1 (by refl)) this, convert this using 1, ac_refl }, suffices : ∀ a', ⟨α', A', B'⟩ =ᴮ ⟨α'', A'', B''⟩ ⊓ A i =ᴮ A' a' ⊓ B' a' ≤ A i ∈ᴮ ⟨α'', A'', B''⟩, by {convert (supr_le this) using 1, simp[mem, inf_comm, inf_supr_eq], congr, ext, ac_refl}, have this2 : ∀ a', ⟨α', A', B'⟩ =ᴮ ⟨α'', A'', B''⟩ ⊓ B' a' ≤ A' a' ∈ᴮ ⟨α'', A'', B''⟩, by {intro a', rw[deduction], apply inf_le_left_of_le, apply infi_le}, suffices : ∀ a', A i =ᴮ A' a' ⊓ A' a' ∈ᴮ ⟨α'', A'', B''⟩ ≤ A i ∈ᴮ ⟨α'', A'', B''⟩, by {intro a', have := le_trans (inf_le_inf (by refl) (this2 a')) (this a'), convert this using 1, ac_refl}, intro a', erw[inf_supr_eq], apply supr_le, intro a'', conv {to_lhs, congr, skip, rw[inf_comm]}, suffices : A i =ᴮ A' a' ⊓ (A' a' =ᴮ A'' a'' ⊓ B'' a'') = A i =ᴮ A' a' ⊓ A' a' =ᴮ A'' a'' ⊓ B'' a'', by {rw[this], clear this, apply le_trans, exact (H1 i a' a''), apply le_supr_of_le a'', rw[inf_comm]}, ac_refl}, {bv_intro i'', apply deduction.mp, conv {to_rhs, congr, funext, rw[bv_eq_symm]}, change _ ≤ (A'' i'') ∈ᴮ ⟨α, A, B⟩, have this1 : ⟨α'', A'', B''⟩ =ᴮ ⟨α', A', B'⟩ ⊓ B'' i'' ≤ A'' i'' ∈ᴮ ⟨α', A', B'⟩, by {rw[deduction], apply inf_le_left_of_le, apply infi_le}, suffices : A'' i'' ∈ᴮ ⟨α', A', B'⟩ ⊓ ⟨α', A', B'⟩ =ᴮ ⟨α, A, B⟩ ≤ A'' i'' ∈ᴮ ⟨α, A, B⟩, by {have := le_trans (inf_le_inf this1 (by refl)) this, convert this using 1, simp[bv_eq_symm], ac_refl}, suffices : ∀ a', ⟨α', A', B'⟩ =ᴮ ⟨α, A, B⟩ ⊓ A'' i'' =ᴮ A' a' ⊓ B' a' ≤ A'' i'' ∈ᴮ ⟨α, A, B⟩, by {convert (supr_le this) using 1, simp[mem, inf_comm, inf_supr_eq], congr, ext, ac_refl}, have this2 : ∀ a', ⟨α', A', B'⟩ =ᴮ ⟨α, A, B⟩ ⊓ B' a' ≤ A' a' ∈ᴮ ⟨α, A, B⟩, by {intro a', rw[deduction], apply inf_le_left_of_le, apply infi_le}, suffices : ∀ a', A'' i'' =ᴮ A' a' ⊓ A' a' ∈ᴮ ⟨α, A, B⟩ ≤ A'' i'' ∈ᴮ ⟨α, A, B⟩, by {intro a', have := le_trans (inf_le_inf (by refl) (this2 a')) (this a'), convert this using 1, ac_refl}, intro a', erw[inf_supr_eq], apply supr_le, intro a, conv {to_lhs, congr, skip, rw[inf_comm]}, suffices : A'' i'' =ᴮ A' a' ⊓ (A' a' =ᴮ A a ⊓ B a) = A'' i'' =ᴮ A' a' ⊓ A' a' =ᴮ A a ⊓ B a, by {rw[this], clear this, apply le_trans, exact (H2 i'' a' a), apply le_supr_of_le a, rw[inf_comm]}, ac_refl} end lemma bv_trans {Γ : 𝔹} {a₁ a₂ a₃ : bSet 𝔹} (H₁ : Γ ≤ a₁ =ᴮ a₂) (H₂ : Γ ≤ a₂ =ᴮ a₃) : Γ ≤ a₁ =ᴮ a₃ := le_trans (le_inf_iff.mpr ⟨H₁,H₂⟩) bv_eq_trans @[symm]lemma bv_symm {Γ} {x y : bSet 𝔹} (H : Γ ≤ x =ᴮ y) : Γ ≤ y =ᴮ x := by rwa[bv_eq_symm] lemma bv_rw {x y : bSet 𝔹} (H : x =ᴮ y = ⊤) (ϕ : bSet 𝔹 → 𝔹) {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} : ϕ y = ϕ x := begin apply le_antisymm, swap, rw[show ϕ x = ϕ x ⊓ ⊤, by simp], rw[<-H, inf_comm], apply h_congr, rw[show ϕ y = ϕ y ⊓ ⊤, by simp], rw[<-H, inf_comm, bv_eq_symm], apply h_congr end /-- If u = v and u ∈ w, then this implies that v ∈ w -/ lemma subst_congr_mem_left {u v w : bSet 𝔹} : u =ᴮ v ⊓ u ∈ᴮ w ≤ v ∈ᴮ w := begin simp only [mem_unfold], tidy_context, bv_cases_at a_right i, apply bv_use i, bv_split, from le_inf ‹_› (bv_trans (bv_symm ‹_›) ‹_›) end -- to derive primed versions of lemmas, use poset_yoneda_inv @[simp]lemma subst_congr_mem_left' {Γ : 𝔹} {u v w : bSet 𝔹} : Γ ≤ u =ᴮ v → Γ ≤ u ∈ᴮ w → Γ ≤ v ∈ᴮ w := λ _ _, poset_yoneda_inv _ subst_congr_mem_left $ le_inf ‹_› ‹_› -- example {u v w : bSet 𝔹} : u =ᴮ v ⊓ u ∈ᴮ w ≤ v ∈ᴮ w := -- begin -- simp only [mem_unfold], tidy_context, -- bv_cases_at a_right i, apply bv_use i, bv_split, refine le_inf ‹_› _, -- from bv_trans (bv_symm a_left) ‹_› -- end /-- If v = w and u ∈ v, then this implies that u ∈ w -/ lemma subst_congr_mem_right {u v w : bSet 𝔹} : (v =ᴮ w ⊓ u ∈ᴮ v) ≤ u ∈ᴮ w := begin induction v, erw[inf_supr_eq], apply supr_le, intro i, suffices : mk v_α ‹_› ‹_› =ᴮ w ⊓ v_B i ≤ v_A i ∈ᴮ w, have := le_trans (inf_le_inf this (by refl : u =ᴮ v_A i ≤ u =ᴮ v_A i)) _, rw[<-inf_assoc], convert this using 1, rw[bv_eq_symm, inf_comm], apply subst_congr_mem_left, rw[deduction], cases w, apply inf_le_left_of_le, apply infi_le end @[simp]lemma subst_congr_mem_right' {Γ : 𝔹} {u v w : bSet 𝔹} : Γ ≤ w =ᴮ v → Γ ≤ u ∈ᴮ w → Γ ≤ u ∈ᴮ v := λ _ _, poset_yoneda_inv _ subst_congr_mem_right $ le_inf ‹_› ‹_› /- Use rw[bounded_forall] and rw[bounded_exists] to pass from restricted quantifiers to the FOL interpretation of the quantifiers -/ lemma bounded_forall {v : bSet 𝔹} {ϕ : bSet 𝔹 → 𝔹 } {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} : (⨅(i_x : v.type), (v.bval i_x ⟹ ϕ (v.func i_x))) = (⨅(x : bSet 𝔹), x ∈ᴮ v ⟹ ϕ x) := begin apply le_antisymm, {bv_intro x, cases v, simp only with cleanup, erw[supr_imp_eq], bv_intro i_y, apply infi_le_of_le i_y, rw[<-deduction,<-inf_assoc], apply le_trans, apply inf_le_inf, apply bv_imp_elim, refl, rw[inf_comm, bv_eq_symm], apply h_congr}, {bv_intro i_x', apply infi_le_of_le (func v i_x'), apply imp_le_of_left_le, cases v, simp only with cleanup, apply le_supr_of_le i_x', apply le_inf, refl, rw[bv_eq_refl], apply le_top} end lemma bounded_exists {v : bSet 𝔹} {ϕ : bSet 𝔹 → 𝔹} {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} : (⨆(i_x : v.type), (v.bval i_x ⊓ ϕ(v.func i_x))) = (⨆(x : bSet 𝔹), x ∈ᴮ v ⊓ ϕ x) := begin apply le_antisymm, {apply bv_Or_elim, intro i_x, apply bv_use (v.func i_x), apply inf_le_inf, apply mem.mk', refl}, {apply bv_Or_elim, intro x, simp only [mem_unfold], apply bv_cases_left, intro i_x, apply bv_use i_x, ac_change bval v i_x ⊓ (x =ᴮ func v i_x ⊓ ϕ x) ≤ bval v i_x ⊓ ϕ (func v i_x), apply inf_le_inf, refl, apply h_congr} end -- foo_unfold' means that the definition foo will be unfolded using global quantifiers lemma mem_unfold' {u v : bSet 𝔹} : u ∈ᴮ v = ⨆z, z ∈ᴮ v ⊓ u =ᴮ z := by {rw[<-bounded_exists, mem_unfold], intros x y, ac_change y =ᴮ x ⊓ x =ᴮ u ≤ y =ᴮ u, simp[bv_eq_symm], exact bv_eq_symm, exact bv_eq_trans } lemma subset_unfold' {x u : bSet 𝔹} : x ⊆ᴮ u = ⨅(w : bSet 𝔹), w ∈ᴮ x ⟹ w ∈ᴮ u := begin simp only [subset_unfold], have := @bounded_forall 𝔹 _ x (λ y, y∈ᴮ u), dsimp at this, rw[this], intros, apply subst_congr_mem_left end lemma bv_eq_unfold' {x y : bSet 𝔹} : x =ᴮ y = (⨅ z, z ∈ᴮ x ⟹ z ∈ᴮ y) ⊓ (⨅ z, z ∈ᴮ y ⟹ z ∈ᴮ x) := begin rw eq_iff_subset_subset, rw [subset_unfold', subset_unfold'] end theorem mem_ext {x y : bSet 𝔹} {Γ : 𝔹} (h₁ : Γ ≤ ⨅z, z ∈ᴮ x ⟹ z ∈ᴮ y) (h₂ : Γ ≤ ⨅z, z ∈ᴮ y ⟹ z ∈ᴮ x) : Γ ≤ x =ᴮ y := by {[smt] eblast_using [subset_ext, subset_unfold']} @[simp]lemma subset_self_eq_top {x : bSet 𝔹} : x ⊆ᴮ x = ⊤ := top_unique subset_self lemma subset_trans {x y z : bSet 𝔹} : x ⊆ᴮ y ⊓ y ⊆ᴮ z ≤ x ⊆ᴮ z := begin simp[subset_unfold'], intro i_z, apply bv_specialize_left i_z, apply bv_specialize_right i_z, rw[<-deduction], ac_change (i_z ∈ᴮ x ⟹ i_z ∈ᴮ y) ⊓ i_z ∈ᴮ x ⊓ (i_z ∈ᴮ y ⟹ i_z ∈ᴮ z) ≤ i_z ∈ᴮ z, rw[deduction], let H := _, change ((H ⟹ _) ⊓ H : 𝔹) ≤ _, apply le_trans, apply bv_imp_elim, rw[<-deduction], rw[inf_comm], apply le_trans, apply bv_imp_elim, refl end lemma subset_trans' {x y z : bSet 𝔹} {Γ : 𝔹} (H₁ : Γ ≤ x ⊆ᴮ y) (H₂ : Γ ≤ y ⊆ᴮ z) : Γ ≤ x ⊆ᴮ z := poset_yoneda_inv Γ subset_trans $ le_inf ‹_› ‹_› -- lemma subset_trans_context {x y z : bSet 𝔹} {c : 𝔹} {h₁ : c ≤ x ⊆ᴮ y} {h₂ : c ≤ y ⊆ᴮ z} : c ≤ x ⊆ᴮ z := -- begin -- apply bv_have h₂, rw[deduction], apply bv_have h₁, rw[<-deduction], -- ac_change c ⊓ (x ⊆ᴮ y ⊓ y ⊆ᴮ z) ≤ x ⊆ᴮ z, apply inf_le_right_of_le, -- apply subset_trans -- end -- TODO(jesse): mark this as simp lemma mem_of_mem_subset {x y z : bSet 𝔹} {Γ} (H₂ : Γ ≤ y ⊆ᴮ z) (H₁ : Γ ≤ x ∈ᴮ y) : Γ ≤ x ∈ᴮ z := by {rw[subset_unfold'] at H₂, from H₂ x ‹_›} -- lemma bounded_forall' {ϕ : bSet 𝔹 → 𝔹 } {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} {v : bSet 𝔹} : -- (⨅(i_x : v.type), (v.bval i_x ⟹ ϕ (v.func i_x))) = (⨅(x : bSet 𝔹), x ∈ᴮ v ⟹ ϕ x) := -- begin -- apply le_antisymm, -- {bv_intro x, cases v, simp, rw[supr_imp_eq], -- bv_intro i_y, apply infi_le_of_le i_y, -- rw[<-deduction,<-inf_assoc], apply le_trans, apply inf_le_inf, -- apply bv_imp_elim, refl, rw[inf_comm, bv_eq_symm], apply h_congr}, -- {bv_intro i_x', apply infi_le_of_le (func v i_x'), apply imp_le_of_left_le, -- cases v, simp, apply le_supr_of_le i_x', -- apply le_inf, refl, rw[bv_eq_refl], apply le_top} -- end lemma subst_congr_subset_left {x v u} : ((v ⊆ᴮ u) ⊓ (x =ᴮ v) : 𝔹) ≤ (x ⊆ᴮ u) := begin simp only [subset_unfold], have H₁ := @bounded_forall _ _ v (λ x, x ∈ᴮ u) (by {intros, apply subst_congr_mem_left}), have H₂ := @bounded_forall _ _ x (λ x, x ∈ᴮ u) (by {intros, apply subst_congr_mem_left}), rw[H₁, H₂], dsimp, bv_intro z, rw[deduction], apply infi_le_of_le z, rw[<-deduction, <-deduction], rw[inf_assoc], apply le_trans, apply inf_le_inf, refl, apply subst_congr_mem_right, apply bv_imp_elim -- todo write tactics to make these calculations easier end lemma subst_congr_subset_right {x v u} : ((v ⊆ᴮ u) ⊓ (u =ᴮ x) : 𝔹) ≤ (v ⊆ᴮ x) := begin simp only [subset_unfold], bv_intro j, apply bv_specialize_left j, rw[<-deduction], ac_change ((bval v j ⟹ func v j ∈ᴮ u) ⊓ bval v j) ⊓ u =ᴮ x ≤ func v j ∈ᴮ x, rw[deduction], apply le_trans, apply bv_imp_elim, rw[<-deduction, inf_comm], apply subst_congr_mem_right end -- use `apply bv_rw' (H : Γ ≤ x =ᴮ y)` for rewriting the `x` to `y` in the goal -- if Lean is able to infer the motive, this will generate a B_ext proof obligation which will usually be `by simp` lemma bv_rw'₀ {x y : bSet 𝔹} {Γ : 𝔹} (H : Γ ≤ x =ᴮ y) {ϕ : bSet 𝔹 → 𝔹} {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} {H_new : Γ ≤ ϕ y} : Γ ≤ ϕ x := begin have : Γ ≤ y =ᴮ x ⊓ ϕ y, by {apply le_inf, rw[bv_eq_symm], from ‹_›, from ‹_›}, from (poset_yoneda_inv _ (h_congr _ _) this) end -- TODO(jesse) maybe replace this with typeclasses instead? @[reducible]def B_ext (ϕ : bSet 𝔹 → 𝔹) : Prop := ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y -- use `apply bv_rw' (H : Γ ≤ x =ᴮ y)` for rewriting the `x` to `y` in the goal -- if Lean is able to infer the motive, this will generate a B_ext proof obligation which will usually be `by simp` lemma bv_rw' {x y : bSet 𝔹} {Γ : 𝔹} (H : Γ ≤ x =ᴮ y) {ϕ : bSet 𝔹 → 𝔹} {h_congr : B_ext ϕ} {H_new : Γ ≤ ϕ y} : Γ ≤ ϕ x := by apply bv_rw'₀; from ‹_› @[simp]lemma B_ext_bv_eq_left {y : bSet 𝔹} : B_ext (λ x, x =ᴮ y) := by {unfold B_ext, intros, rw[bv_eq_symm], apply bv_eq_trans} @[simp]lemma B_ext_bv_eq_right {x : bSet 𝔹} : B_ext (λ y, x =ᴮ y) := by {unfold B_ext, intros, rw[inf_comm], apply bv_eq_trans} @[simp]lemma B_ext_mem_left {y : bSet 𝔹} : B_ext (λ x, x ∈ᴮ y) := by unfold B_ext; intros; apply subst_congr_mem_left @[simp]lemma B_ext_mem_right {x : bSet 𝔹} : B_ext (λ y, x ∈ᴮ y) := by unfold B_ext; intros; apply subst_congr_mem_right @[simp]lemma B_ext_subset_left {y : bSet 𝔹} : B_ext (λ x, x ⊆ᴮ y) := by {unfold B_ext, intros, rw[inf_comm, bv_eq_symm], apply subst_congr_subset_left} @[simp]lemma B_ext_subset_right {x : bSet 𝔹} : B_ext (λ y, x ⊆ᴮ y) := by {unfold B_ext, intros, rw[inf_comm], apply subst_congr_subset_right} @[simp]lemma B_ext_sup {ϕ₁ ϕ₂ : bSet 𝔹 → 𝔹} {h₁ : B_ext ϕ₁} {h₂ : B_ext ϕ₂} : B_ext (λ x, ϕ₁ x ⊔ ϕ₂ x) := begin intros x y, dsimp, rw[inf_comm, deduction], apply bv_or_elim; apply bv_imp_intro; [apply le_sup_left_of_le, apply le_sup_right_of_le]; rw[inf_comm]; [apply h₁, apply h₂] end @[simp]lemma B_ext_inf {ϕ₁ ϕ₂ : bSet 𝔹 → 𝔹} (h₁ : B_ext ϕ₁) (h₂ : B_ext ϕ₂) : B_ext (λ x, ϕ₁ x ⊓ ϕ₂ x) := begin intros x y, tidy_context, refine ⟨_,_⟩, { apply bv_rw' (bv_symm a_left); from ‹_› }, { apply bv_rw' (bv_symm a_left); from ‹_› } end @[simp]lemma B_ext_imp {ϕ₁ ϕ₂ : bSet 𝔹 → 𝔹} {h₁ : B_ext ϕ₁} {h₂ : B_ext ϕ₂} : B_ext (λ x, ϕ₁ x ⟹ ϕ₂ x) := begin intros x y, rw[<-deduction], tidy_context, apply bv_rw' (bv_symm a_left_left), from ‹_›, refine a_left_right _, apply bv_rw' a_left_left; from ‹_› end @[simp]lemma B_ext_const {b : 𝔹} : B_ext (λ x, b) := by tidy @[simp]lemma B_ext_neg {ϕ₁ : bSet 𝔹 → 𝔹} {h : B_ext ϕ₁} : B_ext (λ x, - ϕ₁ x) := by {simp only [imp_bot.symm], apply B_ext_imp, simpa, from B_ext_const} @[simp]lemma B_ext_infi {ι : Type*} {Ψ : ι → (bSet 𝔹 → 𝔹)} {h : ∀ i, B_ext $ Ψ i} : B_ext (λ x, ⨅i, Ψ i x) := by {intros x y, dsimp, bv_intro i, apply bv_specialize_right i, apply h} @[simp]lemma B_ext_supr {ι : Type*} {ψ : ι → (bSet 𝔹 → 𝔹)} {h : ∀i, B_ext $ ψ i} : B_ext (λ x, ⨆i, ψ i x) := by {intros x y, dsimp, apply bv_cases_right, intro i, apply bv_use i, apply h} example {y : bSet 𝔹} : B_ext (λ x : bSet 𝔹, x ∈ᴮ y ⊔ y ∈ᴮ x) := by change B_ext _; simp @[reducible]def B_congr (t : bSet 𝔹 → bSet 𝔹) : Prop := ∀ {x₁ x₂}, ∀ {Γ : 𝔹}, Γ ≤ x₁ =ᴮ x₂ → Γ ≤ t x₁ =ᴮ t x₂ meta def H_congr_handler : tactic unit := `[simp] @[simp]lemma B_ext_term (ϕ : bSet 𝔹 → 𝔹) (t : bSet 𝔹 → bSet 𝔹) (H : B_ext ϕ . H_congr_handler) (H' : B_congr t . H_congr_handler) : B_ext (λ z, ϕ ((λ w, t w) z) ) := begin intros x y, tidy_context, suffices : Γ ≤ t x =ᴮ t y, by {apply bv_rw' (bv_symm this), from ‹_›, from ‹_›}, exact H' ‹_› end -- use for rewriting in the second argument using the first lemma bv_rw'' {x y : bSet 𝔹} {Γ : 𝔹} (H : Γ ≤ x =ᴮ y) {ϕ : bSet 𝔹 → 𝔹} (H_new : Γ ≤ ϕ x) (h_congr : B_ext ϕ . H_congr_handler) : Γ ≤ ϕ y := begin have : Γ ≤ x =ᴮ y ⊓ ϕ x, by {apply le_inf, from ‹_›, from ‹_›}, from (poset_yoneda_inv _ (h_congr _ _) this) end lemma mem_congr {Γ : 𝔹} {x₁ x₂ y₁ y₂ : bSet 𝔹} (H₁ : Γ ≤ x₁ =ᴮ y₁) (H₂ : Γ ≤ x₂ =ᴮ y₂) (H₃ : Γ ≤ x₁ ∈ᴮ x₂) : Γ ≤ y₁ ∈ᴮ y₂ := by {rw[bv_eq_symm] at H₁ H₂, apply bv_rw' H₁, simp, apply bv_rw' H₂, simpa} @[instance]def b_setoid (Γ : 𝔹) : setoid (bSet 𝔹) := { r := bv_eq' Γ, iseqv := ⟨λ _, bv_refl, λ _ _, bv_symm, λ _ _ _, bv_trans⟩ } lemma bv_cc.mk_iff {Γ} {x y : bSet 𝔹} : Γ ≤ x =ᴮ y ↔ (@quotient.mk _ (b_setoid Γ) x) = (@quotient.mk _ (b_setoid Γ) y) := by rw [quotient.eq]; refl lemma bv_cc.mk {Γ} {x y : bSet 𝔹} (H : Γ ≤ x =ᴮ y) : (@quotient.mk _ (b_setoid Γ) x) = (@quotient.mk _ (b_setoid Γ) y) := bv_cc.mk_iff.mp ‹_› -- TODO(jesse): automate the generation of these lemmas with typeclasses def b_setoid_mem (Γ : 𝔹) : quotient (b_setoid Γ) → quotient (b_setoid Γ) → Prop := @quotient.lift₂ (bSet 𝔹) (bSet 𝔹) Prop (b_setoid Γ) (b_setoid Γ) (λ x y, Γ ≤ x ∈ᴮ y) begin intros a₁ a₂ b₁ b₂ H_eqv₁ H_eqv₂, dsimp, apply propext, refine ⟨_,_⟩; intro H, all_goals { rw[<-quotient.eq, <-bv_cc.mk_iff] at H_eqv₁ H_eqv₂}, { exact mem_congr ‹_› ‹_› ‹_› }, { exact mem_congr (bv_symm H_eqv₁) (bv_symm H_eqv₂) ‹_› } end lemma bv_cc.mk_mem_iff {Γ} {x y : bSet 𝔹} : Γ ≤ x ∈ᴮ y ↔ b_setoid_mem Γ (@quotient.mk _ (b_setoid Γ) x) (@quotient.mk _ (b_setoid Γ) y) := by rw b_setoid_mem; refl lemma bv_cc.mk_mem {Γ} {x y : bSet 𝔹} (H : Γ ≤ x ∈ᴮ y) : b_setoid_mem Γ (@quotient.mk _ (b_setoid Γ) x) (@quotient.mk _ (b_setoid Γ) y) := bv_cc.mk_mem_iff.mp ‹_› example {x y z : bSet 𝔹} {Γ : 𝔹} (H1 : Γ ≤ x =ᴮ y) (H2 : Γ ≤ y =ᴮ z) : Γ ≤ x =ᴮ z := begin replace H1 := bv_cc.mk H1, replace H2 := bv_cc.mk H2, rw[bv_cc.mk_iff], cc end end bSet namespace tactic namespace interactive section bv_cc open lean.parser lean interactive.types interactive local postfix `?`:9001 := optional /-- `apply_at (H : α) F` assumes that F's first explicit argument is of type `α` and replaces the assumption H with F H. -/ meta def apply_at (H_tgt : parse ident) (H : parse texpr) : tactic unit := do e_tgt <- resolve_name H_tgt, tactic.replace H_tgt ``(%%H %%e_tgt) meta def apply_all (H : parse texpr) : tactic unit := do ctx <- local_context, let mk_new_hyp (e : expr) : tactic unit := let n_e := get_name e in tactic.try (do n <- get_unused_name n_e, to_expr ``(%%H %%e) >>= note n none) in (list.mmap' mk_new_hyp ctx) meta def bv_cc : tactic unit := do apply_all ``(bSet.bv_cc.mk), try `[rw[bSet.bv_cc.mk_iff]], apply_all ``(bSet.bv_cc.mk_mem), try `[rw[bSet.bv_cc.mk_mem_iff]], cc end bv_cc end interactive end tactic example {𝔹} [nontrivial_complete_boolean_algebra 𝔹] {a b c : 𝔹} : ( a ⟹ b ) ⊓ ( b ⟹ c ) ≤ a ⟹ c := begin tidy_context, bv_tauto end example {α β : Type} (f : α → β) (P : α → Prop) (Q : β → Prop) {a : α} (H : P a) (H' : P a) (C : ∀ {a}, P a → Q (f a)) : true := begin apply_at H C, apply_all C, triv end namespace bSet variables {𝔹 : Type u} [nontrivial_complete_boolean_algebra 𝔹] example {x y z x₁ y₁ z₁: bSet 𝔹} {Γ : 𝔹} (H1 : Γ ≤ x =ᴮ y) (H2 : Γ ≤ y =ᴮ z) (H3 : Γ ≤ z =ᴮ z₁) (H4 : Γ ≤ z₁ =ᴮ y₁) (H5 : Γ ≤ y₁ =ᴮ x₁) : Γ ≤ x =ᴮ x₁ := by bv_cc -- :^) example {x₁ y₁ x₂ y₂ : bSet 𝔹} {Γ} (H₁ : Γ ≤ x₁ ∈ᴮ y₁) (H₂ : Γ ≤ x₁ =ᴮ x₂) (H₂ : Γ ≤ y₁ =ᴮ y₂) : Γ ≤ x₂ ∈ᴮ y₂ := by bv_cc -- :^) example {a b c d e : bSet 𝔹} : (a =ᴮ b) ⊓ (b =ᴮ c) ⊓ (c =ᴮ d) ⊓ (d =ᴮ e) ≤ a =ᴮ e := by tidy_context; bv_cc def is_definite (u : bSet 𝔹) : Prop := ∀ i : u.type, u.bval i = ⊤ lemma eq_empty {u : bSet 𝔹} : u =ᴮ ∅ = -⨆i, u.bval i := begin simp only [bv_eq_unfold], simp only [mem_unfold], simp only [inf_top_eq, bSet.forall_over_empty, bSet.exists_over_empty,imp_bot, neg_supr] end @[simp]lemma empty_subset {x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ ∅ ⊆ᴮ x := by rw[subset_unfold]; bv_intro; repeat{cases i} lemma empty_spec {x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ -(x ∈ᴮ ∅) := by simp[mem_unfold] lemma bot_of_mem_empty {x : bSet 𝔹} {Γ : 𝔹} (H : Γ ≤ x ∈ᴮ ∅) : Γ ≤ ⊥ := by {have := @empty_spec 𝔹 _ x Γ, rw[<-imp_bot] at this, from this H} @[simp]lemma subst_congr_insert1_left {u w v : bSet 𝔹} : u =ᴮ w ≤ bSet.insert1 u v =ᴮ bSet.insert1 w v := begin rcases v with ⟨α,A,B⟩, simp[bSet.insert1, bv_eq, mem], split; intro i; apply bv_imp_intro; refine le_sup_right_of_le _; apply bv_use i; rw[inf_comm]; simp end @[simp]lemma subst_congr_insert1_left' {u w v : bSet 𝔹} {c : 𝔹} {h : c ≤ u =ᴮ w} : c ≤ bSet.insert1 u v =ᴮ bSet.insert1 w v := by apply le_trans h; simp @[simp]lemma subst_congr_insert1_left'' {u w v : bSet 𝔹} {c : 𝔹} {h : c ≤ u =ᴮ w} : c ≤ {v, u} =ᴮ {v, w} := by {unfold has_insert.insert, apply subst_congr_insert1_left', from ‹_›} @[simp]lemma subst_congr_insert1_right {u w v : bSet 𝔹} : u=ᴮw ≤ bSet.insert1 v u =ᴮ bSet.insert1 v w := by {rcases u with ⟨α,A,B⟩, rcases w with ⟨α',A',B'⟩, simp[bSet.insert1, bv_eq, mem]; split; intro i; apply bv_imp_intro, apply le_sup_right_of_le, apply le_trans, apply inf_le_inf, refl, apply mem.mk, from A, change _ ⊓ _ ≤ A i ∈ᴮ ⟨α',A',B'⟩, rw ← bv_eq, apply subst_congr_mem_right, apply le_sup_right_of_le, apply le_trans, apply inf_le_inf, refl, apply mem.mk, from A', conv {to_rhs, congr, funext,rw[bv_eq_symm]}, change _ ≤ A' i ∈ᴮ ⟨α,A,B⟩, rw[←bv_eq, bv_eq_symm], apply subst_congr_mem_right} @[simp]lemma subst_congr_insert1_right' {u w v : bSet 𝔹} {c : 𝔹} {h : c ≤ u =ᴮ w} : c ≤ bSet.insert1 v u =ᴮ bSet.insert1 v w := by {apply le_trans h, apply subst_congr_insert1_right} @[simp]lemma subst_congr_insert1_right'' {u w v : bSet 𝔹} {c : 𝔹} {h : c ≤ u =ᴮ w} : c ≤ {u,v} =ᴮ {w,v} := by {unfold has_insert.insert, apply subst_congr_insert1_right', apply subst_congr_insert1_left', from ‹_›} /- some singleton lemmas -/ @[simp]lemma eq_singleton_of_eq {x y : bSet 𝔹} {c : 𝔹} {h : c ≤ x =ᴮ y} : c ≤ {x} =ᴮ {y} := by {apply subst_congr_insert1_left', from ‹_›} lemma eq_of_eq_singleton {x y : bSet 𝔹} {c : 𝔹} {h : c ≤ {x} =ᴮ {y}} : c ≤ x =ᴮ y := begin apply le_trans h, simp[singleton, has_insert.insert], simp only [insert1_unfold], simp only [bv_eq_unfold], simp only [lattice.le_inf_iff, lattice.infi_option, lattice.inf_top_eq, bSet.mem, lattice.top_inf_eq, lattice.supr_option, lattice.top_imp, lattice.sup_bot_eq, lattice.le_infi_iff, bSet.forall_over_empty, bSet.exists_over_empty] with cleanup, split; intro i; [apply inf_le_left_of_le, apply inf_le_right_of_le]; rw[bv_eq_unfold]; apply inf_le_left_of_le; apply bv_specialize i; refl end lemma eq_singleton_iff_eq {x y : bSet 𝔹} {c : 𝔹} : c ≤ {x} =ᴮ {y} ↔ c ≤ x =ᴮ y := by {split; intros; [apply eq_of_eq_singleton, apply eq_singleton_of_eq]; from ‹_›} lemma singleton_unfold {x : bSet 𝔹} : {x} = bSet.insert1 x ∅ := rfl @[simp]lemma singleton_type {x : bSet 𝔹} : type ({x} : bSet 𝔹) = option (ulift _root_.empty) := rfl @[simp]lemma singleton_func {x : bSet 𝔹} {o} : func ({x} : bSet 𝔹) o = option.rec_on o x (empty.elim ∘ ulift.down) := rfl @[simp]lemma singleton_bval {x : bSet 𝔹} {o} : bval ({x} : bSet 𝔹) o = option.rec_on o ⊤ (empty.elim ∘ ulift.down) := rfl @[simp]lemma singleton_bval_none {x : bSet 𝔹} : bval ({x} : bSet 𝔹) none = ⊤ := rfl -- @[simp]lemma eq_of_eq_insert_right {u w v : bSet 𝔹} {c : 𝔹} {h : c ≤ bSet.insert1 v u =ᴮ bSet.insert1 v w} : c ≤ u =ᴮ w := -- begin -- apply le_trans h, simp only [insert1_unfold, bv_eq_unfold], simp, split; intro i; [apply inf_le_left_of_le, apply inf_le_right_of_le], -- {apply bv_specialize i, apply bv_cancel_antecedent, apply bv_or_elim, }, -- {sorry} -- end /-- ϕ (x) is true if and only if the Boolean truth-value of ϕ(x̌) is ⊤-/ /- To even state this theorem, we need to set up more general machinery for Boolean-valued structures and the interpretation of formulas within them -/ -- theorem check_transfer : sorry := sorry def mixture {ι : Type u} (a : ι → 𝔹) (u : ι → bSet 𝔹) : bSet 𝔹 := ⟨Σ(i : ι), (u i).type, λx, (u x.fst).func x.snd, λx, ⨆(j:ι), a j ⊓ ((u x.fst).func x.snd) ∈ᴮ u j⟩ /-- Given a₁ a₂ : 𝔹, return the canonical map from ulift bool to 𝔹 given by ff ↦ a₁ and tt ↦ a₂-/ @[reducible]def bool.map {α : Type*} (a₁ a₂ : α) : (ulift bool) → α := λ x, bool.rec_on (x.down) a₁ a₂ def two_term_mixture (a₁ a₂ : 𝔹) (h_anti : a₁ ⊓ a₂ = ⊥) (u₁ u₂ : bSet 𝔹) : bSet 𝔹 := @mixture 𝔹 _ (ulift bool) (bool.map a₁ a₂) (bool.map u₁ u₂) -- @[simp]lemma two_term_mixture_type (a₁ a₂ : 𝔹) (h_anti : a₁ ⊓ a₂ = ⊥) (u₁ u₂ : bSet 𝔹) : -- (two_term_mixture a₁ a₂ h_anti u₁ u₂).type = (Σ(i : ulift bool), ((bool.map u₁ u₂) i).type) := sorry lemma two_term_mixture_h_star (a₁ a₂ : 𝔹) (h_anti : a₁ ⊓ a₂ = ⊥) (u₁ u₂ : bSet 𝔹) : ∀ i j : (ulift bool), (bool.map a₁ a₂) i ⊓ (bool.map a₁ a₂) j ≤ (bool.map u₁ u₂) i =ᴮ (bool.map u₁ u₂) j := begin intros i j, cases i, cases j, cases i; cases j; try{simp*}, change a₂ ⊓ a₁ ≤ _, rw[inf_comm, h_anti], apply bot_le end @[simp]lemma bval_mixture {ι : Type u} {a : ι → 𝔹} {u : ι → bSet 𝔹} : (mixture a u).bval = λx, ⨆(j:ι), a j ⊓ ((u x.fst).func x.snd) ∈ᴮ u j := by refl @[simp]lemma two_term_mixture_bval (a₁ a₂ : 𝔹) (h_anti : a₁ ⊓ a₂ = ⊥) (u₁ u₂ : bSet 𝔹) : ∀ i, (two_term_mixture a₁ a₂ h_anti u₁ u₂).bval i = (a₁ ⊓ ((two_term_mixture a₁ a₂ h_anti u₁ u₂).func i ∈ᴮ u₁)) ⊔ (a₂ ⊓ ((two_term_mixture a₁ a₂ h_anti u₁ u₂).func i ∈ᴮ u₂)) := λ i, begin dsimp[two_term_mixture], tidy, apply le_antisymm, apply supr_le, intro j, repeat{cases j}, apply le_sup_left_of_le, refl, apply le_sup_right_of_le, refl, apply bv_or_elim; [apply bv_use (ulift.up ff), apply bv_use (ulift.up tt)]; refl end def floris_mixture {ι : Type u} (a : ι → 𝔹) (u : ι → bSet 𝔹) : bSet 𝔹 := ⟨Σ(i : ι), (u i).type, λx, (u x.fst).func x.snd, λx, a x.fst ⊓ (u x.fst).bval x.snd⟩ /-- Mixing lemma, c.f. Bell's book or Lemma 1 of Hamkins-Seabold -/ lemma mixing_lemma' {ι : Type u} (a : ι → 𝔹) (τ : ι → bSet 𝔹) (h_star : ∀ i j : ι, a i ⊓ a j ≤ τ i =ᴮ τ j) : ∀ i : ι, a i ≤ (mixture a τ) =ᴮ τ i := λ i, begin rw[bv_eq_unfold], apply le_inf, {bv_intro i_z, apply bv_imp_intro, simp only [bSet.bval, bSet.mem, bSet.func, bSet.type, bSet.bval_mixture], rw[inf_supr_eq], apply bv_Or_elim, intro j, rw[<-inf_assoc], have : a i ⊓ a j ⊓ func (τ (i_z.fst)) (i_z.snd) ∈ᴮ τ j ≤ (τ i =ᴮ τ j) ⊓ func (τ (i_z.fst)) (i_z.snd) ∈ᴮ τ j, by {apply inf_le_inf (h_star i j), refl}, apply le_trans this, rw[bv_eq_symm], apply subst_congr_mem_right}, {bv_intro i_z, rw[<-deduction], refine le_supr_of_le (sigma.mk i i_z) _, simp only [bv_eq_top_of_eq, mem, type, inf_top_eq, bval, func], refine le_supr_of_le i _, refine inf_le_inf (by refl : a i ≤ a i) _, dsimp only, cases (τ i), refine le_supr_of_le i_z _, from le_inf (by refl) (by simp)} end lemma mixing_lemma {ι : Type u} (a : ι → 𝔹) (τ : ι → bSet 𝔹) (h_star : ∀ i j : ι, a i ⊓ a j ≤ τ i =ᴮ τ j) : ∃ x, ∀ i : ι, a i ≤ x =ᴮ τ i := by refine ⟨mixture a τ, λ i, _⟩; apply mixing_lemma'; assumption lemma mixing_lemma_two_term (a₁ a₂ : 𝔹) (h_anti : a₁ ⊓ a₂ = ⊥) (u₁ u₂ : bSet 𝔹) : a₁ ≤ (two_term_mixture a₁ a₂ h_anti u₁ u₂ =ᴮ u₁) ∧ a₂ ≤ (two_term_mixture a₁ a₂ h_anti u₁ u₂ =ᴮ u₂) := begin have := mixing_lemma' (bool.map a₁ a₂) (bool.map u₁ u₂) (by {apply two_term_mixture_h_star, exact h_anti}), split; [specialize this (ulift.up ff), specialize this (ulift.up tt)]; exact this end -- TODO(jesse) try proving mixing_lemma with floris_mixture and see if anything goes wrong /-- In particular, the mixing lemma applies when the weights (a_i) form an antichain and the indexing is injective -/ lemma h_star_of_antichain_injective {ι : Type u} {a : ι → 𝔹} {τ : ι → bSet 𝔹} {h_anti : antichain (a '' set.univ)} {h_inj : function.injective a} : ∀ i j : ι, a i ⊓ a j ≤ τ i =ᴮ τ j := begin intros i j, by_cases a i = a j, simp[h_inj h], have := h_anti _ _ _ _ h, simp[this], tidy end /- Note: this is the special condition assumed of indexed antichains by Bell-/ lemma h_star_of_antichain_index {ι : Type u} {a : ι → 𝔹} {τ : ι → bSet 𝔹} {h_anti : antichain (a '' set.univ)} {h_index : ∀ i j : ι, i ≠ j → a i ⊓ a j = ⊥} : ∀ i j : ι, a i ⊓ a j ≤ τ i =ᴮ τ j := λ i j, by {haveI : decidable_eq ι := λ _ _, by apply classical.prop_decidable _, by_cases i = j, simp[h], finish[h_index i j]} /- The next two lemmas use the fact that 𝔹 : Type u to extract a small set witnessing quantification over all of bSet 𝔹 -/ /- i.e., in bSet 𝔹, any existential quantification is equivalent to a bounded existential quantification. this is one place where it's crucial that 𝔹 lives in the type universe out of which bSet 𝔹 is being built -/ section smallness variable {ϕ : bSet 𝔹 → 𝔹} @[reducible, simp]noncomputable def fiber_lift (b : ϕ '' set.univ) := classical.indefinite_description (λ a : bSet 𝔹, ϕ a = b.val) $ by {cases b.property, use w, exact h.right} noncomputable def B_small_witness : bSet 𝔹 := ⟨ϕ '' set.univ, λ b, (fiber_lift b).val, λ _, ⊤⟩ @[simp]lemma B_small_witness_spec : ∀ b, ϕ ((@B_small_witness _ _ ϕ).func b) = b.val := λ b, (fiber_lift b).property lemma B_small_witness_supr : (⨆(x : bSet 𝔹), ϕ x) = ⨆(b : (@B_small_witness _ _ ϕ).type), ϕ (B_small_witness.func b) := begin apply le_antisymm, apply supr_le, intro x, let b : type B_small_witness := by {use ϕ x, simp only [set.image_univ, set.mem_range], exact ⟨x, rfl⟩}, fapply le_supr_of_le, exact b, have := B_small_witness_spec b, dsimp at this, rw[this], apply supr_le, intro b, apply le_supr_of_le, swap, exact (fiber_lift b).val, refl end @[reducible, simp]def not_b (b : 𝔹) : set 𝔹 := λ y, y ≠ b section well_ordering variables {α : Type*} (r : α → α → Prop) [is_well_order α r] local infix `≺`:50 := r def down_set (a : α) : set α := {a' | a' ≺ a} def down_set' (a : α) : set α := insert a $ down_set r a lemma down_set_trans {a b} {h : a ≺ b} : down_set r a ⊆ down_set r b := begin intros x H, have := is_well_order.is_trans r, cases this, apply this, exact H, exact h end end well_ordering variable (r : type (@B_small_witness _ _ ϕ) → type (@B_small_witness _ _ ϕ) → Prop) variable [is_well_order _ r] local infix `≺`:50 := r lemma down_set_mono_supr {a b} {h : a ≺ b} {s : type (@B_small_witness _ _ ϕ) → 𝔹} : (⨆(i ∈ down_set r a), s i) ≤ (⨆(i ∈ down_set r b), s i) := begin apply supr_le_supr, intro i, apply supr_le, intro H, apply le_supr_of_le, apply down_set_trans, exact h, exact H, refl end lemma down_set'_mono_supr {a b} {h : a ≺ b} {s : type (@B_small_witness _ _ ϕ) → 𝔹} : (⨆(i ∈ down_set' r a), s i) ≤ (⨆(i ∈ down_set' r b), s i) := begin apply supr_le_supr, intro i, apply supr_le, intro H, apply le_supr_of_le, cases H, apply or.inr, rw[H], exact h, apply or.inr, apply down_set_trans, exact h, exact H, refl end def witness_antichain : _ → 𝔹 := (λ b : type (@B_small_witness _ _ ϕ), b.val - (⨆(b' : (down_set r b)), b'.val.val)) def trichotomy := (is_well_order.is_trichotomous r).trichotomous lemma dichotomy_of_neq (x y) : x ≠ y → x ≺ y ∨ y ≺ x := λ H, by {[smt] eblast_using [trichotomy r x y]} lemma not_ge_of_in_down_set (a b) : a ∈ down_set r b → ¬ b ≺ a := begin intros H H', have H'' : a ≺ b, by {simpa[down_set]}, cases (show (is_asymm _ r), by apply_instance), specialize asymm a b H'', contradiction end def witness_antichain_index : ∀ {i j}, i ≠ j → (@witness_antichain _ _ ϕ r _) i ⊓ (@witness_antichain _ _ ϕ r _) j = ⊥ := λ x y h_neq, begin dsimp[witness_antichain], simp[sub_eq, neg_supr], apply bot_unique, cases dichotomy_of_neq r _ _ h_neq, {/- `tidy_context` says -/ apply poset_yoneda, intros Γ a, simp only [le_inf_iff] at *, cases a, cases a_right, cases a_left, replace a_right_right := a_right_right ⟨x,‹_›⟩, dsimp at a_right_right, bv_contradiction}, { /- `tidy_context` says -/ apply poset_yoneda, intros Γ a, simp only [le_inf_iff] at *, cases a, cases a_right, cases a_left, replace a_left_right := a_left_right ⟨y,‹_›⟩, dsimp at a_left_right, bv_contradiction} end lemma witness_antichain_antichain : antichain ((@witness_antichain _ _ ϕ r _) '' set.univ) := begin intros x h_x y h_y h_neq, simp at h_x h_y, rcases h_y with ⟨w_y, h_y⟩, rcases h_x with ⟨w_x, h_x⟩, rw[<-h_y, <-h_x], apply witness_antichain_index, by_contra, cc end lemma witness_antichain_property : ∀ b, (@witness_antichain _ _ ϕ r _) b ≤ b.val := λ b, by simp[witness_antichain, sub_eq] lemma supr_antichain2_contains : (⨆ (b' : type (@B_small_witness _ _ ϕ)), ϕ (func (@B_small_witness _ _ ϕ) b')) ≤ ⨆ (b : type (@B_small_witness _ _ ϕ)), witness_antichain r b := begin apply supr_le, intro i, apply le_supr_of_le'', fsplit, exact down_set' r i, rw[B_small_witness_spec i], have := (is_well_order.wf r).apply i, induction this, intros, rw[down_set',supr_insert], unfold witness_antichain, rw[sub_eq], rw[sup_inf_right], apply le_inf, apply le_sup_left, -- simp[neg_supr, sub_eq], apply le_trans (@le_top _ _ this_x.val), let A := _, change ⊤ ≤ (A ⊔ _ : 𝔹), apply le_trans (by simp : ⊤ ≤ A ⊔ -A), apply sup_le_sup, refl, dsimp[A], rw[lattice.neg_neg], apply supr_le, intro j, apply le_trans (this_ih j j.property), unfold witness_antichain, apply supr_le_supr, intro i', apply supr_le, intro H', cases H', subst H', apply le_supr_of_le, exact j.property, refl, apply le_supr_of_le, apply down_set_trans, exact j.property, exact H', refl end end smallness lemma maximum_principle (ϕ : bSet 𝔹 → 𝔹) (h_congr : B_ext ϕ) : ∃ u, (⨆(x:bSet 𝔹), ϕ x) = ϕ u := begin have := classical.indefinite_description _ (@ordinal.well_ordering_thm (type (@B_small_witness _ _ ϕ))), cases this with r inst_r, haveI : is_well_order _ r := by assumption, let w := @B_small_witness _ _ ϕ, have from_mixing_lemma := mixing_lemma ((witness_antichain r)) (w.func) (λ i j, by {by_cases i = j, finish, simp[witness_antichain_index r h]}), rcases from_mixing_lemma with ⟨u, H_w⟩, use u, fapply le_antisymm, {rw[B_small_witness_supr], have H1 : (⨆(b : type B_small_witness), (witness_antichain r) b) ≤ ϕ u, apply supr_le, intro ξ, have this'' : ∀ b, (witness_antichain r) b ≤ u =ᴮ func w b ⊓ b.val, by {intro b, apply le_inf, apply H_w b, apply witness_antichain_property}, have this''' : ∀ b, u =ᴮ func w b ⊓ (ϕ (func B_small_witness b)) ≤ ϕ u, intro b, dsimp[w], rw[bv_eq_symm], apply h_congr, apply le_trans, exact this'' ξ, convert this''' ξ, apply (B_small_witness_spec _).symm, suffices H2 : (⨆(b' : type (@B_small_witness _ _ ϕ)), ϕ (func B_small_witness b')) ≤ ⨆(b : type (@B_small_witness _ _ ϕ)), (witness_antichain r) b, from le_trans H2 H1, apply supr_antichain2_contains}, {apply le_supr} end /-- extract an element witnessing a 𝔹-valued existential -/ lemma exists_convert {ϕ : bSet 𝔹 → 𝔹} {Γ : 𝔹} (H : Γ ≤ ⨆x, ϕ x) (H_congr : B_ext ϕ . H_congr_handler) : ∃ u, Γ ≤ ϕ u := by {rcases (maximum_principle ϕ ‹_›) with ⟨u, Hu⟩, use u, finish} lemma maximum_principle_verbose {ϕ : bSet 𝔹 → 𝔹} {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} {b : 𝔹} (h_eq_top L : (⨆(x:bSet 𝔹), ϕ x) = b) : ∃ u, ϕ u = b := by cases maximum_principle ϕ h_congr with w h; from ⟨w, by finish⟩ /-- "∃ x ∈ u, ϕ x implies ∃ x : bSet 𝔹, ϕ x", but this time, say it in Boolean -/ lemma weaken_ex_scope {α : Type*} (A : α → bSet 𝔹) (ϕ : bSet 𝔹 → 𝔹) : (⨆(a : α), ϕ (A a)) ≤ (⨆(x : bSet 𝔹), ϕ x) := supr_le $ λ a, le_supr_of_le (A a) (by refl) lemma maximum_principle_bounded_top {ϕ : bSet 𝔹 → 𝔹} {h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y} {α : Type*} {A : α → bSet 𝔹} (h_eq_top : (⨆(a:α), ϕ (A a)) = ⊤) : ∃ u, ϕ u = ⊤ := @maximum_principle_verbose 𝔹 (by apply_instance) ϕ h_congr ⊤ (by {have := weaken_ex_scope A ϕ, finish}) (by {have := weaken_ex_scope A ϕ, finish}) /-- Convert a Boolean-valued ∀∃-statement into a Prop-valued ∀∃-statement Given A : α → bSet 𝔹, a binary function ϕ : bSet 𝔹 → bSet 𝔹 → 𝔹, a truth-value assignment B : α → 𝔹, ∀ i : α, there exists a y_i : bSet 𝔹, such that (B i ⟹ ϕ (A i) y_i) ≥ ⨅(i:α), B i ⟹ ⨆(y : bSet 𝔹), ϕ(A i, bSet 𝔹) A more verbose, but maybe clearer way to see this is: if there is an equality (⨅i-⨆j body i j) = b, then for all i, there exists j, such that body i j ≥ b This is a consequence of the maximum principle. -/ lemma AE_convert {α 𝔹 : Type*} [nontrivial_complete_boolean_algebra 𝔹] (A : α → bSet 𝔹) (B : α → 𝔹) (ϕ : bSet 𝔹 → bSet 𝔹 → 𝔹) (h_congr : ∀ z, B_ext (λ x, ϕ z x)) : ∀ i : α, ∃ y : bSet 𝔹, (⨅(j:α), (B j ⟹ ⨆(z : bSet 𝔹), ϕ (A j) z)) ≤ (B i ⟹ ϕ (A i) y) := λ i, by {have := maximum_principle (λ y, ϕ (A i) y) (by {intros x y, apply h_congr}), rcases this with ⟨u', H'⟩, use u', apply infi_le_of_le i, apply imp_le_of_right_le, from le_of_eq H'} lemma AE_convert' (ϕ : bSet 𝔹 → bSet 𝔹 → 𝔹) (h_congr : ∀ z, B_ext (λ x, ϕ z x)) (x : bSet 𝔹) : ∀ v : bSet 𝔹, ∃ w : bSet 𝔹, ∀ {Γ : 𝔹}, (Γ ≤ ⨅ z, z ∈ᴮ x ⟹ ⨆ w, ϕ z w) → Γ ≤ v ∈ᴮ x → Γ ≤ ϕ v w := begin intro v, have := maximum_principle (λ y, ϕ v y) (by simp*), rcases this with ⟨u, Hu⟩, use u, intros Γ H_AE H_mem, dsimp at Hu, rw ←Hu, change _ ≤ ⨆ y, _, exact (H_AE v ‹_›) end section mixing_corollaries -- The lemmas in this section are corollaries of the mixing lemma variables (X u₁ u₂ : bSet 𝔹) (a₁ a₂ : 𝔹) (h_anti : a₁ ⊓ a₂ = ⊥) (h_partition : a₁ ⊔ a₂ = ⊤) include h_partition lemma two_term_mixture_mem_top (h₁ : u₁ ∈ᴮ X = ⊤) (h₂ : u₂ ∈ᴮ X = ⊤) : two_term_mixture a₁ a₂ h_anti u₁ u₂ ∈ᴮ X = ⊤:= begin let U := _, change U ∈ᴮ X= _, apply top_unique, have : ⊤ ≤ U =ᴮ u₁ ⊔ U =ᴮ u₂, by {rw[h_partition.symm], have := mixing_lemma_two_term a₁ a₂ h_anti u₁ u₂,apply sup_le_sup, tidy}, have : ⊤ ≤ (U =ᴮ u₁ ⊔ U =ᴮ u₂) ⊓ (u₁ ∈ᴮ X ⊓ u₂ ∈ᴮ X), by finish, apply le_trans this, apply bv_or_elim_left; [rw[<-inf_assoc], ac_change (U =ᴮ u₂ ⊓ u₂ ∈ᴮ X) ⊓ u₁ ∈ᴮ X ≤ U ∈ᴮ X]; apply inf_le_left_of_le; rw[bv_eq_symm]; apply subst_congr_mem_left end lemma two_term_mixture_subset_top (H : a₁ = u₂ ⊆ᴮ u₁) : ⊤ ≤ u₂ ⊆ᴮ (two_term_mixture a₁ a₂ h_anti u₁ u₂) := begin let U := _, change _ ≤ u₂ ⊆ᴮ U, rw[subset_unfold'], bv_intro w, apply bv_imp_intro, rw[top_inf_eq], simp only [mem_unfold], apply bv_Or_elim, intro i, fapply bv_use, exact ⟨ulift.up tt,i⟩, refine inf_le_inf _ (by refl), simp, rw[sup_inf_left_right_eq], repeat{apply bv_and_intro}, {rw[h_partition], apply le_top}, {apply le_sup_right_of_le, cases u₂, apply mem.mk}, {have : a₂ = - a₁, by apply eq_neg_of_partition; assumption, conv {to_rhs, congr, skip, rw[this, H]}, rw[sup_comm], change _ ≤ _ ⟹ _, apply bv_imp_intro, rw[inf_comm], simp only [subset_unfold], apply bv_specialize_left i, apply bv_imp_elim}, {apply le_sup_right_of_le, cases u₂, apply mem.mk} end end mixing_corollaries lemma core_aux_lemma (ϕ : bSet 𝔹 → 𝔹) (h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y) (h_definite : (⨆(w : bSet 𝔹), ϕ w) = ⊤) (v : bSet 𝔹) : ∃ u : bSet 𝔹, ϕ u = ⊤ ∧ ϕ v = u =ᴮ v := begin have := maximum_principle ϕ h_congr, cases this with w H_w, let b := ϕ v, let u := two_term_mixture b (- b) (by simp) v w, use u, have h_partition : b ⊔ (- b) = ⊤, by simp, have H_max : ϕ u = ⊤, by {apply top_unique, rw[<-h_partition], apply le_trans, apply sup_le_sup, apply le_inf, apply (mixing_lemma_two_term _ _ _ _ _).left, exact -b, simp, exact v, exact w, refl, apply le_inf, apply (mixing_lemma_two_term _ _ _ _ _).right, exact b, simp, exact v, exact w, swap, exact ϕ w, rw[<-H_w, h_definite], apply le_top, apply bv_or_elim; rw[bv_eq_symm]; apply h_congr}, refine ⟨H_max, _⟩, apply le_antisymm, {apply (mixing_lemma_two_term _ _ _ _ _).left}, {suffices : u =ᴮ v ⊓ ϕ u ≤ ϕ v, by {rw[H_max] at this, finish}, by apply h_congr} end lemma core_aux_lemma2 (ϕ ψ : bSet 𝔹 → 𝔹) (h_congrϕ : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y) (h_congrψ : ∀ x y, x =ᴮ y ⊓ ψ x ≤ ψ y) (h_sub : ∀ u, ϕ u = ⊤ → ψ u = ⊤) (h_definite : (⨆(w : bSet 𝔹), ϕ w) = ⊤) : (⨅(x : bSet 𝔹), ϕ x ⟹ ψ x) = ⊤ := begin simp, intro x, have := core_aux_lemma ϕ h_congrϕ h_definite x, rcases this with ⟨u, ⟨h₁, h₂⟩⟩, have := h_sub u ‹_›, rw[show ϕ x = ϕ x ⊓ ⊤, by simp], rw[<-this, h₂], apply h_congrψ end section smallness' variables {α : Type u} (ϕ : bSet 𝔹 → α) -- in this section we prove the smallness-type arguments required for showing that cores always exist. @[reducible, simp]noncomputable def fiber_lift' (b : ϕ '' set.univ) : {x : bSet 𝔹 // ϕ x = b.val} := classical.indefinite_description (λ a : bSet 𝔹, ϕ a = b.val) $ by {cases b.property, use w, exact h.right} end smallness' section cores @[reducible]def pullback_eq_rel {α β : Type*} (f : α → β) (E : β → β → Prop) : α → α → Prop := λ a₁ a₂, E (f a₁) (f a₂) def core {α : Type u} (u : bSet 𝔹) (S : α → bSet 𝔹) : Prop := (∀ x : α, S x ∈ᴮ u = ⊤) ∧ (∀ y : bSet 𝔹, y ∈ᴮ u = ⊤ → ∃! x_y : α, y =ᴮ S x_y = ⊤) noncomputable def core_witness {α : Type u} {u : bSet 𝔹} {S : α → bSet 𝔹} (h_core : core u S) (x : bSet 𝔹) (h_X : x ∈ᴮ u = ⊤) : Σ' (x_y : α), x =ᴮ S x_y = ⊤ := begin cases h_core, specialize h_core_right x h_X, have := classical.indefinite_description _ h_core_right, use this.val, tidy end lemma core_inj {α : Type u} (u : bSet 𝔹) (S : α → bSet 𝔹) (h_core : core u S) : function.injective S := begin intros x y H, cases h_core, have h_left₁ := h_core_left x, have h_left₂ := h_core_left y, have this_right₁ := h_core_right (S x) h_left₁, have this_right₂:= h_core_right (S y) h_left₂, rcases this_right₁ with ⟨w₁, ⟨H₁, H₂⟩⟩, rcases this_right₂ with ⟨w₂, ⟨H₁', H₂'⟩⟩, have Q₂ := H₂ y, have Q₃ := H₂ x (by apply bv_eq_refl), dsimp at *, rw[Q₂], swap, simpa[H] end /-- `core_inj` says that if a b : α satisfy S a =ᴮ S b = ⊤, then a = b -/ lemma core_inj' {α : Type u} {u : bSet 𝔹} {S : α → bSet 𝔹} (h_core : core u S) : ∀ a b : α, S a =ᴮ S b = ⊤ → a = b := begin intros x y H, cases h_core, have h_left₁ := h_core_left x, have h_left₂ := h_core_left y, have this_right₁ := h_core_right (S x) h_left₁, have this_right₂:= h_core_right (S y) h_left₂, rcases this_right₁ with ⟨w₁, ⟨H₁, H₂⟩⟩, rcases this_right₂ with ⟨w₂, ⟨H₁', H₂'⟩⟩, have Q₂ := H₂ y H, have Q₂ := H₂ x (by apply bv_eq_refl), cc end /-- This is the "f_x" in the notes. We are free to use function types since universes are inaccessible. -/ def core.mk_ϕ (u : bSet 𝔹) : bSet 𝔹 → (u.type → 𝔹) := λ x, (λ a, (u.bval a) ⊓ x =ᴮ u.func a ) lemma core.mk_ϕ_inj (u : bSet 𝔹) (x y : bSet 𝔹) : (x ∈ᴮ u = ⊤) → (y ∈ᴮ u = ⊤) → core.mk_ϕ u x = core.mk_ϕ u y → x =ᴮ y = ⊤ := begin intros h₁ h₂ H, unfold core.mk_ϕ at H, replace H := congr_fun H, apply top_unique, have : ∀ i_z : u.type, u.bval i_z ⊓ x =ᴮ u.func i_z ⊓ u.bval i_z ⊓ u.func i_z =ᴮ y ≤ x =ᴮ y := λ i_z, by {tidy_context, from bv_trans (‹_› : Γ ≤ x =ᴮ func u i_z) ‹_›}, dsimp at H, simp[H] at this, rw[<-supr_le_iff] at this, rw[eq_top_iff] at h₂, refine le_trans _ this, convert h₂, rw[mem_unfold], congr' 1, ext, refine le_antisymm _ _; tidy_context, from ⟨⟨⟨‹_›,‹_›⟩,‹_›⟩, bv_symm ‹_›⟩ end noncomputable def core.S' (u : bSet 𝔹) : (core.mk_ϕ u '' set.univ) → bSet 𝔹 := λ x, (fiber_lift' (core.mk_ϕ u) x).val def core.α_S'' (u : bSet 𝔹) : Type u := {i : core.mk_ϕ u '' set.univ // core.S' u i ∈ᴮ u = ⊤} noncomputable def core.S'' (u : bSet 𝔹) : core.α_S'' u → bSet 𝔹 := λ x, core.S' u x.val lemma core.S'_spec (u : bSet 𝔹) (x : core.mk_ϕ u '' set.univ) : core.mk_ϕ u (core.S' u x) = x.val := by unfold core.S'; simp[(fiber_lift' (core.mk_ϕ u) x).property] def core.bv_eq_top : bSet 𝔹 → bSet 𝔹 → Prop := λ x₁ x₂, x₁ =ᴮ x₂ = ⊤ def core.bv_eq_top_setoid : setoid $ bSet 𝔹 := { r := core.bv_eq_top, iseqv := begin repeat{split}, {apply bv_eq_refl}, {dsimp[core.bv_eq_top], tidy, rwa[bv_eq_symm]}, {dsimp[core.bv_eq_top], tidy, apply top_unique, rw[show ⊤ = x =ᴮ y ⊓ y =ᴮ z, by finish], apply bv_eq_trans} end} instance core.S''_setoid (u : bSet 𝔹) : setoid $ core.α_S'' u := { r := pullback_eq_rel (core.S'' u) core.bv_eq_top, iseqv := begin repeat{split}, intro x, apply bv_eq_refl, intros x y, intro H, unfold pullback_eq_rel core.bv_eq_top, rwa[bv_eq_symm], intros x y z, unfold pullback_eq_rel core.bv_eq_top, intros H₁ H₂, apply top_unique, rw[show ⊤ = (core.S'' u x) =ᴮ (core.S'' u y) ⊓ (core.S'' u y) =ᴮ (core.S'' u z), by finish], apply bv_eq_trans end} noncomputable def core.mk_aux (u : bSet 𝔹) : (quotient (@core.S''_setoid 𝔹 _ u)) → bSet 𝔹 := λ x, (core.S'' u) (@quotient.out _ (core.S''_setoid u ) x) @[reducible]private def image.mk {α β : Type*} {f : α → β} (a : α) : f '' set.univ := ⟨f a, by tidy⟩ lemma core.mk (u : bSet 𝔹) : ∃ α : Type u, ∃ S : α → bSet 𝔹, core u S := begin repeat{split}, show _ → bSet 𝔹, exact core.mk_aux u, {dsimp, intro x,unfold core.mk_aux, let y := _, change core.S'' u y ∈ᴮ u = _, apply y.property}, {intros y H_y, let y' := (core.S' u (image.mk y)), have H_y' : core.mk_ϕ u y = core.mk_ϕ u y', by rw[core.S'_spec], have H_y'2 : y' ∈ᴮ u = ⊤, by {unfold core.mk_ϕ at H_y', have := congr_fun H_y', simp only [mem_unfold], apply top_unique, conv {to_rhs, congr, rw[<-H_y']}, simpa[mem_unfold] using H_y}, let y'' := (core.mk_aux u ⟦by split; exact H_y'2⟧), have H_y'' : y'' =ᴮ y' = ⊤, by {dsimp[y''], unfold core.mk_aux, have := quotient.mk_out, show setoid _, exact core.S''_setoid u, apply this}, have H₃ : y =ᴮ y' = ⊤, by {apply core.mk_ϕ_inj, repeat{assumption}}, have H₁ : y =ᴮ y'' = ⊤, by {apply top_unique, apply le_trans, show 𝔹, from y =ᴮ y' ⊓ y' =ᴮ y'', apply le_inf, {rw[<-eq_top_iff], exact H₃}, {rw[<-eq_top_iff], convert H_y'' using 1, apply bv_eq_symm}, apply bv_eq_trans}, split, refine ⟨H₁, _⟩, intros i H_y''', suffices : core.mk_aux u i =ᴮ y' = ⊤, by {have : core.mk_aux u i =ᴮ y'' = ⊤, by {apply top_unique, rw[eq_top_iff] at *, apply bv_trans this, convert H_y'' using 1, apply bv_eq_symm}, dsimp[y''] at this, unfold core.mk_aux at this_1, have : ⟦quotient.out i⟧ = ⟦quotient.out ⟦⟨image.mk y, H_y'2⟩⟧⟧, by {apply quotient.sound, exact this_1}, convert this using 1; rw[quotient.out_eq]}, apply top_unique, rw[bv_eq_symm] at H_y''', rw[show ⊤ = (core.mk_aux u i =ᴮ y ⊓ y =ᴮ y'), by {dsimp at H_y''', rw [H₃, H_y'''], simp}], apply bv_eq_trans} end /-- Given a subset C of α, and an α-indexed core S, return the bSet whose underlying type is C, such that A is the canonical inclusion and B is always ⊤. -/ def bSet_of_core_set {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} (h : core u S) (C : set α) : bSet 𝔹 := ⟨C, λ x, S x, λ x, ⊤⟩ def bSet_of_core {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} (h : core u S) : bSet 𝔹 := bSet_of_core_set h set.univ @[simp]lemma of_core_type {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} {h : core u S} {C : set α} : (bSet_of_core_set h C).type = C := rfl @[simp]lemma of_core_bval {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} {h : core u S} {C : set α} {i} : (bSet_of_core_set h C).bval i = ⊤ := rfl lemma of_core_mem {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} {h : core u S} {C : set α} {i} : ⊤ ≤ (bSet_of_core_set h C).func i ∈ᴮ u := top_le_iff.mpr (h.left _) /-- Given a core S for u, pull back the ordering -/ def subset' {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} (h : core u S) : α → α → Prop := λ a₁ a₂, S a₁ ⊆ᴮ S a₂ = ⊤ open classical zorn def subset'_partial_order {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} (h : core u S) : partial_order α := { le := subset' h, lt := λ a₁ a₂, (subset' h a₁ a₂) ∧ a₁ ≠ a₂, le_refl := by {simp[subset']}, le_trans := by {intros a b c, simp only [subset'], intros, rw[eq_top_iff] at a_1 a_2 ⊢, from subset_trans' ‹_› ‹_›}, lt_iff_le_not_le := begin /- `tidy` says -/ intros a b, cases h, dsimp at *, fsplit, work_on_goal 0 { intros a_1, cases a_1, fsplit, work_on_goal 0 { assumption }, intros a_1 }, work_on_goal 1 { intros a_1, cases a_1, fsplit, work_on_goal 0 { assumption }, intros a_1, induction a_1, solve_by_elim }, dsimp[subset'] at *, suffices : S a = S b, by {have := core_inj u _ ⟨h_left, h_right⟩ this, contradiction}, suffices : a = b, by rw[this]; refl, apply core_inj' ⟨h_left, h_right⟩, dsimp, rw[eq_top_iff] at a_1_left a_1 ⊢, from subset_ext ‹_› ‹_› end, le_antisymm := begin intros a b H₁ H₂, apply core_inj' h, unfold subset' at H₁ H₂, rw[eq_top_iff] at H₁ H₂ ⊢, from subset_ext ‹_› ‹_› end} local attribute [instance] subset'_partial_order lemma subset'_trans {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} {h : core u S} : by haveI := subset'_partial_order h; from ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c := by apply partial_order.le_trans lemma subset'_unfold {u : bSet 𝔹} {α : Type u} {S : α → bSet 𝔹} {h : core u S} {a₁ a₂ : α} : by {haveI := subset'_partial_order h, from a₁ ≤ a₂ → (S a₁ ⊆ᴮ S a₂ = ⊤)} := by tidy @[reducible]def exists_mem (x : bSet 𝔹) : 𝔹 := ⨆ (y : bSet 𝔹), y ∈ᴮ x @[reducible]def not_empty (x : bSet 𝔹) : 𝔹 := - (x =ᴮ ∅) -- note: nonempty means "not empty" lemma exists_mem_of_nonempty (u : bSet 𝔹) {Γ : 𝔹} (H : Γ ≤ -(u =ᴮ ∅)) : Γ ≤ ⨆x, x∈ᴮ u := by {apply le_trans H, simp[eq_empty], intro x, apply bv_use (u.func x), apply mem.mk'} lemma nonempty_of_exists_mem (u : bSet 𝔹) {Γ : 𝔹} (H : Γ ≤ (⨆x, x ∈ᴮ u)) : Γ ≤ -(u =ᴮ ∅) := begin {apply le_trans H, simp[eq_empty], intro x, rw[mem_unfold], apply bv_Or_elim, intro i, apply bv_use i, apply inf_le_left} end lemma nonempty_iff_exists_mem {u : bSet 𝔹} {Γ : 𝔹} : Γ ≤ -(u =ᴮ ∅) ↔ Γ ≤ ⨆x, x ∈ᴮ u := begin refine ⟨_,_⟩; intro H, { exact exists_mem_of_nonempty _ ‹_› }, { exact nonempty_of_exists_mem _ ‹_› } end lemma empty_iff_forall_not_mem {u : bSet 𝔹} {Γ : 𝔹} : Γ ≤ u=ᴮ ∅ ↔ Γ ≤ ⨅ x, -(x ∈ᴮ u) := begin refine ⟨_,_⟩; intro H, { apply bv_by_contra, bv_imp_intro H_contra, simp only with bv_push_neg at H_contra, rw ←nonempty_iff_exists_mem at H_contra, bv_contradiction }, { apply bv_by_contra, bv_imp_intro H_contra, rw nonempty_iff_exists_mem at H_contra, rw ←neg_supr at H, bv_contradiction } end lemma core_aux_lemma3 (u : bSet 𝔹) (h_nonempty : -(u =ᴮ ∅) = ⊤) {α : Type u} (S : α → bSet 𝔹) (h_core : core u S) : ∀ x, ∃ y ∈ S '' set.univ, x =ᴮ y = x ∈ᴮ u := begin intro x, have := core_aux_lemma (λ z, z∈ᴮu) (by intros; apply subst_congr_mem_left) (by {apply top_unique, apply exists_mem_of_nonempty, simpa}) x, rcases this with ⟨y, ⟨H₁, H₂⟩⟩, cases h_core with H_left H_right, specialize H_right y H₁, cases H_right with y' H_y', use S y', specialize H_left y', split, use y', finish, dsimp at H₁ H₂, rw[H₂], cases H_y', have := bv_rw H_y'_left (λ z, x =ᴮ z), simpa[bv_eq_symm] using this, intros x₁ y₁, dsimp, rw[inf_comm], exact bv_eq_trans end lemma core_mem_of_mem_image {u y} {α : Type u} {S : α → bSet 𝔹} (h_core : core u S) : y ∈ S '' set.univ → y ∈ᴮ u = ⊤ := by tidy end cores section check_names /- `check` is the canonical embedding of pSet into bSet. note that a check-name is not only definite, but recursively definite -/ @[simp]def check : (pSet.{u}) → bSet 𝔹 | ⟨α,A⟩ := ⟨α, λ a, check (A a), λ a, ⊤⟩ postfix `̌ `:8999 := check @[simp, cleanup]lemma check_type {α : Type u} {A : α → pSet} : bSet.type ((pSet.mk α A)̌ : bSet 𝔹) = α := rfl @[simp, cleanup]lemma check_type_infi {α : Type u} {A : α → pSet} {s : α → 𝔹} : (⨅(a : bSet.type ((pSet.mk α A)̌ : bSet 𝔹)), s a) = (⨅(a : α), s a : 𝔹) := by refl @[simp, cleanup]lemma check_type_supr {α : Type u} {A : α → pSet} {s : α → 𝔹} : (⨆(a : bSet.type ((pSet.mk α A)̌ : bSet 𝔹)), s a) = (⨆(a : α), s a : 𝔹) := rfl @[simp, cleanup]lemma pSet.type_mk {α : Type u} {A : α → pSet} : pSet.type (pSet.mk α A) = α := rfl @[simp, cleanup]lemma check_type' {x : pSet.{u}} : bSet.type (x̌ : bSet 𝔹) = x.type := by {induction x, simp} @[simp, cleanup]lemma check_type'_set {x : pSet} : set (bSet.type (x̌ : bSet 𝔹)) = set (x.type) := by {induction x, simp} @[reducible, simp]def check_cast {x : pSet} (i : (x̌ : bSet 𝔹).type) : x.type := cast check_type' i @[reducible, simp]def check_cast.symm {x : pSet} (i : x.type) : (x̌ : bSet 𝔹).type := cast check_type'.symm i @[reducible, simp] def check_cast_set {x : pSet} (S : set (x̌ : bSet 𝔹).type) : set (x.type) := cast check_type'_set S lemma check_func {x : pSet} {i} : (x̌ : bSet 𝔹).func i = (x.func (check_cast i))̌ := by induction x; refl lemma check_unfold {x : pSet.{u}} : (x̌ : bSet 𝔹) = bSet.mk x.type (λ i, (x.func i)̌ ) (λ i, ⊤) := by induction x; refl @[simp]lemma check_bval_top (x : pSet) {i} : (x̌ : bSet 𝔹).bval i = ⊤ := by induction x; refl @[simp]lemma check_bval_mk {α : Type u} {A : α → pSet} {i} : ((pSet.mk α A)̌ ).bval i = (⊤ : 𝔹) := rfl @[simp]lemma check_empty_eq_empty : (∅ : pSet)̌ = (∅ : bSet 𝔹) := by {change mk _ _ _ = mk _ _ _, congr, tidy} -- this is essentially a restatement of mem.mk/mem.mk', but will be useful later @[simp]lemma mem_top_of_bval_top {u : bSet 𝔹} {i : u.type} {H_top : u.bval i = ⊤} : u.func i ∈ᴮ u = ⊤ := by {apply top_unique, rw[<-H_top], apply mem.mk'} @[simp]lemma check_mem_top {x : pSet} {i : (x̌ : bSet 𝔹).type} : (x̌).func i ∈ᴮ x̌ = ⊤ := by simp /-- TODO(jesse): this name should really belong to check_mem instead -/ @[simp]lemma mem_check_of_mem {x : pSet} {i : x.type} {Γ : 𝔹} : Γ ≤ ((x.func i) ̌) ∈ᴮ (x̌) := begin rw[mem_unfold], apply bv_use (check_cast.symm i), simp only [true_and, type, le_inf_iff, bval, le_top, func, check, check_cast.symm, check_bval_top], convert bv_refl, cases x, refl end lemma check_bv_eq_top_of_equiv {x y : pSet} : pSet.equiv x y → x̌ =ᴮ y̌ = (⊤ : 𝔹) := begin induction x generalizing y, cases y, dsimp[check, bv_eq], simp only [pSet.equiv, lattice.top_le_iff, bSet.check, lattice.top_inf_eq, lattice.imp_top_iff_le, lattice.inf_eq_top_iff, lattice.infi_eq_top], intros a, cases a, split; intro i; apply top_unique; [rcases a_left i with ⟨w, h⟩, rcases a_right i with ⟨w,h⟩]; apply le_supr_of_le w; simp only [lattice.top_le_iff, bSet.check]; apply (x_ih _); exact h end -- deprecated, use check_eq lemma check_bv_eq {x y : pSet} {Γ : 𝔹} (H : pSet.equiv x y) : (Γ : 𝔹) ≤ x̌ =ᴮ y̌ := le_trans (le_top) $ by {simp only [top_le_iff], apply check_bv_eq_top_of_equiv ‹_›} lemma check_eq {x y : pSet} {Γ : 𝔹} (H : pSet.equiv x y) : (Γ : 𝔹) ≤ x̌ =ᴮ y̌ := check_bv_eq H -- deprecated, use check_not_eq lemma check_bv_eq_bot_of_not_equiv {x y : pSet} : (¬ pSet.equiv x y) → (x̌ =ᴮ y̌) = (⊥ : 𝔹) := begin induction x generalizing y, cases y, dsimp[check], intro H, apply bot_unique, cases pSet.not_equiv H with H H; cases H with w H_w; [apply inf_le_left_of_le, apply inf_le_right_of_le]; apply infi_le_of_le (w); simp[-le_bot_iff]; intro a'; rw[le_bot_iff]; apply x_ih; apply H_w end lemma check_bv_eq_dichotomy (x y : pSet) : (x̌ =ᴮ y̌ = (⊤ : 𝔹)) ∨ (x̌ =ᴮ y̌ = (⊥ : 𝔹)) := begin haveI : decidable (pSet.equiv x y) := by apply classical.prop_decidable, by_cases pSet.equiv x y; [left, right]; [apply check_bv_eq_top_of_equiv, apply check_bv_eq_bot_of_not_equiv]; assumption end lemma check_bv_eq_iff {x y : pSet} : pSet.equiv x y ↔ x̌ =ᴮ y̌ = (⊤ : 𝔹) := begin induction x generalizing y, cases y, dsimp[check, bv_eq], simp only [pSet.equiv, lattice.top_le_iff, bSet.check, lattice.top_inf_eq, lattice.imp_top_iff_le, lattice.inf_eq_top_iff, lattice.infi_eq_top], fsplit, work_on_goal 0 { intros a, cases a, fsplit, work_on_goal 0 { intros i }, work_on_goal 1 { intros i } }, work_on_goal 2 { intros a, cases a, fsplit, work_on_goal 0 { intros a}}, work_on_goal 3 {intros b}, {apply top_unique, rcases a_left i with ⟨w, h⟩, apply le_supr_of_le w, simp only [lattice.top_le_iff, bSet.check], apply (x_ih _).mp, exact h}, {apply top_unique, rcases a_right i with ⟨w, h⟩, apply le_supr_of_le w, simp only [lattice.top_le_iff, bSet.check], apply (x_ih _).mp, exact h}, all_goals{have := supr_eq_top_max, cases this with w h, use w, apply (x_ih _).mpr, apply h, exact nontrivial.bot_lt_top}, apply a_left, work_on_goal 1 {apply a_right}, all_goals{intros a' H, have := check_bv_eq_dichotomy (x_A ‹x_α›) (y_A ‹y_α›), tidy} end lemma not_check_bv_eq_iff {x y : pSet} : ¬ pSet.equiv x y ↔ x̌ =ᴮ y̌ = (⊥ : 𝔹) := begin refine ⟨_,_⟩; intro H, { exact check_bv_eq_bot_of_not_equiv ‹_› }, { intro H_equiv, have := check_bv_eq_top_of_equiv ‹_›, suffices this : ⊥ < (⊥ : 𝔹), by exact lt_irrefl' this, rw[this] at H, conv{to_rhs, rw[<-H]}, simp } end lemma check_not_eq {x y : pSet.{u}} (H : ¬ pSet.equiv x y) {Γ : 𝔹} : Γ ≤ -(x̌ =ᴮ y̌) := by {rw[not_check_bv_eq_iff.mp H], simp} lemma check_bv_eq_nonzero_iff_eq_top {x y : pSet} : (⊥ : 𝔹) < x̌ =ᴮ y̌ ↔ x̌ =ᴮ y̌ = (⊤ : 𝔹) := begin refine ⟨_,_⟩; intro H, { by_contra, finish[or.resolve_left (check_bv_eq_dichotomy x y) ‹_›] }, { simp* } end lemma check_eq_reflect {x y : pSet} {Γ : 𝔹} (H_lt : ⊥ < Γ) (H_mem : Γ ≤ x̌ =ᴮ y̌) : pSet.equiv x y := begin have := check_bv_eq_nonzero_iff_eq_top.mp (lt_of_lt_of_le H_lt H_mem), rwa ←check_bv_eq_iff at this end @[simp]lemma check_insert (a b : pSet) : (pSet.insert a b)̌ = (bSet.insert1 (ǎ) (b̌) : bSet 𝔹) := by {induction a, induction b, simp[pSet.insert, bSet.insert1], split; ext; cases x; simp} lemma mem_check_witness {y x : pSet.{u}} {Γ : 𝔹} (h_nonzero : ⊥ < Γ) (H : Γ ≤ y̌ ∈ᴮ (x̌)) : ∃ i : x.type, Γ ≤ y̌ =ᴮ (x.func i)̌ := begin rw[mem_unfold] at H, simp at H, have := supr_eq_Gamma_max _ _ _, cases this with w h, use w, tactic.rotate 3, from λ a, (y̌ : bSet 𝔹) =ᴮ (x.func a)̌, from Γ, from ‹_›, cases x, from H, swap, from ‹_›, intros a H, by_contra, cases (@check_bv_eq_dichotomy 𝔹 _ y (pSet.func x a)), { finish }, { contradiction } end lemma check_mem_iff {x y : pSet} : x ∈ y ↔ x̌ ∈ᴮ y̌ = (⊤ : 𝔹) := begin refine ⟨_,_⟩; intro H, { cases y, unfold has_mem.mem pSet.mem at H, cases H with b Hb, rw[<-top_le_iff], apply bv_use b, refine le_inf (by refl) (by rwa[top_le_iff, <-check_bv_eq_iff]) }, { cases y, rw[<-top_le_iff] at H, replace H := mem_check_witness (by simp) H, cases H with b Hb, exact ⟨b, by rwa[top_le_iff, <-check_bv_eq_iff] at Hb⟩} end lemma not_check_mem_iff {x y : pSet} : x ∉ y ↔ x̌ ∈ᴮ y̌ = (⊥ : 𝔹) := begin refine ⟨_,_⟩; intro H, { rw[<-le_bot_iff, mem_unfold], rw[supr_le_iff], intro i, tidy_context, cases y, unfold has_mem.mem pSet.mem at H, push_neg at H, have := check_bv_eq_bot_of_not_equiv (H i), convert a_right, exact this.symm }, { intro this, replace this := check_mem_iff.mp this, suffices this : ⊥ < (⊥ : 𝔹), by exact lt_irrefl' this, rw[this] at H, conv{to_rhs, rw[<-H]}, simp } end -- TODO(jesse): refactor this so that the conclusion is simply Γ ≤ ¬ (x̌ ∈ᴮ y̌) lemma check_not_mem {x y : pSet} : x ∉ y → ∀ {Γ : 𝔹}, Γ ≤ x̌ ∈ᴮ y̌ → Γ ≤ ⊥ := by {intro H, replace H := not_check_mem_iff.mp H, intros Γ HΓ, rwa ←H} lemma check_mem_dichotomy (x y : pSet) : (x̌ ∈ᴮ y̌ = (⊤ : 𝔹)) ∨ (x̌ ∈ᴮ y̌ = (⊥ : 𝔹)) := begin haveI := classical.prop_decidable, by_cases (x ∈ y); {[smt] eblast_using [check_mem_iff, not_check_mem_iff]} end lemma check_mem_nonzero_iff_eq_top {x y : pSet} : (⊥ : 𝔹) < x̌ ∈ᴮ y̌ ↔ x̌ ∈ᴮ y̌ = (⊤ : 𝔹) := begin refine ⟨_,_⟩; intro H, { by_contra, finish[or.resolve_left (check_mem_dichotomy x y) ‹_›] }, { simp* } end lemma check_mem_reflect {x y : pSet} {Γ : 𝔹} (H_lt : ⊥ < Γ) (H_mem : Γ ≤ (x̌ : bSet 𝔹) ∈ᴮ y̌) : x ∈ y := begin have := check_mem_nonzero_iff_eq_top.mp (lt_of_lt_of_le H_lt H_mem), rwa ←check_mem_iff at this end @[simp]lemma check_mem {x y : pSet} {Γ} (h_mem : x ∈ y) : (Γ : 𝔹) ≤ x̌ ∈ᴮ y̌ := begin rw[mem_unfold], cases y, unfold has_mem.mem pSet.mem at h_mem, cases h_mem with w_y H_w_y, apply bv_use w_y, apply le_inf, simp, from check_bv_eq ‹_› end @[simp]lemma check_subset_of_subset {x y : pSet} (h_subset : x ⊆ y) : (⊤ : 𝔹) ≤ x̌ ⊆ᴮ y̌ := begin rw[subset_unfold], unfold has_subset.subset pSet.subset at h_subset, bv_intro x_j, bv_imp_intro H_x_j, cases x with α A, cases y with β B, rcases (h_subset ‹_›) with ⟨b , Hb⟩, apply bv_use b, convert (check_bv_eq ‹_›), simpa[check_func] end lemma check_subset {x y : pSet} {Γ : 𝔹} (h_subset : x ⊆ y) : Γ ≤ x̌ ⊆ᴮ y̌ := le_trans le_top (check_subset_of_subset ‹_›) lemma check_not_subset {x y : pSet} (H : ¬ x ⊆ y) {Γ} : (Γ : 𝔹) ≤ -(x̌ ⊆ᴮ y̌) := begin rw[subset_unfold], simp only with bv_push_neg, rw pSet.subset_iff_all_mem at H, push_neg at H, rcases H with ⟨z,Hz₁,Hz₂⟩, rw pSet.mem_unfold at Hz₁, cases Hz₁ with j Hj, apply bv_use (check_cast.symm j), refine le_inf (by simp) _, rw ←imp_bot, bv_imp_intro H, apply check_not_mem Hz₂, change _ ≤ (λ w, w ∈ᴮ y̌) _, apply bv_rw' (check_eq Hj), simp, cases x, exact H end @[simp]lemma check_exists_mem {y : pSet} (H_exists_mem : ∃ z, z ∈ y ) {Γ : 𝔹} : Γ ≤ exists_mem y̌ := by { rcases H_exists_mem with ⟨z,Hz⟩, apply bv_use ž, simp* } -- note(jesse): this lemma is not true; one also requires that x is a check-name -- lemma definite_mem_definite_iff_of_subset_check {x y : bSet 𝔹} (H_definite₁ : is_definite x) (H_definite₂ : is_definite y) (H_sub : ∃ z : pSet, ⊤ ≤ y ⊆ᴮ ž) : ⊤ ≤ x ∈ᴮ y ↔ ∃ j : y.type, ⊤ ≤ x =ᴮ y.func j := -- begin -- refine ⟨_,_⟩; intro H, -- { rw[mem_unfold] at H, haveI := classical.prop_decidable, by_contra H', push_neg at H', -- simp only [lt_top_iff_not_top_le.symm] at H', -- suffices this : (⨆ (i : type y), bval y i ⊓ x =ᴮ func y i) ≤ ⊥, -- by {rw[le_bot_iff] at this, rw[this] at H, convert H, simp, }, -- replace H := (by refl : (⨆ (i : type y), bval y i ⊓ x =ᴮ func y i) ≤ ⨆ (i : type y), bval y i ⊓ x =ᴮ func y i), -- bv_cases_at H j, specialize H' j, -- suffices this : x =ᴮ func y j ≤ ⊥, -- by {transitivity bval y j ⊓ x =ᴮ func y j, from ‹_›, rw[le_bot_iff] at this, simp[this]}, -- sorry -- }, -- { cases H with j Hj, rw[mem_unfold], apply bv_use j, exact le_inf (by {unfold is_definite at H_definite₂, simp* }) (Hj) } -- end -- lemma instantiate_existential_over_check -- {ϕ : bSet 𝔹 → 𝔹} (H_congr : B_ext ϕ) (x : pSet) {Γ} (H_nonzero : ⊥ < Γ) (H_ex : Γ ≤ ⨆y, (y ∈ᴮ (x̌) ⊓ ϕ (y))) : -- ∃ (Γ' : 𝔹) (H_nonzero : ⊥ < Γ') (H : Γ' ≤ Γ) (z) (H_mem : z ∈ x), Γ' ≤ ϕ (ž) := -- begin -- rw[<-@bounded_exists] at H_ex, swap, by change B_ext _; simpa, -- cases (nonzero_inf_of_nonzero_le_supr H_nonzero H_ex) with i Hi, -- refine ⟨_, Hi, _, _, _, _⟩, -- { tidy_context }, -- { exact (x.func (cast (by cases x; refl) i)) }, -- { convert pSet.mem.mk _ _, simp, }, -- { tidy_context, cases x, exact a_right_right } -- end lemma instantiate_existential_over_check_aux {ϕ : bSet 𝔹 → 𝔹} (H_congr : B_ext ϕ) (x : pSet) {Γ} (H_nonzero : ⊥ < Γ) (H_ex : Γ ≤ ⨆y, (y ∈ᴮ (x̌) ⊓ ϕ (y))) : ∃ i : x.type, ⊥ < (ϕ ((x.func i)̌ ) ⊓ Γ) := begin simp only [inf_comm], rw[<-@bounded_exists] at H_ex, swap, by change B_ext _; simpa, cases (nonzero_inf_of_nonzero_le_supr H_nonzero H_ex) with i Hi, refine ⟨cast check_type' i,_⟩, dsimp at Hi, rw[check_bval_top _, top_inf_eq] at Hi, cases x, exact Hi end noncomputable def instantiate_existential_over_check {ϕ : bSet 𝔹 → 𝔹} (H_congr : B_ext ϕ) (x : pSet) {Γ} (H_nonzero : ⊥ < Γ) (H_ex : Γ ≤ ⨆y, (y ∈ᴮ (x̌) ⊓ ϕ (y))) : x.type := begin apply @classical.some _ (λ i : x.type, ⊥ < ϕ ((x.func i)̌ ) ⊓ Γ), apply instantiate_existential_over_check_aux; from ‹_› end lemma instantiate_existential_over_check_spec {ϕ : bSet 𝔹 → 𝔹} (H_congr : B_ext ϕ) (x : pSet) {Γ} (H_nonzero : ⊥ < Γ) (H_ex : Γ ≤ ⨆y, (y ∈ᴮ (x̌) ⊓ ϕ (y))) : ⊥ < (ϕ ((x.func $ instantiate_existential_over_check ‹_› x ‹_› ‹_›)̌ ) ⊓ Γ) := by {unfold instantiate_existential_over_check, exact classical.some_spec (instantiate_existential_over_check_aux H_congr x H_nonzero ‹_›)} lemma instantiate_existential_over_check_spec₂ (ϕ : bSet 𝔹 → 𝔹) (H_congr : B_ext ϕ) (x : pSet) {Γ} (H_nonzero : ⊥ < Γ) (H_ex : Γ ≤ ⨆y, (y ∈ᴮ (x̌) ⊓ ϕ (y))) : ⊥ < (ϕ ((x.func $ instantiate_existential_over_check ‹_› x ‹_› ‹_›)̌ )) := bot_lt_resolve_right H_nonzero (instantiate_existential_over_check_spec ‹_› x ‹_› ‹_›) /-- This corresponds to Property 4 in Moore's The method of forcing -/ -- we really need the stronger version lemma eq_check_of_mem_check {Γ : 𝔹} (h_nonzero : ⊥ < Γ) {x : pSet.{u}} {y : bSet 𝔹} (H_mem : Γ ≤ y ∈ᴮ x̌) : ∃ (i : x.type) (Γ' : 𝔹) (H_nonzero : ⊥ < Γ') (H_le : Γ' ≤ Γ), Γ' ≤ y =ᴮ (x.func i)̌ := begin let ϕ : bSet 𝔹 → 𝔹 := λ z, y =ᴮ z, let H_congr : B_ext ϕ := (by simp), have H_ex : Γ ≤ ⨆ (y : bSet 𝔹), y ∈ᴮ x̌ ⊓ ϕ y, by {apply bv_use y, from le_inf ‹_› bv_refl}, let i : x.type := instantiate_existential_over_check H_congr x ‹_› H_ex, refine ⟨i,y =ᴮ (x.func i)̌ ⊓ Γ,_,inf_le_right,inf_le_left⟩, { exact instantiate_existential_over_check_spec H_congr _ ‹_› H_ex } end lemma eq_check_of_mem_check₂ {Γ : 𝔹} (h_nonzero : ⊥ < Γ) (x : pSet.{u}) (y : bSet 𝔹) (H_mem : Γ ≤ y ∈ᴮ x̌) : ∃ i : x.type, ⊥ < y =ᴮ (x.func i)̌ := -- ∃ Γ' (H_le : Γ' ≤ Γ) (z) (H_mem : z ∈ x), (Γ' ≤ y =ᴮ ž) := begin rcases (eq_check_of_mem_check ‹_› ‹_›) with ⟨i, Γ', HΓ'₁, HΓ'₂, HΓ'₃⟩, use i, from lt_of_lt_of_le HΓ'₁ ‹_› end end check_names section collect variables (ϕ : bSet 𝔹 → bSet 𝔹 → 𝔹) (h_congr_right : ∀ x y z, x =ᴮ y ⊓ ϕ z x ≤ ϕ z y) (h_congr_left : ∀ x y z, x =ᴮ y ⊓ ϕ x z ≤ ϕ y z) (u : bSet 𝔹) include ϕ h_congr_right h_congr_left u noncomputable def collect.func : u.type → bSet 𝔹 := classical.some $ (classical.axiom_of_choice (AE_convert u.func u.bval ϕ (by { intros z x y, exact h_congr_right x y z }))) lemma collect.func_spec (Γ : 𝔹) (H : Γ ≤ ⨅ (j : type u), bval u j ⟹ ⨆ (z : bSet 𝔹), ϕ (func u j) z) : Γ ≤ ⨅ x : u.type, bval u x ⟹ ϕ (func u x) (collect.func ϕ h_congr_right h_congr_left u x) := begin bv_intro i, bv_imp_intro Hi, let p := (collect.func._proof_1 ϕ h_congr_right u), have := classical.some_spec p, specialize this i, exact poset_yoneda_inv Γ_1 this ‹_› ‹_› end noncomputable def collect : bSet 𝔹 := ⟨u.type, collect.func ϕ h_congr_right h_congr_left u, u.bval⟩ lemma collect_spec₁ {Γ : 𝔹} (H_AE : Γ ≤ ⨅ i : u.type, u.bval i ⟹ ⨆ w, ϕ (u.func i) w) : Γ ≤ ⨅ z, z ∈ᴮ u ⟹ ⨆ w, w ∈ᴮ collect ϕ h_congr_right h_congr_left u ⊓ ϕ z w := begin bv_intro z, bv_imp_intro Hz_mem, rw mem_unfold at Hz_mem, bv_cases_at Hz_mem i Hi, bv_split, apply bv_use (collect.func ϕ ‹_› ‹_› u i), refine le_inf _ _, { unfold collect, rw mem_unfold, apply bv_use i, simp* }, { apply bv_rw' Hi_right, {intros x y, solve_by_elim}, exact collect.func_spec ϕ ‹_› ‹_› u Γ_2 ‹_› i ‹_› } end lemma collect_spec₂ {Γ : 𝔹} (H_AE : Γ ≤ ⨅ i : u.type, u.bval i ⟹ ⨆ w, ϕ (u.func i) w) : Γ ≤ ⨅ w, w ∈ᴮ collect ϕ h_congr_right h_congr_left u ⟹ ⨆ z, z ∈ᴮ u ⊓ ϕ z w := begin -- TODO(jesse): prove mem_collect_iff bv_intro w, bv_imp_intro Hw_mem, rw mem_unfold at Hw_mem, bv_cases_at Hw_mem i Hi, apply bv_use (u.func i), bv_split, apply bv_rw' Hi_right, { refine B_ext_inf _ _, { simp }, { intros x y, solve_by_elim }}, { refine le_inf _ _, { apply mem.mk'', from ‹_› }, { exact collect.func_spec ϕ ‹_› ‹_› u Γ_2 ‹_› i ‹_› }} end end collect -- /-- The (strong) axiom of collection says that for every ϕ(x,y), -- for every set u, ∀ x ∈ u, ∃ y ϕ (x,y) implies there exists a set v -- such that ∀ x ∈ u, ∃ y ∈ v, ϕ (x,y) and all elements of v are obtained -- from an element x in this way. With the other axioms, -- this is equivalent to the usual axiom of replacement. -/ theorem bSet_axiom_of_collection (ϕ : bSet 𝔹 → bSet 𝔹 → 𝔹) (h_congr_right : ∀ x y z, x =ᴮ y ⊓ ϕ z x ≤ ϕ z y) (h_congr_left : ∀ x y z, x =ᴮ y ⊓ ϕ x z ≤ ϕ y z) : ⊤ ≤ ⨅u, (⨅x, x ∈ᴮ u ⟹ ⨆y, ϕ x y) ⟹ ⨆v, (⨅w, w ∈ᴮ u ⟹ ⨆w', w' ∈ᴮ v ⊓ ϕ w w') ⊓ ⨅w', w' ∈ᴮ v ⟹ ⨆w, w ∈ᴮ u ⊓ ϕ w w' := begin bv_intro u, bv_imp_intro, refine le_supr_of_le (collect ϕ h_congr_right h_congr_left u) _, have : Γ ≤ ⨅ (i : type u), bval u i ⟹ ⨆ (w : bSet 𝔹), ϕ (func u i) w, { bv_intro i, bv_imp_intro, exact H (func u i) (mem.mk'' ‹_›) }, apply le_inf, { apply collect_spec₁, exact this }, { apply collect_spec₂, exact this } end /-- The boolean-valued unionset operator -/ def bv_union (u : bSet 𝔹) : bSet 𝔹 := ⟨Σ(i : u.type), (u.func i).type, λ x, (u.func x.1).func x.2, λ x, ⨆(y : u.type), u.bval y ⊓ (u.func x.1).func x.2 ∈ᴮ (u.func y)⟩ lemma func_cast {u x : bSet 𝔹} {i_y : u.type} {α : Type u} {A : α → bSet 𝔹} {B : α → 𝔹} {h : func u i_y = mk α A B} {i_x' : α} : func (func u i_y) (eq.mpr (by rw[h]; refl) i_x') = A i_x' := begin change _ = (mk α A B).func i_x', have : func (mk α A B) (eq.mpr rfl i_x') = func (mk α A B) i_x', by refl, convert this end lemma bv_union_spec (u : bSet 𝔹) : ⊤ ≤ ⨅ (x : bSet 𝔹), (x ∈ᴮ bv_union u ⟹ ⨆ (y : type u), u.bval y ⊓ x ∈ᴮ func u y) ⊓ ((⨆ (y : type u), u.bval y ⊓ x ∈ᴮ func u y) ⟹ x ∈ᴮ bv_union u) := begin bv_intro x, apply le_inf, {simp only [bv_union, lattice.top_le_iff, lattice.imp_top_iff_le, sigma.forall, lattice.supr_le_iff], apply bv_Or_elim, rintro ⟨a,i⟩, apply bv_cases_left, intro a', apply bv_use a', simp only [inf_assoc], apply inf_le_inf, refl, rw[inf_comm,bv_eq_symm], apply B_ext_mem_left}, {simp only [lattice.top_le_iff, bSet.bval, bSet.mem, mem_unfold, lattice.imp_top_iff_le, bSet.func, bSet.type, lattice.supr_le_iff, bv_union], intro i, dsimp, apply bv_cases_right, intro i_1, fapply bv_use, use i, from i_1, apply le_inf, {apply bv_use i, apply inf_le_inf, refl, apply bv_use i_1, apply inf_le_inf, apply refl, simp[bv_eq_refl]}, {rw[<-inf_assoc], apply inf_le_right_of_le, refl}}, end lemma bv_union_spec' (u : bSet 𝔹) {Γ} : Γ ≤ ⨅ (x : bSet 𝔹), (x ∈ᴮ bv_union u ⟹ ⨆ y, y ∈ᴮ u ⊓ x ∈ᴮ y) ⊓ ((⨆ y, y ∈ᴮ u ⊓ x ∈ᴮ y) ⟹ x ∈ᴮ bv_union u) := begin have := bv_union_spec u, bv_intro x, apply le_inf, replace this := this x, bv_split_at this, from le_trans (le_top) (by {bv_imp_intro, replace this_left := this_left ‹_›, bv_cases_at this_left i_y, apply bv_use (u.func i_y), bv_split, from le_inf (mem.mk'' ‹_›) ‹_›}), replace this := this x, bv_split_at this, bv_imp_intro, specialize_context_at this_right Γ_1, replace this_1_1 := this_right _, from ‹_›, rw[@bounded_exists 𝔹 _ u (λ z, x ∈ᴮ z)], from ‹_›, change B_ext _, simp end lemma bv_union_spec_split (u : bSet 𝔹) {Γ} (x : bSet 𝔹) : (Γ ≤ x ∈ᴮ bv_union u) ↔ (Γ ≤ ⨆ y, y ∈ᴮ u ⊓ x ∈ᴮ y) := begin have := bv_union_spec' u, show 𝔹, from Γ, replace this := this x, dsimp at this, bv_split_at this, split; intro, from this_left ‹_›, from this_right ‹_› end lemma mem_bv_union_iff {u : bSet 𝔹} {Γ} {x : bSet 𝔹} : (Γ ≤ x ∈ᴮ bv_union u) ↔ (Γ ≤ ⨆ y, y ∈ᴮ u ⊓ x ∈ᴮ y) := by apply bv_union_spec_split /-- For every x ∈ u, x ⊆ᴮ ⋃ u.-/ lemma bv_union_spec'' (u : bSet 𝔹) : ⊤ ≤ ⨅(x : bSet 𝔹), (x ∈ᴮ u) ⟹ (x ⊆ᴮ bv_union u) := begin bv_intro x, rw[<-deduction], simp[subset_unfold], intro i_v, rw[<-deduction, inf_comm], apply le_trans, apply inf_le_inf, apply mem.mk', refl, have := bv_union_spec u, apply bv_have, apply le_trans, apply le_top, exact this, apply bv_specialize_right (x.func i_v), rw[inf_comm], ac_change (func x i_v ∈ᴮ bv_union u ⟹ ⨆ (y : type u), u.bval y ⊓ func x i_v ∈ᴮ func u y) ⊓ (((⨆ (y : type u), u.bval y ⊓ func x i_v ∈ᴮ func u y) ⟹ func x i_v ∈ᴮ bv_union u) ⊓ (func x i_v ∈ᴮ x ⊓ x ∈ᴮ u)) ≤ func x i_v ∈ᴮ bv_union u, apply inf_le_right_of_le, suffices : (func x i_v ∈ᴮ x ⊓ x ∈ᴮ u) ≤ (⨆ (y : type u), bval u y ⊓ func x i_v ∈ᴮ func u y), by {apply le_trans, apply inf_le_inf, refl, exact this, apply bv_imp_elim}, conv in (x ∈ᴮ u) {simp only [mem_unfold]}, apply bv_cases_right, intro y, apply bv_use y, ac_change bval u y ⊓ (func x i_v ∈ᴮ x ⊓ x =ᴮ func u y) ≤ u.bval y ⊓ (func x i_v ∈ᴮ func u y), apply inf_le_inf, refl, rw[inf_comm], apply subst_congr_mem_right end lemma bv_union_congr {x y : bSet 𝔹} {Γ} (H_eq : Γ ≤ x =ᴮ y) : Γ ≤ bv_union x =ᴮ bv_union y := begin apply mem_ext; bv_intro z; bv_imp_intro, have := bv_union_spec x z, bv_split, specialize_context_at this_left Γ_1, specialize_context_at this_right Γ_1, replace this_left := this_left H, have := bv_union_spec y z, bv_split, specialize_context_at this_left_1 Γ_1, specialize_context_at this_right_1 Γ_1, replace this_right_1 := this_right_1 _, from ‹_›, rw[@bounded_exists 𝔹 _ y (λ w, z ∈ᴮ w)], rw[@bounded_exists 𝔹 _ x (λ w, z ∈ᴮ w)] at this_left, bv_cases_at this_left w, bv_split_at this_left_2, apply bv_use w, apply le_inf, apply bv_rw' (bv_symm H_eq), simp, from ‹_›, from ‹_›, change B_ext _, simp, change B_ext _, simp, have := bv_union_spec y z, bv_split, specialize_context_at this_left Γ_1, specialize_context_at this_right Γ_1, replace this_left := this_left H, have := bv_union_spec x z, bv_split, specialize_context_at this_left_1 Γ_1, specialize_context_at this_right_1 Γ_1, replace this_right_1 := this_right_1 _, from ‹_›, rw[@bounded_exists 𝔹 _ x (λ w, z ∈ᴮ w)], rw[@bounded_exists 𝔹 _ y (λ w, z ∈ᴮ w)] at this_left, bv_cases_at this_left w, bv_split_at this_left_2, apply bv_use w, apply le_inf, apply bv_rw' (H_eq), simp, from ‹_›, from ‹_›, change B_ext _, simp, change B_ext _, simp end @[simp]lemma B_congr_bv_union : B_congr (bv_union : bSet 𝔹 → bSet 𝔹) := by apply bv_union_congr theorem bSet_axiom_of_union : (⨅ (u : bSet 𝔹), (⨆v, ⨅x, (x ∈ᴮ v ⇔ (⨆(y : u.type), u.bval y ⊓ x ∈ᴮ u.func y)))) = ⊤ := begin simp only [bSet.mem, lattice.biimp, bSet.func, lattice.infi_eq_top, bSet.type],intro u, apply top_unique, apply bv_use (bv_union u), exact @bv_union_spec 𝔹 _ u end @[simp]def set_of_indicator {u : bSet 𝔹} (f : u.type → 𝔹) : bSet 𝔹 := ⟨u.type, u.func, f⟩ @[simp, cleanup]lemma set_of_indicator.type {u} {f} : (@set_of_indicator 𝔹 _ u f).type = u.type := rfl @[simp, cleanup]lemma set_of_indicator.func {u} {f} {i}: (@set_of_indicator 𝔹 _ u f).func i = u.func i := rfl @[simp, cleanup]lemma set_of_indicator.bval {u} {f} {i} : (@set_of_indicator 𝔹 _ u f).bval i = f i := rfl -- @[reducible, simp]def set_of_indicator' {u : bSet 𝔹} (f : u.type → 𝔹) : bSet 𝔹 := -- ⟨u.type, u.func, λ i, f i ⊓ u.bval i⟩ def bv_powerset (u : bSet 𝔹) : bSet 𝔹 := ⟨u.type → 𝔹, λ f, set_of_indicator f, λ f, set_of_indicator f ⊆ᴮ u⟩ prefix `𝒫`:80 := bv_powerset -- def bv_powerset' (u : bSet 𝔹) : bSet 𝔹 := -- ⟨u.type → 𝔹, λ f, set_of_indicator' f, λ f, ⊤⟩ --TODO (jesse) try proving bv_powerset and bv_powerset' are equivalent -- example {u : bSet 𝔹} : bv_powerset u =ᴮ bv_powerset' u = ⊤ := -- begin -- apply top_unique, apply le_trans, swap, apply bSet_axiom_of_extensionality, -- bv_intro z, apply le_inf; apply bv_imp_intro; simp[top_inf_eq], -- {unfold bv_powerset, dsimp, apply supr_le, intro f, -- unfold bv_powerset', simp, apply le_supr_of_le f, -- refine le_trans _ (by apply bSet_axiom_of_extensionality), -- bv_intro z', -- have := @bounded_forall _ _ (set_of_indicator f) (λ x, x ∈ᴮ u), dsimp[set_of_indicator] at this, simp[subset_unfold], rw[this], -- rw[deduction], apply infi_le_of_le z', rw[supr_imp_eq], -- apply bv_imp_intro, apply le_inf, apply bv_imp_intro, -- ac_change (⨅ (i : type u), f i ⊓ z' =ᴮ func u i ⟹ z' ∈ᴮ u) ⊓ (z =ᴮ mk (type u) (func u) f ⊓ z' ∈ᴮ z) ≤ z' ∈ᴮ mk (type u) (func u) (λ (i : type u), f i ⊓ bval u i), -- apply le_trans, apply inf_le_inf, refl, apply subst_congr_mem_right, -- rw[inf_comm], rw[deduction], apply supr_le, intro i', -- rw[<-deduction], apply le_supr_of_le i', dsimp, -- repeat{apply le_inf}, apply inf_le_left_of_le, apply inf_le_left_of_le, refl, -- repeat{sorry} -- }, -- {sorry} -- end lemma bSet_axiom_of_powerset' {Γ : 𝔹} (u : bSet 𝔹) : Γ ≤ ⨅(x : bSet 𝔹), x∈ᴮ 𝒫 u ⇔ ⨅(y : x.type), x.bval y ⟹ (x.func y ∈ᴮ u) := begin bv_intro x, apply le_inf, {apply le_trans le_top, rw[<-deduction, top_inf_eq], unfold bv_powerset, apply supr_le, intro χ, suffices : ((set_of_indicator χ) ⊆ᴮ u ⊓ (x =ᴮ (set_of_indicator χ)) : 𝔹) ≤ x ⊆ᴮ u, by {convert this, simp[subset_unfold]}, apply subst_congr_subset_left}, {apply le_trans le_top, have := @bounded_forall _ _ x (λ y, (y ∈ᴮ u)) (by {intros x y, apply subst_congr_mem_left}), rw[this], dsimp, unfold bv_powerset, simp[subset_unfold], fapply le_supr_of_le, from λ i, u.func i ∈ᴮ x, have this' := @bounded_forall _ _ (set_of_indicator (λ y, (u.func y ∈ᴮ x))) (λ y, (y ∈ᴮ u)) (by {intros x y, apply subst_congr_mem_left}), dsimp at this', dsimp, rw[this'], apply le_inf, bv_intro a', apply infi_le_of_le a', erw[supr_imp_eq], bv_intro i_y, apply imp_le_of_left_right_le, swap, refl, rw[inf_comm, bv_eq_symm], apply subst_congr_mem_left, rw[bv_eq_unfold], apply le_inf, {conv {to_rhs, dsimp[mem, bv_eq]}, have := @bounded_forall _ _ x (λ y, ⨆ (a' : type u), func u a' ∈ᴮ x ⊓ y =ᴮ func u a'), rw[this], swap, intros a₁ a₂, dsimp, rw[inf_supr_eq], apply supr_le, intro i, apply le_supr_of_le i, ac_change (a₂ =ᴮ a₁ ⊓ a₁ =ᴮ func u i) ⊓ func u i ∈ᴮ x ≤ func u i ∈ᴮ x ⊓ a₂ =ᴮ func u i, rw[bv_eq_symm], ac_refl, apply le_trans, apply inf_le_inf, apply bv_eq_trans, refl, rw[inf_comm], {bv_intro a₁, dsimp, apply infi_le_of_le a₁, rw[<-deduction], apply le_trans, apply bv_imp_elim', rw[inf_comm, deduction], rw[mem_unfold], apply supr_le, intro i, rw[<-deduction], apply le_supr_of_le i, apply le_inf, rw[inf_assoc], apply inf_le_right_of_le, apply subst_congr_mem_left, ac_change a₁ =ᴮ func u i ⊓ (bval u i ⊓ a₁ ∈ᴮ x) ≤ a₁ =ᴮ func u i, apply inf_le_left_of_le, refl}}, {have := @bounded_forall _ _ (set_of_indicator (λ y, func _ y ∈ᴮ x)) (λ y, y ∈ᴮ x), erw[this], swap, simp[subst_congr_mem_left], bv_intro a₁, apply infi_le_of_le a₁, unfold set_of_indicator, dsimp[mem, bv_eq], rw[supr_imp_eq], bv_intro i, apply from_empty_context, rw[inf_comm, bv_eq_symm], simp[-bv_eq_symm,subst_congr_mem_left]}} end theorem bSet_axiom_of_powerset : (⨅(u : bSet 𝔹), ⨆(v : _), ⨅(x : bSet 𝔹), x∈ᴮ v ⇔ ⨅(y : x.type), x.bval y ⟹ (x.func y ∈ᴮ u)) = ⊤:= begin apply top_unique, bv_intro u, apply bv_use (𝒫 u), apply bSet_axiom_of_powerset' end lemma bv_powerset_spec {u x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ x ⊆ᴮ u ↔ Γ ≤ x ∈ᴮ 𝒫 u := begin have := bSet_axiom_of_powerset' u, show 𝔹, from Γ, simp only [lattice.biimp] at this, replace this := this x, bv_split, rw[subset_unfold], fsplit; intro H; [from this_right ‹_›, from this_left ‹_›] end lemma mem_powerset_iff {u x : bSet 𝔹} {Γ : 𝔹} : Γ ≤ x ∈ᴮ (𝒫 u) ↔ Γ ≤ x ⊆ᴮ u := bv_powerset_spec.symm lemma bv_powerset_congr {Γ : 𝔹} {x y : bSet 𝔹} : Γ ≤ x =ᴮ y → Γ ≤ 𝒫 x =ᴮ 𝒫 y := begin intro H, apply mem_ext; bv_intro z; bv_imp_intro, rw[<-bv_powerset_spec], apply bv_rw' (bv_symm H), simp, rwa[bv_powerset_spec], rw[<-bv_powerset_spec], apply bv_rw' H, simp, rwa[bv_powerset_spec] end @[simp]lemma set_of_indicator_mem.mk {x : bSet 𝔹} {i : x.type} {χ : x.type → 𝔹} {Γ} (H_Γ : Γ ≤ χ i) : Γ ≤ (x.func i) ∈ᴮ (set_of_indicator χ) := by {rw[mem_unfold], apply bv_use i, exact le_inf H_Γ (bv_refl)} @[simp]lemma set_of_indicator_subset {x : bSet 𝔹} {χ : x.type → 𝔹} {Γ} (H_χ : ∀ i, χ i ≤ x.bval i) : Γ ≤ set_of_indicator χ ⊆ᴮ x := begin rw[subset_unfold], bv_intro j, bv_imp_intro H, simpa using le_trans (le_trans H (by solve_by_elim)) (mem.mk' _ _) end @[reducible, simp]def subset.mk {u : bSet 𝔹} (χ : u.type → 𝔹) : bSet 𝔹 := set_of_indicator (λ i, χ i ⊓ (u.bval i)) @[simp]lemma subset.mk_subset {u : bSet 𝔹} {χ : u.type → 𝔹} {Γ : 𝔹} : Γ ≤ subset.mk χ ⊆ᴮ u := set_of_indicator_subset $ by simp lemma check_set_of_indicator_subset {x : pSet} {χ : x̌.type → 𝔹} {Γ} : Γ ≤ set_of_indicator χ ⊆ᴮ x̌ := set_of_indicator_subset $ by simp instance subset_to_pi {z x y : bSet 𝔹} {Γ : 𝔹} : has_coe_to_fun (Γ ≤ x ⊆ᴮ y) := { F := λ H, (Γ ≤ z ∈ᴮ x → Γ ≤ z ∈ᴮ y), coe := λ H₁ H₂, mem_of_mem_subset H₁ H₂ } lemma mem_set_of_indicator_iff {x : bSet 𝔹} {χ : x.type → 𝔹} {z : bSet 𝔹} {Γ : 𝔹} (H_χ : ∀ i, χ i ≤ x.bval i) : Γ ≤ z ∈ᴮ set_of_indicator χ ↔ Γ ≤ ⨆(i : x.type), z =ᴮ (x.func i) ⊓ χ i := begin refine ⟨_,_⟩; intro H, { rw[mem_unfold] at H, bv_cases_at H i Hi, apply bv_use i, exact le_inf (bv_and.right Hi) (bv_and.left Hi) }, { bv_cases_at H i Hi, bv_split, apply bv_rw' Hi_left, simp, apply set_of_indicator_mem.mk, from ‹_› } end lemma mem_subset.mk_iff {x : bSet 𝔹} {χ : x.type → 𝔹} {z : bSet 𝔹} {Γ : 𝔹} : Γ ≤ z ∈ᴮ subset.mk χ ↔ Γ ≤ ⨆ (i : x.type), z =ᴮ (x.func i) ⊓ (χ i ⊓ (x.bval i)) := mem_set_of_indicator_iff $ by simp -- same as mem_subset.mk_iff, but with better ordering of terms on the RHS lemma mem_subset.mk_iff₂ {x : bSet 𝔹} {χ : x .type → 𝔹} {z : bSet 𝔹} {Γ : 𝔹} : Γ ≤ z ∈ᴮ subset.mk χ ↔ Γ ≤ ⨆ (i : x.type), x.bval i ⊓ (z =ᴮ (x.func i) ⊓ χ i) := by { rw mem_subset.mk_iff, congr' 3, ext, ac_refl } @[simp]lemma mem_of_mem_subset.mk {x : bSet 𝔹} {χ : x.type → 𝔹} {z} {Γ} (Hz : Γ ≤ z ∈ᴮ subset.mk χ) : Γ ≤ z ∈ᴮ x := mem_of_mem_subset (subset.mk_subset) ‹_› /-- For x an injective pSet and χ : x̌.type → 𝔹, ⊤ ≤ (x.func i) ∈ set_of_indicator χ iff χ i = ⊤. -/ lemma check_mem_set_of_indicator_iff {x : pSet} (H_inj : ∀ i₁ i₂ : x.type, pSet.equiv (x.func i₁) (x.func i₂) → i₁ = i₂) (i : x.type) {χ : x̌.type → 𝔹} : (∀{Γ}, Γ ≤ (x.func i)̌ ∈ᴮ set_of_indicator χ) ↔ (∀ {Γ}, Γ ≤ χ (cast check_type'.symm i)) := begin refine ⟨_,_⟩; intro H, { intro Γ, have H' := @H Γ, bv_cases_at H' j, bv_split, haveI := classical.prop_decidable, by_cases i = (cast check_type' j), { subst h, convert H'_1_left, cases x, refl }, { replace H_inj := mt (H_inj i (cast check_type' j)) ‹_›, have := check_bv_eq_bot_of_not_equiv ‹_›, transitivity ⊥, { rw[<-this], convert H'_1_right, cases x, refl }, { exact bot_le }}}, { intro Γ, specialize @H Γ, apply bv_use (cast check_type'.symm i), cases x, exact le_inf ‹_› bv_refl } end lemma subset_of_pointwise_bounded {Γ : 𝔹} {x : bSet 𝔹} {p : x.type → 𝔹} {p' : x.type → 𝔹} (H_bd : ∀ i : x.type, p i ≤ p' i) : Γ ≤ set_of_indicator p ⊆ᴮ set_of_indicator p' := begin simp[subset_unfold], intro i, bv_imp_intro, apply bv_use i, from le_inf (le_trans H (by simp*)) bv_refl end lemma pointwise_bounded_of_check_subset_check {x : pSet} {p₁ p₂ : x̌.type → 𝔹} (H_inj : ∀ i₁ i₂ : x.type, pSet.equiv (x.func i₁) (x.func i₂) → i₁ = i₂)(H_eq : ∀ {Γ}, Γ ≤ (set_of_indicator p₁ ⊆ᴮ set_of_indicator p₂)) : ∀ i, p₁ i ≤ p₂ i := begin intro i, have : (p₁ i) ≤ (set_of_indicator p₁ ⊆ᴮ set_of_indicator p₂) := H_eq, unfold set_of_indicator at this, rw[subset_unfold] at this, replace this := this i (by refl), refine le_trans this _, simp[mem, bv_eq], intro j, haveI := classical.prop_decidable, by_cases i = j, { subst h, simp }, { specialize H_inj (cast check_type' i) (cast check_type' j), replace H_inj := mt H_inj, suffices this : ¬pSet.equiv (pSet.func x (cast check_type' i)) (pSet.func x (cast check_type' j)), by {refine inf_le_right_of_le _, convert bot_le, convert check_bv_eq_bot_of_not_equiv ‹_›; cases x; simp; refl}, exact (H_inj (by cases x; from ‹_›))} end lemma pointwise_eq_of_eq_set_of_indicator {x : pSet} {p₁ p₂ : x̌.type → 𝔹} (H_inj : ∀ i₁ i₂ : x.type, pSet.equiv (x.func i₁) (x.func i₂) → i₁ = i₂) (H_eq : ∀ {Γ}, Γ ≤ (set_of_indicator p₁ =ᴮ set_of_indicator p₂)) : ∀ i, p₁ i = p₂ i := begin rw[eq_iff_subset_subset] at H_eq, refine (λ i, le_antisymm _ _); { apply pointwise_bounded_of_check_subset_check, from ‹_›, intro Γ, specialize @H_eq Γ, bv_split, from ‹_› } end lemma set_of_indicator_eq_iff_pointwise_eq {x : pSet} {p₁ p₂ : x̌.type → 𝔹} (H_inj : ∀ i₁ i₂ : x.type, pSet.equiv (x.func i₁) (x.func i₂) → i₁ = i₂) : (∀ {Γ}, Γ ≤ (set_of_indicator p₁ =ᴮ set_of_indicator p₂)) ↔ (∀i, p₁ i = p₂ i) := begin refine ⟨_,_⟩, { intro H_eq, apply pointwise_eq_of_eq_set_of_indicator; from ‹_› }, { intros H_eq Γ, rw[show p₁ = p₂, from funext H_eq], simp } end section infinity local notation `ω` := pSet.omega @[simp]lemma check_omega_type : (ω̌ : bSet 𝔹).type = ulift ℕ := rfl @[simp]lemma check_omega_func : (ω̌: bSet 𝔹).func = λ x, check (pSet.of_nat x.down) := rfl postfix `̃ `:70 := pSet.of_nat -- i'm a bit skeptical of this notation @[simp, reducible]def axiom_of_infinity_spec (u : bSet 𝔹) : 𝔹 := (∅∈ᴮ u) ⊓ (⨅(i_x : u.type), ⨆(i_y : u.type), (u.func i_x ∈ᴮ u.func i_y)) @[reducible]def contains_empty (u : bSet 𝔹) : 𝔹 := ∅ ∈ᴮ u @[reducible]def contains_succ (u : bSet 𝔹) : 𝔹 := (⨅(i_x : u.type), ⨆(i_y : u.type), (u.func i_x ∈ᴮ u.func i_y)) lemma infinity_of_empty_succ {u : bSet 𝔹} {c} (h₁ : c ≤ contains_empty u) (h₂ : c ≤ contains_succ u) : c ≤ axiom_of_infinity_spec u := le_inf ‹_› ‹_› lemma contains_empty_check_omega : (⊤ : 𝔹) ≤ contains_empty (ω̌) := by {dsimp[pSet.omega,check, contains_empty], apply bv_use (ulift.up nat.zero), simp[pSet.of_nat]} lemma contains_succ_check_omega : (⊤ : 𝔹) ≤ contains_succ (ω̌) := begin bv_intro n, induction n, apply bv_use (ulift.up (n + 1)), simp only [lattice.top_le_iff, bSet.check_omega_func, bSet.check, bSet.mem, bSet.func, bSet.type], induction n; simp[pSet.of_nat, *] end theorem bSet_axiom_of_infinity : (⨆(u : bSet 𝔹), axiom_of_infinity_spec u) = ⊤ := begin apply top_unique, apply bv_use (ω̌), apply infinity_of_empty_succ, exacts [contains_empty_check_omega, contains_succ_check_omega] end @[reducible]def omega := (ω̌ : bSet 𝔹) @[simp, cleanup]lemma omega_type : (omega : bSet 𝔹).type = ulift ℕ := rfl /-- The n-th von Neumann ordinal in bSet 𝔹 is just the check-name of the n-th von Neumann ordinal in pSet -/ @[reducible]def of_nat : ℕ → bSet 𝔹 := λ n, (pSet.of_nat n)̌ @[simp, cleanup]lemma omega_func {k} : (omega : bSet 𝔹).func k = of_nat k.down := by refl lemma omega_definite {n : ℕ} {Γ : 𝔹} : Γ ≤ of_nat n ∈ᴮ omega := begin suffices : of_nat n ∈ᴮ omega = (⊤ : 𝔹), from le_trans le_top (by rwa[top_le_iff]), induction n, {apply top_unique, apply bv_use (ulift.up 0), simp}, {apply top_unique, apply bv_use (ulift.up (n_n + 1)), simp} end lemma of_nat_mem_omega {n : ℕ} {Γ : 𝔹} : Γ ≤ of_nat n ∈ᴮ omega := omega_definite instance has_zero_bSet : has_zero (bSet 𝔹) := ⟨of_nat 0⟩ instance has_one_bSet : has_one (bSet 𝔹) := ⟨of_nat 1⟩ @[reducible]def two : bSet 𝔹 := of_nat 2 notation `𝟚` := bSet.two lemma zero_eq_empty {Γ : 𝔹} : Γ ≤ 0 =ᴮ ∅ := begin unfold has_zero.zero, unfold bSet.of_nat, rw ←check_empty_eq_empty, apply check_eq, refl end @[simp]lemma zero_mem_one {Γ : 𝔹} : Γ ≤ 0 ∈ᴮ 1 := by {unfold has_zero.zero, apply bv_use none, simp} lemma one_eq_singleton_zero {Γ : 𝔹} : Γ ≤ 1 =ᴮ {0} := begin unfold has_one.one, unfold singleton, unfold has_insert.insert, change Γ ≤ (pSet.insert _ _)̌ =ᴮ _, have := check_insert (0̃ ) (0̃ ), rw this, change _ ≤ bSet.insert1 0 0 =ᴮ bSet.insert1 0 ∅, convert bv_refl, unfold has_zero.zero, unfold of_nat, unfold pSet.of_nat, rw check_empty_eq_empty end --TODO(jesse): add simp lemmas ensuing (0 : bSet 𝔹) is the simp normal form of (∅̌), (of_nat 0), etc lemma forall_empty {Γ : 𝔹} {ϕ : bSet 𝔹 → 𝔹} : Γ ≤ ⨅ x, x ∈ᴮ ∅ ⟹ ϕ x := begin bv_intro x, bv_imp_intro H_mem, refine le_trans _ bot_le, exact bot_of_mem_empty ‹_› end @[simp, cleanup]lemma omega_bval {k} : (omega : bSet 𝔹).bval k = ⊤ := by refl theorem bSet_axiom_of_infinity' : (⊤ : 𝔹) ≤ (∅ ∈ᴮ omega) ⊓ (⨅x, x ∈ᴮ omega ⟹ ⨆y, y ∈ᴮ omega ⊓ x ∈ᴮ y) := begin apply le_inf, apply contains_empty_check_omega, rw [←bounded_forall], rw [infi_congr], swap, intro n, rw [←bounded_exists, omega_bval, top_imp, @supr_congr _ _ _ (λ m, func omega n ∈ᴮ func omega m)], intro m, rw [omega_bval, top_inf_eq], { intros, apply subst_congr_mem_right }, { exact contains_succ_check_omega }, { change B_ext _, simp } end example {w : bSet 𝔹} : let ϕ := λ x, ⨅ z, z ∈ᴮ w ⊓ z ⊆ᴮ x ⊓ x ⊆ᴮ z in B_ext ϕ := by simp end infinity theorem bSet_epsilon_induction (ϕ : bSet 𝔹 → 𝔹) (h_congr : ∀ x y, x =ᴮ y ⊓ ϕ x ≤ ϕ y) : (⨅(x : bSet 𝔹), ((⨅(y : bSet 𝔹), y ∈ᴮ x ⟹ ϕ y) ⟹ ϕ x)) ⟹ (⨅(z : bSet 𝔹), ϕ z) = ⊤ := begin apply top_unique, apply bv_imp_intro, rw[top_inf_eq], bv_intro x, let b := _, change b ≤ _, induction x with α A B ih, dsimp at *, have : b ≤ ⨅(i_y:α), B i_y ⟹ ϕ (A i_y), by {bv_intro i_y, specialize ih i_y, apply le_trans ih, rw[<-deduction], apply inf_le_left}, have h := @bounded_forall _ _ (mk α A B) ϕ h_congr, simp only with cleanup at h, rw[h] at this, apply bv_have this, have : b ≤ (⨅ (y : bSet 𝔹), (y) ∈ᴮ (mk α A B) ⟹ ϕ (y)) ⟹ ϕ (mk α A B), by {apply bv_specialize (mk α A B), refl}, rw[deduction], apply le_trans this, rw[<-deduction], apply bv_imp_elim end -- the natural induction principle for bSet 𝔹 will always suffice where regularity/epsilon_induction are required lemma epsilon_induction {Γ} (ϕ : bSet 𝔹 → 𝔹) (h_congr : B_ext ϕ) (H_ih : ∀ x, Γ ≤ ((⨅(y : bSet 𝔹), y ∈ᴮ x ⟹ ϕ y) ⟹ ϕ x)) : ∀ z, Γ ≤ ϕ z := begin have := bSet_epsilon_induction ϕ h_congr, rw[eq_top_iff] at this, intro z, have H_a : Γ ≤ (⨅ (x : bSet 𝔹), (⨅ (y : bSet 𝔹), y ∈ᴮ x ⟹ ϕ y) ⟹ ϕ x), bv_intro x, specialize H_ih x, from ‹_›, have := le_trans (le_top) this, bv_imp_elim_at this H_a, bv_specialize_at H z, exact H_1 end @[elab_as_eliminator]protected lemma rec_on' {C : bSet 𝔹 → Sort*} (y : bSet 𝔹) : (Π(x : bSet 𝔹), (Π(a : x.type), C (x.func a)) → C x) → C y := by {induction y, intro IH, apply IH, from λ a, y_ih a ‹_›} @[elab_as_eliminator]protected lemma rec' {C : bSet 𝔹 → Sort*} : (Π(x : bSet 𝔹), (Π(a : x.type), C (x.func a)) → C x) → Π(y : bSet 𝔹), C y := by {intro H, intro y, induction y with α A B, solve_by_elim} lemma regularity_aux (x : bSet 𝔹) {Γ : 𝔹} : Γ ≤ ⨅u, x ∈ᴮ u ⟹ (⨆y, y ∈ᴮ u ⊓ (⨅z', z' ∈ᴮ u ⟹ (-(z' ∈ᴮ y)))) := begin apply bSet.rec_on' x, clear x, intros x IH, bv_intro u, bv_imp_intro, have := bv_em_aux Γ_1 (⨅z', z' ∈ᴮ u ⟹ (-(z' ∈ᴮ x))), bv_or_elim_at this, apply bv_use x, from le_inf ‹_› ‹_›, rw[neg_infi] at this.right, bv_cases_at this.right x_a, rw[neg_imp] at this.right_1, bv_split, rw[lattice.neg_neg] at this.right_1_right, rw[mem_unfold] at this.right_1_right, bv_cases_at this.right_1_right a, bv_split, have H_in : Γ_4 ≤ (func x a) ∈ᴮ u, rw[bv_eq_symm] at this.right_1_right_1_right, apply @bv_rw' 𝔹 _ _ _ _ this.right_1_right_1_right (λ z, z ∈ᴮ u) (by simp) _, from ‹_›, from (le_trans (by {dsimp*, simp[inf_le_right_of_le]} : Γ_4 ≤ Γ) (IH a u)) ‹_› end theorem bSet_axiom_of_regularity (x : bSet 𝔹) {Γ : 𝔹} (H : Γ ≤ -(x =ᴮ ∅)) : Γ ≤ (⨆y, y ∈ᴮ x ⊓ (⨅z', z' ∈ᴮ x ⟹ (-(z' ∈ᴮ y)))) := begin rw nonempty_iff_exists_mem at H, bv_cases_at H u Hu, have : Γ_1 ≤ _ := (regularity_aux (u : bSet 𝔹)), exact this x ‹_› end /-- ∃! x, ϕ x ↔ ∃ x ∀ y, ϕ(x) ⊓ ϕ (y) → y = x -/ @[reducible]def bv_exists_unique (ϕ : bSet 𝔹 → 𝔹) : 𝔹 := ⨆(x:bSet 𝔹), (⨅(y : bSet 𝔹), ϕ y ⟹ (y =ᴮ x)) local notation `⨆!` binders `, ` r:(scoped f, bv_exists_unique f) := r section zorns_lemma open classical zorn lemma B_ext_subset_or_subset_left (y : bSet 𝔹) : B_ext (λ x, x ⊆ᴮ y ⊔ y ⊆ᴮ x) := by simp lemma B_ext_subset_or_subset_right (x : bSet 𝔹) : B_ext (λ y, x ⊆ᴮ y ⊔ y ⊆ᴮ x) := by simp lemma forall_forall_reindex (ϕ : bSet 𝔹 → bSet 𝔹 → 𝔹) {h₁ : ∀ x, B_ext (λ y, ϕ x y)} {h₂ : ∀ y, B_ext (λ x, ϕ x y)} {C : bSet 𝔹} : (⨅(i₁:C.type), (C.bval i₁ ⟹ ⨅(i₂ : C.type), C.bval i₂ ⟹ ϕ (C.func i₁) (C.func i₂))) = ⨅(w₁ w₂ : bSet 𝔹), w₁∈ᴮ C ⊓ w₂ ∈ᴮ C ⟹ ϕ w₁ w₂ := begin have := @bounded_forall _ _ C (λ x, ⨅(i₂ : C.type), bval C i₂ ⟹ ϕ x (func C i₂)), rw[this], dsimp at *, apply le_antisymm, bv_intro w₁, bv_intro w₂, apply bv_specialize w₁, rw[<-deduction], simp only [inf_assoc.symm], rw[deduction], apply le_trans, apply bv_imp_elim, have := @bounded_forall _ _ C (λ z, ϕ w₁ z), rw[this], apply bv_specialize w₂, apply bv_imp_intro, apply le_trans, apply bv_imp_elim, refl, intros w₁ w₂, apply h₁, bv_intro w₁, apply infi_le_of_le w₁, apply bv_imp_intro, have := @bounded_forall _ _ C (λ z, ϕ w₁ z), rw[this], bv_intro w₂, apply bv_specialize_left w₂, apply bv_imp_intro, simp only [inf_assoc], apply le_trans, apply bv_imp_elim, refl, intros w₁ w₂, apply h₁, intros w₁ w₂, apply B_ext_infi, intro j, apply B_ext_imp; simp* end lemma subset'_inductive (X : bSet 𝔹) (H : ⊤ ≤ (⨅y, (y ⊆ᴮ X ⊓ (⨅(w₁ : bSet 𝔹), ⨅(w₂ : bSet 𝔹), w₁ ∈ᴮ y ⊓ w₂ ∈ᴮ y ⟹ (w₁ ⊆ᴮ w₂ ⊔ w₂ ⊆ᴮ w₁))) ⟹ (bv_union y ∈ᴮ X))) {α : Type*} {S : α → bSet 𝔹} (h_core : core X S) : by {haveI := subset'_partial_order h_core, from ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub} := begin intros C C_chain, let C' := bSet_of_core_set h_core C, /- First, we show that C' is internally a chain -/ have H_internal_chain : ⊤ ≤ ⨅ i₁ : C'.type, C'.bval i₁ ⟹ ⨅ i₂ : C'.type, C'.bval i₂ ⟹ (C'.func i₁ ⊆ᴮ C'.func i₂ ⊔ C'.func i₂ ⊆ᴮ C'.func i₁), by {simp[subset_unfold], intros i₁ i₂, simp[chain, set.pairwise_on] at C_chain, cases i₁ with i₁ H₁, cases i₂ with i₂ H₂, specialize C_chain i₁ H₁ i₂ H₂, haveI : decidable_eq α := λ _ _, prop_decidable _, by_cases i₁ = i₂, subst h, apply top_unique, apply le_sup_left_of_le, bv_intro j, apply bv_imp_intro, rw[top_inf_eq], apply mem.mk', specialize C_chain h, cases C_chain; apply top_unique; [apply le_sup_left_of_le, apply le_sup_right_of_le]; have := subset'_unfold C_chain; rw[eq_top_iff] at this; convert this using 1; simp only [subset_unfold]; refl}, have H_in_X : ⊤ ≤ ⨅(u : C'.type), C'.bval u ⟹ C'.func u ∈ᴮ X, by {bv_intro i_u, rw[of_core_bval, top_imp], apply of_core_mem}, /- Show that ⋃C' is in X -/ have H_internal_ub_mem : ⊤ ≤ (bv_union C') ∈ᴮ X, by {rw[le_infi_iff] at H, specialize H C', apply bv_context_apply H, apply le_inf, {apply le_trans H_in_X, simp only [subset_unfold]}, {apply le_trans H_internal_chain, rw[forall_forall_reindex (λ z₁ z₂, ((z₁ ⊆ᴮ z₂) ⊔ (z₂ ⊆ᴮ z₁) : 𝔹))]; simp}}, /- Show that ⋃C' is an upper bound on C' in X -/ have H_internal_ub_spec : ⊤ ≤ ⨅(i_w : C'.type), C'.bval i_w ⟹ C'.func i_w ⊆ᴮ (bv_union C'), by {have := bv_union_spec'' C', apply le_trans this, have := @bounded_forall 𝔹 _ C' (λ w, w ⊆ᴮ bv_union C'), dsimp only at this, rw[this_1], intros x y, rw[inf_comm, bv_eq_symm], apply subst_congr_subset_left}, have := core_witness h_core (bv_union C') (by {rw[eq_top_iff], exact H_internal_ub_mem}), cases this with w w_property, use w, intros x_w' H_x_w', change S (x_w') ⊆ᴮ S w = ⊤, apply top_unique, apply le_trans H_internal_ub_spec, apply bv_specialize, swap, use x_w', from H_x_w', rw[of_core_bval, top_imp], fapply bv_have, exact bv_union C' =ᴮ S w, rw[w_property], apply le_top, apply subst_congr_subset_right end /- ∀ x, x ≠ ∅ ∧ ((∀ y, y ⊆ x ∧ ∀ w₁ w₂ ∈ y, w₁ ⊆ w₂ ∨ w₂ ⊆ w₁) → (⋃y) ∈ x) → ∃ c ∈ x, ∀ z ∈ x, c ⊆ z → c = z -/ theorem bSet_zorns_lemma (X : bSet 𝔹) (H_nonempty : -(X =ᴮ ∅) = ⊤) (H : ⊤ ≤ (⨅y, (y ⊆ᴮ X ⊓ (⨅(w₁ : bSet 𝔹), ⨅(w₂ : bSet 𝔹), w₁ ∈ᴮ y ⊓ w₂ ∈ᴮ y ⟹ (w₁ ⊆ᴮ w₂ ⊔ w₂ ⊆ᴮ w₁))) ⟹ (bv_union y ∈ᴮ X))) : ⊤ ≤ (⨆c, c ∈ᴮ X ⊓ (⨅z, z ∈ᴮ X ⟹ (c ⊆ᴮ z ⟹ c =ᴮ z))) := begin have := core.mk X, rcases this with ⟨α, ⟨S, h_core⟩⟩, have H_zorn := exists_maximal_of_chains_bounded (subset'_inductive X H h_core) (by apply subset'_trans), rcases H_zorn with ⟨c, H_c⟩, rcases h_core with ⟨h_core_l, h_core_r⟩, have H_c_in_X := h_core_l c, apply bv_use (S c), rw[H_c_in_X], rw[top_inf_eq], bv_intro x, apply bv_imp_intro, rw[top_inf_eq], have := core_aux_lemma3 X H_nonempty S ⟨h_core_l, h_core_r⟩ x, rcases this with ⟨y, ⟨H₁_y, H₂_y⟩⟩, rw[<-H₂_y], apply bv_imp_intro, conv in (S c =ᴮ _) {rw[bv_eq_symm]}, suffices : x =ᴮ y ⊓ (S c ⊆ᴮ y) ≤ x =ᴮ S c, by {apply le_trans, show 𝔹, from x =ᴮ y ⊓ S c ⊆ᴮ y, apply le_inf, apply inf_le_left, apply B_ext_subset_right, from this}, suffices : S c ⊆ᴮ y ≤ y =ᴮ S c, by {apply le_trans, apply inf_le_inf, refl, from this, apply bv_eq_trans}, let a := S c ⊆ᴮ y, have h_a_bot : a ⊓ (-a) = ⊥, by apply inf_neg_eq_bot, have h_a_top : a ⊔ (-a) = ⊤, by apply sup_neg_eq_top, let v := two_term_mixture a (-a) h_a_bot y (S c), have claim_1 : v ∈ᴮ X = ⊤, by {apply two_term_mixture_mem_top, from h_a_top, apply core_mem_of_mem_image ⟨‹_›,‹_›⟩ ‹_›, from ‹_›}, have claim_2 : Σ' z : α, v =ᴮ S z = ⊤ := core_witness ⟨‹_›,‹_›⟩ v claim_1, rcases claim_2 with ⟨z, H_z⟩, have claim_3 : ⊤ ≤ S c ⊆ᴮ v, by {apply two_term_mixture_subset_top, from ‹_›, refl}, have claim_4 : by haveI := subset'_partial_order ⟨h_core_l,h_core_r⟩; from c ≤ z, by {apply top_unique, apply le_trans' claim_3, rw[<-H_z], apply B_ext_subset_right}, have claim_5 : S c =ᴮ S z = ⊤, by {have : S z ⊆ᴮ S c = ⊤, apply H_c z claim_4, apply top_unique, rw[eq_iff_subset_subset], apply le_inf, rw[top_le_iff], from ‹_›, rw[<-this]}, change a ≤ _, apply le_trans, apply (mixing_lemma_two_term a (-a) ‹_› y (S c)).left, change v =ᴮ _ ≤ _, rw[bv_eq_symm], apply le_trans', show 𝔹, from v =ᴮ S z, rw[H_z], apply le_top, apply le_trans, apply bv_eq_trans, apply bv_have (le_top : y =ᴮ _ ≤ _), rw[bv_eq_symm] at claim_5, simp[claim_5.symm, bv_eq_trans] end end zorns_lemma section comprehension variables (ϕ : bSet 𝔹 → 𝔹) (x : bSet 𝔹) (H_congr : B_ext ϕ) @[reducible]def comprehend : bSet 𝔹 := subset.mk (λ i : x.type, ϕ (x.func i)) include ϕ x H_congr lemma mem_comprehend_iff : ∀ {z x : bSet 𝔹} {Γ}, Γ ≤ z ∈ᴮ comprehend ϕ x ↔ Γ ≤ ⨆ (i : x.type), x.bval i ⊓ (z =ᴮ (x.func i) ⊓ (λ i : x.type, ϕ (x.func i)) i) := by intros; exact mem_subset.mk_iff₂ lemma mem_comprehend_iff₂ : ∀ {z : bSet 𝔹} {Γ}, Γ ≤ z ∈ᴮ comprehend ϕ x ↔ Γ ≤ ⨆ w, w ∈ᴮ x ⊓ (z =ᴮ w ⊓ (λ v, ϕ v) w) := begin intros z Γ, rw ←bounded_exists, apply mem_comprehend_iff, from z, from ‹_›, change B_ext _, simp* end lemma B_congr_comprehend {ϕ} {H_congr : B_ext ϕ} : B_congr (λ x : bSet 𝔹, (comprehend ϕ x)) := begin intros x y Γ H_eq, refine mem_ext _ _, { bv_intro z, bv_imp_intro Hz, rw mem_comprehend_iff₂ at Hz ⊢, apply bv_rw' (bv_symm H_eq), simp*, repeat { from ‹_› } }, { bv_intro z, bv_imp_intro Hz, rw mem_comprehend_iff₂ at Hz ⊢, apply bv_rw' H_eq, simp*, repeat { from ‹_› } } end variables {ϕ} {H_congr} lemma comprehend_subset {Γ : 𝔹} : Γ ≤ comprehend ϕ x ⊆ᴮ x := begin rw subset_unfold', bv_intro z, bv_imp_intro Hz, rw mem_comprehend_iff₂ at Hz, bv_cases_at Hz w Hw, bv_split, bv_split, bv_cc, from ‹_› end /-- For any ϕ and x, there is a subset y of x such that ∀ z, z ∈ y ↔ z ∈ x ∧ ϕ z -/ variables (ϕ) (H_congr) lemma bSet_axiom_of_comprehension {Γ : 𝔹} : Γ ≤ ⨆ y, y ⊆ᴮ x ⊓ ⨅ z, z ∈ᴮ y ⇔ (z ∈ᴮ x ⊓ ϕ z) := begin apply bv_use (comprehend ϕ x), refine le_inf _ _, { apply subset.mk_subset }, { bv_intro z, refine le_inf _ _, { bv_imp_intro H, rw[mem_subset.mk_iff] at H, bv_cases_at H i Hi, bv_split_at Hi, refine le_inf _ _, { apply bv_rw' Hi_left, simp, apply mem.mk'', from bv_and.right Hi_right }, { apply bv_rw' Hi_left, simp*, from bv_and.left Hi_right }}, { bv_imp_intro H, rw[mem_subset.mk_iff₂], rw @bounded_exists _ _ _ (λ w, z =ᴮ w ⊓ ϕ w), swap, {change B_ext _, simp* /- nice job, simp! -/ }, apply bv_use z, exact le_inf (bv_and.left ‹_›) (le_inf bv_refl $ bv_and.right ‹_›) }} end end comprehension -- /-- This is the abbreviated version of AC found at http://us.metamath.org/mpeuni/ac3.html -- It is provably equivalent over ZF to the usual formulation of AC -- After we have the Boolean soundness theorem, we can transport the proof via completeness -- from the 2-valued setting to the 𝔹-valued setting -/ -- -- ∀x ∃𝑦 ∀𝑧 ∈ 𝑥 (𝑧 ≠ ∅ → ∃!𝑤 ∈ 𝑧 ∃𝑣 ∈ 𝑦 (𝑧 ∈ 𝑣 ∧ 𝑤 ∈ 𝑣)) -- theorem bSet_axiom_of_choice : -- (⨅(x : bSet 𝔹), ⨆(y : bSet 𝔹), ⨅(z : bSet 𝔹), -- z ∈ᴮ x ⟹ ((- (z =ᴮ ∅)) ⟹ -- (⨆!(w : bSet 𝔹), w ∈ᴮ z ⟹ -- ⨆(v : bSet 𝔹), v ∈ᴮ y ⟹ (z ∈ᴮ v ⊓ w ∈ᴮ v)))) = ⊤ := sorry -- def check_shadow : Π (x : bSet 𝔹), (bSet 𝔹) -- | (bSet.mk α A B) := ⟨α, λ i, check_shadow (A i), λ _, ⊤⟩ -- lemma check_shadow_check : Π {x : pSet.{u}}, check_shadow (x̌) = (x̌ : bSet 𝔹) -- | ⟨α,A⟩ := by simp[check, check_shadow,check_shadow_check] def dom : ∀ x : bSet 𝔹, pSet.{u} | ⟨α,A,B⟩ := ⟨α, λ i, dom (A i)⟩ -- lemma dom_spec : Π {x : bSet 𝔹}, (dom x)̌ = check_shadow x -- | ⟨α,A,B⟩ := by simp[dom, check_shadow, *] @[reducible]def check_shadow : bSet 𝔹 → bSet 𝔹 := λ x, (dom x)̌ lemma check_shadow_type {x : bSet 𝔹} : (check_shadow x).type = x.type := by cases x; refl @[reducible]def check_shadow_cast {x : bSet 𝔹} : (check_shadow x).type → x.type := cast check_shadow_type @[reducible]def check_shadow_cast_symm {x : bSet 𝔹} : x.type → (check_shadow x).type := cast (check_shadow_type.symm) -- bSet 𝔹 retracts onto pSet lemma dom_check : Π {x : pSet.{u}}, dom (x̌ : bSet 𝔹) = x | ⟨α,A⟩ := by simp[dom,*] lemma dom_left_inv_check : function.left_inverse dom (check : pSet.{u} → bSet 𝔹) := λ x, dom_check lemma check_injective : function.injective (check : pSet.{u} → bSet 𝔹) := function.injective_of_left_inverse dom_left_inv_check -- -- should follow from maximum principle + induction (every member of a dom is a dom) -- @[simp]lemma dom_congr : ∀ x y : bSet 𝔹, (∀ {Γ}, Γ ≤ x =ᴮ y) → pSet.equiv (dom x) (dom y) -- | x@⟨α,A,B⟩ x'@⟨α',A',B'⟩ H := -- begin -- sorry -- end -- should follow from induction (every member of a check_shadow is a check_shadow) -- @[simp]lemma B_congr_check_shadow : B_congr (check_shadow : bSet 𝔹 → bSet 𝔹) -- | x@⟨α,A,B⟩ x'@⟨α',A',B'⟩ Γ H := -- begin -- unfold check_shadow, rw[bv_eq_unfold] at H ⊢, refine le_inf _ _; bv_intro i; simp at ⊢ H; cases H with H H', -- { sorry }, -- { sorry }, -- end end bSet
4dd9c1deb055e8f1105ef4311eae427f18b21058
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/uniform_space/cauchy_auto.lean
0fc679150ef1517a1d6bb7809aa8e41dfb21cab5
[]
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
21,991
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.uniform_space.basic import Mathlib.topology.bases import Mathlib.data.set.intervals.default import Mathlib.PostPort universes u v u_1 l namespace Mathlib /-! # Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy {α : Type u} [uniform_space α] (f : filter α) := filter.ne_bot f ∧ filter.prod f f ≤ uniformity α /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def is_complete {α : Type u} [uniform_space α] (s : set α) := ∀ (f : filter α), cauchy f → f ≤ filter.principal s → ∃ (x : α), ∃ (H : x ∈ s), f ≤ nhds x theorem filter.has_basis.cauchy_iff {α : Type u} {β : Type v} [uniform_space α] {p : β → Prop} {s : β → set (α × α)} (h : filter.has_basis (uniformity α) p s) {f : filter α} : cauchy f ↔ filter.ne_bot f ∧ ∀ (i : β), p i → ∃ (t : set α), ∃ (H : t ∈ f), ∀ (x y : α), x ∈ t → y ∈ t → (x, y) ∈ s i := sorry theorem cauchy_iff' {α : Type u} [uniform_space α] {f : filter α} : cauchy f ↔ filter.ne_bot f ∧ ∀ (s : set (α × α)) (H : s ∈ uniformity α), ∃ (t : set α), ∃ (H : t ∈ f), ∀ (x y : α), x ∈ t → y ∈ t → (x, y) ∈ s := filter.has_basis.cauchy_iff (filter.basis_sets (uniformity α)) theorem cauchy_iff {α : Type u} [uniform_space α] {f : filter α} : cauchy f ↔ filter.ne_bot f ∧ ∀ (s : set (α × α)) (H : s ∈ uniformity α), ∃ (t : set α), ∃ (H : t ∈ f), set.prod t t ⊆ s := sorry theorem cauchy_map_iff {α : Type u} {β : Type v} [uniform_space α] {l : filter β} {f : β → α} : cauchy (filter.map f l) ↔ filter.ne_bot l ∧ filter.tendsto (fun (p : β × β) => (f (prod.fst p), f (prod.snd p))) (filter.prod l l) (uniformity α) := sorry theorem cauchy_map_iff' {α : Type u} {β : Type v} [uniform_space α] {l : filter β} [hl : filter.ne_bot l] {f : β → α} : cauchy (filter.map f l) ↔ filter.tendsto (fun (p : β × β) => (f (prod.fst p), f (prod.snd p))) (filter.prod l l) (uniformity α) := iff.trans cauchy_map_iff (and_iff_right hl) theorem cauchy.mono {α : Type u} [uniform_space α] {f : filter α} {g : filter α} [hg : filter.ne_bot g] (h_c : cauchy f) (h_le : g ≤ f) : cauchy g := { left := hg, right := le_trans (filter.prod_mono h_le h_le) (and.right h_c) } theorem cauchy.mono' {α : Type u} [uniform_space α] {f : filter α} {g : filter α} (h_c : cauchy f) (hg : filter.ne_bot g) (h_le : g ≤ f) : cauchy g := cauchy.mono h_c h_le theorem cauchy_nhds {α : Type u} [uniform_space α] {a : α} : cauchy (nhds a) := sorry theorem cauchy_pure {α : Type u} [uniform_space α] {a : α} : cauchy (pure a) := cauchy.mono cauchy_nhds (pure_le_nhds a) theorem filter.tendsto.cauchy_map {α : Type u} {β : Type v} [uniform_space α] {l : filter β} [filter.ne_bot l] {f : β → α} {a : α} (h : filter.tendsto f l (nhds a)) : cauchy (filter.map f l) := cauchy.mono cauchy_nhds h /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ theorem le_nhds_of_cauchy_adhp_aux {α : Type u} [uniform_space α] {f : filter α} {x : α} (adhs : ∀ (s : set (α × α)) (H : s ∈ uniformity α), ∃ (t : set α), ∃ (H : t ∈ f), set.prod t t ⊆ s ∧ ∃ (y : α), (x, y) ∈ s ∧ y ∈ t) : f ≤ nhds x := sorry /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ theorem le_nhds_of_cauchy_adhp {α : Type u} [uniform_space α] {f : filter α} {x : α} (hf : cauchy f) (adhs : cluster_pt x f) : f ≤ nhds x := sorry theorem le_nhds_iff_adhp_of_cauchy {α : Type u} [uniform_space α] {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ cluster_pt x f := { mp := fun (h : f ≤ nhds x) => cluster_pt.of_le_nhds' h (and.left hf), mpr := le_nhds_of_cauchy_adhp hf } theorem cauchy.map {α : Type u} {β : Type v} [uniform_space α] [uniform_space β] {f : filter α} {m : α → β} (hf : cauchy f) (hm : uniform_continuous m) : cauchy (filter.map m f) := { left := filter.ne_bot.map (and.left hf) m, right := le_trans (trans_rel_right LessEq filter.prod_map_map_eq (filter.map_mono (and.right hf))) hm } theorem cauchy.comap {α : Type u} {β : Type v} [uniform_space α] [uniform_space β] {f : filter β} {m : α → β} (hf : cauchy f) (hm : filter.comap (fun (p : α × α) => (m (prod.fst p), m (prod.snd p))) (uniformity β) ≤ uniformity α) [filter.ne_bot (filter.comap m f)] : cauchy (filter.comap m f) := { left := _inst_3, right := le_trans (trans_rel_right LessEq filter.prod_comap_comap_eq (filter.comap_mono (and.right hf))) hm } theorem cauchy.comap' {α : Type u} {β : Type v} [uniform_space α] [uniform_space β] {f : filter β} {m : α → β} (hf : cauchy f) (hm : filter.comap (fun (p : α × α) => (m (prod.fst p), m (prod.snd p))) (uniformity β) ≤ uniformity α) (hb : filter.ne_bot (filter.comap m f)) : cauchy (filter.comap m f) := cauchy.comap hf hm /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def cauchy_seq {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] (u : β → α) := cauchy (filter.map u filter.at_top) theorem cauchy_seq.mem_entourage {α : Type u} [uniform_space α] {ι : Type u_1} [Nonempty ι] [linear_order ι] {u : ι → α} (h : cauchy_seq u) {V : set (α × α)} (hV : V ∈ uniformity α) : ∃ (k₀ : ι), ∀ (i j : ι), k₀ ≤ i → k₀ ≤ j → (u i, u j) ∈ V := sorry theorem filter.tendsto.cauchy_seq {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] [Nonempty β] {f : β → α} {x : α} (hx : filter.tendsto f filter.at_top (nhds x)) : cauchy_seq f := filter.tendsto.cauchy_map hx theorem cauchy_seq_iff_tendsto {α : Type u} {β : Type v} [uniform_space α] [Nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ filter.tendsto (prod.map u u) filter.at_top (uniformity α) := sorry /-- If a Cauchy sequence has a convergent subsequence, then it converges. -/ theorem tendsto_nhds_of_cauchy_seq_of_subseq {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] {u : β → α} (hu : cauchy_seq u) {ι : Type u_1} {f : ι → β} {p : filter ι} [filter.ne_bot p] (hf : filter.tendsto f p filter.at_top) {a : α} (ha : filter.tendsto (u ∘ f) p (nhds a)) : filter.tendsto u filter.at_top (nhds a) := le_nhds_of_cauchy_adhp hu (map_cluster_pt_of_comp hf ha) theorem filter.has_basis.cauchy_seq_iff {α : Type u} {β : Type v} [uniform_space α] {γ : Type u_1} [Nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (h : filter.has_basis (uniformity α) p s) : cauchy_seq u ↔ ∀ (i : γ), p i → ∃ (N : β), ∀ (m n : β), m ≥ N → n ≥ N → (u m, u n) ∈ s i := sorry theorem filter.has_basis.cauchy_seq_iff' {α : Type u} {β : Type v} [uniform_space α] {γ : Type u_1} [Nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (H : filter.has_basis (uniformity α) p s) : cauchy_seq u ↔ ∀ (i : γ), p i → ∃ (N : β), ∀ (n : β), n ≥ N → (u n, u N) ∈ s i := sorry theorem cauchy_seq_of_controlled {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] [Nonempty β] (U : β → set (α × α)) (hU : ∀ (s : set (α × α)), s ∈ uniformity α → ∃ (n : β), U n ⊆ s) {f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) : cauchy_seq f := sorry /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] where complete : ∀ {f : filter α}, cauchy f → ∃ (x : α), f ≤ nhds x theorem complete_univ {α : Type u} [uniform_space α] [complete_space α] : is_complete set.univ := sorry theorem cauchy_prod {α : Type u} {β : Type v} [uniform_space α] [uniform_space β] {f : filter α} {g : filter β} : cauchy f → cauchy g → cauchy (filter.prod f g) := sorry protected instance complete_space.prod {α : Type u} {β : Type v} [uniform_space α] [uniform_space β] [complete_space α] [complete_space β] : complete_space (α × β) := complete_space.mk fun (f : filter (α × β)) (hf : cauchy f) => sorry /--If `univ` is complete, the space is a complete space -/ theorem complete_space_of_is_complete_univ {α : Type u} [uniform_space α] (h : is_complete set.univ) : complete_space α := sorry theorem complete_space_iff_is_complete_univ {α : Type u} [uniform_space α] : complete_space α ↔ is_complete set.univ := { mp := complete_univ, mpr := complete_space_of_is_complete_univ } theorem cauchy_iff_exists_le_nhds {α : Type u} [uniform_space α] [complete_space α] {l : filter α} [filter.ne_bot l] : cauchy l ↔ ∃ (x : α), l ≤ nhds x := sorry theorem cauchy_map_iff_exists_tendsto {α : Type u} {β : Type v} [uniform_space α] [complete_space α] {l : filter β} {f : β → α} [filter.ne_bot l] : cauchy (filter.map f l) ↔ ∃ (x : α), filter.tendsto f l (nhds x) := cauchy_iff_exists_le_nhds /-- A Cauchy sequence in a complete space converges -/ theorem cauchy_seq_tendsto_of_complete {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] [complete_space α] {u : β → α} (H : cauchy_seq u) : ∃ (x : α), filter.tendsto u filter.at_top (nhds x) := complete_space.complete H /-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/ theorem cauchy_seq_tendsto_of_is_complete {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] {K : set α} (h₁ : is_complete K) {u : β → α} (h₂ : ∀ (n : β), u n ∈ K) (h₃ : cauchy_seq u) : ∃ (v : α), ∃ (H : v ∈ K), filter.tendsto u filter.at_top (nhds v) := sorry theorem cauchy.le_nhds_Lim {α : Type u} [uniform_space α] [complete_space α] [Nonempty α] {f : filter α} (hf : cauchy f) : f ≤ nhds (Lim f) := le_nhds_Lim (complete_space.complete hf) theorem cauchy_seq.tendsto_lim {α : Type u} {β : Type v} [uniform_space α] [semilattice_sup β] [complete_space α] [Nonempty α] {u : β → α} (h : cauchy_seq u) : filter.tendsto u filter.at_top (nhds (lim filter.at_top u)) := cauchy.le_nhds_Lim h theorem is_closed.is_complete {α : Type u} [uniform_space α] [complete_space α] {s : set α} (h : is_closed s) : is_complete s := sorry /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded {α : Type u} [uniform_space α] (s : set α) := ∀ (d : set (α × α)) (H : d ∈ uniformity α), ∃ (t : set α), set.finite t ∧ s ⊆ set.Union fun (y : α) => set.Union fun (H : y ∈ t) => set_of fun (x : α) => (x, y) ∈ d theorem totally_bounded_iff_subset {α : Type u} [uniform_space α] {s : set α} : totally_bounded s ↔ ∀ (d : set (α × α)) (H : d ∈ uniformity α), ∃ (t : set α), ∃ (H : t ⊆ s), set.finite t ∧ s ⊆ set.Union fun (y : α) => set.Union fun (H : y ∈ t) => set_of fun (x : α) => (x, y) ∈ d := sorry theorem totally_bounded_of_forall_symm {α : Type u} [uniform_space α] {s : set α} (h : ∀ (V : set (α × α)) (H : V ∈ uniformity α), symmetric_rel V → ∃ (t : set α), set.finite t ∧ s ⊆ set.Union fun (y : α) => set.Union fun (H : y ∈ t) => uniform_space.ball y V) : totally_bounded s := sorry theorem totally_bounded_subset {α : Type u} [uniform_space α] {s₁ : set α} {s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := sorry theorem totally_bounded_empty {α : Type u} [uniform_space α] : totally_bounded ∅ := sorry /-- The closure of a totally bounded set is totally bounded. -/ theorem totally_bounded.closure {α : Type u} [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := sorry /-- The image of a totally bounded set under a unifromly continuous map is totally bounded. -/ theorem totally_bounded.image {α : Type u} {β : Type v} [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hs : totally_bounded s) (hf : uniform_continuous f) : totally_bounded (f '' s) := sorry theorem ultrafilter.cauchy_of_totally_bounded {α : Type u} [uniform_space α] {s : set α} (f : ultrafilter α) (hs : totally_bounded s) (h : ↑f ≤ filter.principal s) : cauchy ↑f := sorry theorem totally_bounded_iff_filter {α : Type u} [uniform_space α] {s : set α} : totally_bounded s ↔ ∀ (f : filter α), filter.ne_bot f → f ≤ filter.principal s → ∃ (c : filter α), ∃ (H : c ≤ f), cauchy c := sorry theorem totally_bounded_iff_ultrafilter {α : Type u} [uniform_space α] {s : set α} : totally_bounded s ↔ ∀ (f : ultrafilter α), ↑f ≤ filter.principal s → cauchy ↑f := sorry theorem compact_iff_totally_bounded_complete {α : Type u} [uniform_space α] {s : set α} : is_compact s ↔ totally_bounded s ∧ is_complete s := sorry protected instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := sorry theorem compact_of_totally_bounded_is_closed {α : Type u} [uniform_space α] [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : is_compact s := iff.mpr compact_iff_totally_bounded_complete { left := ht, right := is_closed.is_complete hc } /-! ### Sequentially complete space In this section we prove that a uniform space is complete provided that it is sequentially complete (i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set. In particular, this applies to (e)metric spaces, see the files `topology/metric_space/emetric_space` and `topology/metric_space/basic`. More precisely, we assume that there is a sequence of entourages `U_n` such that any other entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/ namespace sequentially_complete /-- An auxiliary sequence of sets approximating a Cauchy filter. -/ def set_seq_aux {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (n : ℕ) : Subtype fun (s : set α) => ∃ (_x : s ∈ f), set.prod s s ⊆ U n := classical.indefinite_description (fun (s : set α) => ∃ (_x : s ∈ f), set.prod s s ⊆ U n) sorry /-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides a sequence of monotonically decreasing sets `s n ∈ f` such that `(s n).prod (s n) ⊆ U`. -/ def set_seq {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (n : ℕ) : set α := set.Inter fun (m : ℕ) => set.Inter fun (H : m ∈ set.Iic n) => subtype.val (set_seq_aux hf U_mem m) theorem set_seq_mem {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (n : ℕ) : set_seq hf U_mem n ∈ f := iff.mpr (filter.bInter_mem_sets (set.finite_le_nat n)) fun (m : ℕ) (_x : m ∈ set_of fun (i : ℕ) => i ≤ n) => Exists.fst (subtype.property (set_seq_aux hf U_mem m)) theorem set_seq_mono {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) {m : ℕ} {n : ℕ} (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m := set.bInter_subset_bInter_left fun (k : ℕ) (hk : k ∈ set.Iic m) => le_trans hk h theorem set_seq_sub_aux {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (n : ℕ) : set_seq hf U_mem n ⊆ ↑(set_seq_aux hf U_mem n) := set.bInter_subset_of_mem set.right_mem_Iic theorem set_seq_prod_subset {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) {N : ℕ} {m : ℕ} {n : ℕ} (hm : N ≤ m) (hn : N ≤ n) : set.prod (set_seq hf U_mem m) (set_seq hf U_mem n) ⊆ U N := sorry /-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is a monotonically decreasing sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence of entourages. -/ def seq {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (n : ℕ) : α := classical.some sorry theorem seq_mem {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n := classical.some_spec (filter.ne_bot.nonempty_of_mem (and.left hf) (set_seq_mem hf U_mem n)) theorem seq_pair_mem {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) {N : ℕ} {m : ℕ} {n : ℕ} (hm : N ≤ m) (hn : N ≤ n) : (seq hf U_mem m, seq hf U_mem n) ∈ U N := set_seq_prod_subset hf U_mem hm hn { left := seq_mem hf U_mem m, right := seq_mem hf U_mem n } theorem seq_is_cauchy_seq {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (U_le : ∀ (s : set (α × α)), s ∈ uniformity α → ∃ (n : ℕ), U n ⊆ s) : cauchy_seq (seq hf U_mem) := cauchy_seq_of_controlled U U_le (seq_pair_mem hf U_mem) /-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/ theorem le_nhds_of_seq_tendsto_nhds {α : Type u} [uniform_space α] {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (U_le : ∀ (s : set (α × α)), s ∈ uniformity α → ∃ (n : ℕ), U n ⊆ s) {a : α} (ha : filter.tendsto (seq hf U_mem) filter.at_top (nhds a)) : f ≤ nhds a := sorry end sequentially_complete namespace uniform_space /-- A uniform space is complete provided that (a) its uniformity filter has a countable basis; (b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/ theorem complete_of_convergent_controlled_sequences {α : Type u} [uniform_space α] (H : filter.is_countably_generated (uniformity α)) (U : ℕ → set (α × α)) (U_mem : ∀ (n : ℕ), U n ∈ uniformity α) (HU : ∀ (u : ℕ → α), (∀ (N m n : ℕ), N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ (a : α), filter.tendsto u filter.at_top (nhds a)) : complete_space α := sorry /-- A sequentially complete uniform space with a countable basis of the uniformity filter is complete. -/ theorem complete_of_cauchy_seq_tendsto {α : Type u} [uniform_space α] (H : filter.is_countably_generated (uniformity α)) (H' : ∀ (u : ℕ → α), cauchy_seq u → ∃ (a : α), filter.tendsto u filter.at_top (nhds a)) : complete_space α := sorry protected theorem first_countable_topology {α : Type u} [uniform_space α] (H : filter.is_countably_generated (uniformity α)) : topological_space.first_countable_topology α := sorry /-- A separable uniform space with countably generated uniformity filter is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational "radii" from a countable open symmetric antimono basis of `𝓤 α`. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ theorem second_countable_of_separable {α : Type u} [uniform_space α] (H : filter.is_countably_generated (uniformity α)) [topological_space.separable_space α] : topological_space.second_countable_topology α := sorry end Mathlib
74993e253bcfd6116ee4444d5a87c97d581cf535
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/tactic/split_ifs.lean
4fd9a0addecdc3ea41a89d17a4d83a106c2db9e8
[ "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,305
lean
/- Copyright (c) 2018 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner. Tactic to split if-then-else-expressions. -/ import tactic.hint open expr tactic namespace tactic open interactive meta def find_if_cond : expr → option expr | e := e.fold none $ λ e _ acc, acc <|> do c ← match e with | `(@ite %%c %%_ _ _ _) := some c | `(@dite %%c %%_ _ _ _) := some c | _ := none end, guard ¬c.has_var, find_if_cond c <|> return c meta def find_if_cond_at (at_ : loc) : tactic (option expr) := do lctx ← at_.get_locals, lctx ← lctx.mmap infer_type, tgt ← target, let es := if at_.include_goal then tgt::lctx else lctx, return $ find_if_cond $ es.foldr app (default expr) run_cmd mk_simp_attr `split_if_reduction run_cmd add_doc_string `simp_attr.split_if_reduction "Simp set for if-then-else statements" attribute [split_if_reduction] if_pos if_neg dif_pos dif_neg meta def reduce_ifs_at (at_ : loc) : tactic unit := do sls ← get_user_simp_lemmas `split_if_reduction, let cfg : simp_config := { fail_if_unchanged := ff }, let discharger := assumption <|> (applyc `not_not_intro >> assumption), hs ← at_.get_locals, hs.mmap' (λ h, simp_hyp sls [] h cfg discharger >> skip), when at_.include_goal (simp_target sls [] cfg discharger >> skip) meta def split_if1 (c : expr) (n : name) (at_ : loc) : tactic unit := by_cases c n; reduce_ifs_at at_ private meta def get_next_name (names : ref (list name)) : tactic name := do ns ← read_ref names, match ns with | [] := get_unused_name `h | n::ns := do write_ref names ns, return n end private meta def value_known (c : expr) : tactic bool := do lctx ← local_context, lctx ← lctx.mmap infer_type, return $ c ∈ lctx ∨ `(¬%%c) ∈ lctx private meta def split_ifs_core (at_ : loc) (names : ref (list name)) : list expr → tactic unit | done := do some cond ← find_if_cond_at at_ | fail "no if-then-else expressions to split", let cond := match cond with `(¬%%p) := p | p := p end, if cond ∈ done then skip else do no_split ← value_known cond, if no_split then reduce_ifs_at at_; try (split_ifs_core (cond :: done)) else do n ← get_next_name names, split_if1 cond n at_; try (split_ifs_core (cond :: done)) meta def split_ifs (names : list name) (at_ : loc := loc.ns [none]) := using_new_ref names $ λ names, split_ifs_core at_ names [] namespace interactive open interactive interactive.types expr lean.parser /-- Splits all if-then-else-expressions into multiple goals. Given a goal of the form `g (if p then x else y)`, `split_ifs` will produce two goals: `p ⊢ g x` and `¬p ⊢ g y`. If there are multiple ite-expressions, then `split_ifs` will split them all, starting with a top-most one whose condition does not contain another ite-expression. `split_ifs at *` splits all ite-expressions in all hypotheses as well as the goal. `split_ifs with h₁ h₂ h₃` overrides the default names for the hypotheses. -/ meta def split_ifs (at_ : parse location) (names : parse with_ident_list) : tactic unit := tactic.split_ifs names at_ add_hint_tactic "split_ifs" add_tactic_doc { name := "split_ifs", category := doc_category.tactic, decl_names := [``split_ifs], tags := ["case bashing"] } end interactive end tactic
2c0dd8f65a2bba8c5e26b3e75dceb5db4c03c905
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/tactic/ring_exp.lean
672739d5466ae8397bc94bef7ec80e28f6357a40
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
55,383
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Tim Baanen. Solve equations in commutative (semi)rings with exponents. -/ import tactic.norm_num /-! # `ring_exp` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`, something that the `ring` tactic cannot do, but `ring_exp` can. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ex` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The normalised version and normalisation proofs are also stored in the `ex` type. The outline of the file: - Define an inductive family of types `ex`, parametrised over `ex_type`, which can represent expressions with `+`, `*`, `^` and rational numerals. The parametrisation over `ex_type` ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ex` type, thus allowing us to map expressions to `ex` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `ex_type`) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - In the tactic, a normalized expression `ps : ex` lives in the meta-world, but the normalization proofs live in the real world. Thus, we cannot directly say `ps.orig = ps.pretty` anywhere, but we have to carefully construct the proof when we compute `ps`. This was a major source of bugs in development! - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. This is accomplished by the `in_exponent` function and is relatively painless since we work in a `reader` monad. - The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`. ## Caveats and future work Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring_exp` solves the goal, but `a / a := 1 by ring_exp` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ -- The base ring `α` will have a universe level `u`. -- We do not introduce `α` as a variable yet, -- in order to make it explicit or implicit as required. universes u namespace tactic.ring_exp open nat /-- The `atom` structure is used to represent atomic expressions: those which `ring_exp` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring_exp_eq` tactic does not normalize the subexpressions in atoms, but `ring_exp` does if `ring_exp_eq` was not sufficient. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ meta structure atom : Type := (value : expr) (index : ℕ) namespace atom /-- The `eq` operation on `atom`s works modulo definitional equality, ignoring their `value`s. The invariants on `atom` ensure indices are unique per value. Thus, `eq` indicates equality as long as the `atom`s come from the same context. -/ meta def eq (a b : atom) : bool := a.index = b.index /-- We order `atom`s on the order of appearance in the main expression. -/ meta def lt (a b : atom) : bool := a.index < b.index meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩ end atom section expression /-! ### `expression` section In this section, we define the `ex` type and its basic operations. First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`. For understanding the code, it's easier to check out `ex` itself first, then refer back to the supporting types. The arithmetic operations on `ex` need additional definitions, so they are defined in a later section. -/ /-- Coefficients in the expression are stored in a wrapper structure, allowing for easier modification of the data structures. The modifications might be caching of the result of `expr.of_rat`, or using a different meta representation of numerals. -/ @[derive decidable_eq, derive inhabited] structure coeff : Type := (value : ℚ) /-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/ @[derive decidable_eq, derive inhabited] inductive ex_type : Type | base : ex_type | sum : ex_type | prod : ex_type | exp : ex_type open ex_type /-- Each `ex` stores information for its normalization proof. The `orig` expression is the expression that was passed to `eval`. The `pretty` expression is the normalised form that the `ex` represents. (I didn't call this something like `norm`, because there are already too many things called `norm` in mathematics!) The field `proof` contains an optional proof term of type `%%orig = %%pretty`. The value `none` for the proof indicates that everything reduces to reflexivity. (Which saves space in quite a lot of cases.) -/ meta structure ex_info : Type := (orig : expr) (pretty : expr) (proof : option expr) /-- The `ex` type is an abstract representation of an expression with `+`, `*` and `^`. Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively. The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented by (something along the lines of) `sum 1 (sum 2 zero)`. The `coeff` constructor is the base case for `ex prod`, and is used for numerals. The code maintains the invariant that the coefficient is never `0`. The `var` constructor is the base case for `ex exp`, and is used for atoms. The `sum_b` constructor allows for addition in the base of an exponentiation; it serves a similar purpose as the parentheses in `(a + b)^c`. The code maintains the invariant that the argument to `sum_b` is not `zero` or `sum _ zero`. All of the constructors contain an `ex_info` field, used to carry around (arguments to) proof terms. While the `ex_type` parameter enforces some simplification invariants, the following ones must be manually maintained at the risk of insufficient power: - the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`) - the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`) - normalisation proofs of subexpressions must be `refl ps.pretty` - if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted according to the `lt` relation defined further down; similarly for `prod` and `coeff` (to ensure `a + b = b + a`). The first two invariants could be encoded in a subtype of `ex`, but aren't (yet) to spare some implementation burden. The other invariants cannot be encoded because we need the `tactic` monad to check them. (For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.) -/ meta inductive ex : ex_type → Type | zero (info : ex_info) : ex sum | sum (info : ex_info) : ex prod → ex sum → ex sum | coeff (info : ex_info) : coeff → ex prod | prod (info : ex_info) : ex exp → ex prod → ex prod | var (info : ex_info) : atom → ex base | sum_b (info : ex_info) : ex sum → ex base | exp (info : ex_info) : ex base → ex prod → ex exp /-- Return the proof information associated to the `ex`. -/ meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info | sum (ex.zero i) := i | sum (ex.sum i _ _) := i | prod (ex.coeff i _) := i | prod (ex.prod i _ _) := i | base (ex.var i _) := i | base (ex.sum_b i _) := i | exp (ex.exp i _ _) := i /-- Return the original, non-normalized version of this `ex`. Note that arguments to another `ex` are always "pre-normalized": their `orig` and `pretty` are equal, and their `proof` is reflexivity. -/ meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig /-- Return the normalized version of this `ex`. -/ meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty /-- Return the normalisation proof of the given expression. If the proof is `refl`, we give `none` instead, which helps to control the size of proof terms. To get an actual term, use `ex.proof_term`, or use `mk_proof` with the correct set of arguments. -/ meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof /-- Update the `orig` and `proof` fields of the `ex_info`. Intended for use in `ex.set_info`. -/ meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info := {orig := o.get_or_else i.pretty, proof := pf, .. i} /-- Update the `ex_info` of the given expression. We use this to combine intermediate normalisation proofs. Since `pretty` only depends on the subexpressions, which do not change, we do not set `pretty`. -/ meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et | sum (ex.zero i) o pf := ex.zero (i.set o pf) | sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps | prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x | prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps | base (ex.var i x) o pf := ex.var (i.set o pf) x | base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps | exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩ /-- Convert an `ex` to a `string`. -/ meta def ex.repr : Π {et : ex_type}, ex et → string | sum (ex.zero _) := "0" | sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps | prod (ex.coeff _ x) := repr x | prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps | base (ex.var _ x) := repr x | base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")" | exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩ /-- Equality test for expressions. Since equivalence of `atom`s is not the same as equality, we cannot make a true `(=)` operator for `ex` either. -/ meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool | sum (ex.zero _) (ex.zero _) := tt | sum (ex.zero _) (ex.sum _ _ _) := ff | sum (ex.sum _ _ _) (ex.zero _) := ff | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs | prod (ex.coeff _ x) (ex.coeff _ y) := x = y | prod (ex.coeff _ _) (ex.prod _ _ _) := ff | prod (ex.prod _ _ _) (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs | base (ex.var _ x) (ex.var _ y) := x.eq y | base (ex.var _ _) (ex.sum_b _ _) := ff | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs /-- The ordering on expressions. As for `ex.eq`, this is a linear order only in one context. -/ meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool | sum _ (ex.zero _) := ff | sum (ex.zero _) _ := tt | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs) | prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1 | prod (ex.coeff _ _) _ := tt | prod _ (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs) | base (ex.var _ x) (ex.var _ y) := x.lt y | base (ex.var _ _) (ex.sum_b _ _) := tt | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs) end expression section operations /-! ### `operations` section This section defines the operations (on `ex`) that use tactics. They live in the `ring_exp_m` monad, which adds a cache and a list of encountered atoms to the `tactic` monad. Throughout this section, we will be constructing proof terms. The lemmas used in the construction are all defined over a commutative semiring α. -/ variables {α : Type u} [comm_semiring α] open tactic open ex_type /-- Stores the information needed in the `eval` function and its dependencies, so they can (re)construct expressions. The `eval_info` structure stores this information for one type, and the `context` combines the two types, one for bases and one for exponents. -/ meta structure eval_info := (α : expr) (univ : level) -- Cache the instances for optimization and consistency (csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr) -- Optional instances (only required for (-) and (/) respectively) (ring_instance : option expr) (dr_instance : option expr) -- Cache common constants. (zero : expr) (one : expr) /-- The `context` contains the full set of information needed for the `eval` function. This structure has two copies of `eval_info`: one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`). When evaluating an exponent, we put `info_e` in `info_b`. -/ meta structure context := (info_b : eval_info) (info_e : eval_info) (transp : transparency) /-- The `ring_exp_m` monad is used instead of `tactic` to store the context. -/ @[derive [monad, alternative]] meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α /-- Access the instance cache. -/ meta def get_context : ring_exp_m context := reader_t.read /-- Lift an operation in the `tactic` monad to the `ring_exp_m` monad. This operation will not access the cache. -/ meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m) /-- Change the context of the given computation, so that expressions are evaluated in the exponent ring, instead of the base ring. -/ meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do ctx ← get_context, reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩ /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class f (ctx.info_b.csr_instance) args /-- Specialized version of `mk_app ``has_add.add`. Should be faster because it can use the cached instances. -/ meta def mk_add (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_add.add ctx.info_b.ha_instance args /-- Specialized version of `mk_app ``has_mul.mul`. Should be faster because it can use the cached instances. -/ meta def mk_mul (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_mul.mul ctx.info_b.hm_instance args /-- Specialized version of `mk_app ``has_pow.pow`. Should be faster because it can use the cached instances. -/ meta def mk_pow (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt ``has_pow.pow [ctx.info_b.univ, ctx.info_e.univ] ctx.info_b.α ctx.info_e.α ctx.info_b.hp_instance).mk_app args /-- Construct a normalization proof term or return the cached one. -/ meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr := match ps.proof with | none := lift $ tactic.mk_eq_refl ps.pretty | (some p) := pure p end /-- Construct a normalization proof term or return the cached one. -/ meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term /-- If all `ex_info` have trivial proofs, return a trivial proof. Otherwise, construct all proof terms. Useful in applications where trivial proofs combine to another trivial proof, most importantly to pass to `mk_proof_or_refl`. -/ meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr)) | [] := pure none | (x :: xs) := do xs_pfs ← none_or_proof_term xs, match (x.proof, xs_pfs) with | (none, none) := pure none | (some x_pf, none) := do xs_pfs ← traverse ex_info.proof_term xs, pure (some (x_pf :: xs_pfs)) | (_, some xs_pfs) := do x_pf ← x.proof_term, pure (some (x_pf :: xs_pfs)) end /-- Use the proof terms as arguments to the given lemma. If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.` -/ meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs' ← traverse ex_info.proof_term hs, mk_app_csr lem (args ++ hs') /-- Use the proof terms as arguments to the given lemma. Often, we construct a proof term using congruence where reflexivity suffices. To solve this, the following function tries to get away with reflexivity. -/ meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs_full ← none_or_proof_term hs, match hs_full with | none := lift $ mk_eq_refl term | (some hs') := mk_app_csr lem (args ++ hs') end /-- A shortcut for adding the original terms of two expressions. -/ meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_add [ps.orig, qs.orig] /-- A shortcut for multiplying the original terms of two expressions. -/ meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_mul [ps.orig, qs.orig] /-- A shortcut for exponentiating the original terms of two expressions. -/ meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_pow [ps.orig, qs.orig] /-- Congruence lemma for constructing `ex.sum`. -/ lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc /-- Congruence lemma for constructing `ex.prod`. -/ lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc /-- Congruence lemma for constructing `ex.exp`. -/ lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc /-- Constructs `ex.zero` with the correct arguments. -/ meta def ex_zero : ring_exp_m (ex sum) := do ctx ← get_context, pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩ /-- Constructs `ex.sum` with the correct arguments. -/ meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do pps_o ← add_orig p ps, pps_p ← mk_add [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``sum_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.coeff` with the correct arguments. There are more efficient constructors for specific numerals: if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`. -/ meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do ctx ← get_context, x_p ← lift $ expr.of_rat ctx.info_b.α x, pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩) /-- Constructs `ex.coeff 1` with the correct arguments. This is a special case for optimization purposes. -/ meta def ex_one : ring_exp_m (ex prod) := do ctx ← get_context, pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩ /-- Constructs `ex.prod` with the correct arguments. -/ meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do pps_o ← mul_orig p ps, pps_p ← mk_mul [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``prod_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.var` with the correct arguments. -/ meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p) /-- Constructs `ex.sum_b` with the correct arguments. -/ meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) := pure (ex.sum_b ps.info (ps.set_info none none)) /-- Constructs `ex.exp` with the correct arguments. -/ meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do ctx ← get_context, pps_o ← pow_orig p ps, pps_p ← mk_pow [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``exp_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp /-- Conversion from `ex base` to `ex exp`. -/ meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do o ← in_exponent $ ex_one, ps ← ex_exp p o, pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp /-- Conversion from `ex exp` to `ex prod`. -/ meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do o ← ex_one, ps ← ex_prod p o, pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp /-- Conversion from `ex prod` to `ex sum`. -/ meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do z ← ex_zero, ps ← ex_sum p z, pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp /-- A more efficient conversion from `atom` to `ex sum`. The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`, except we need to calculate less intermediate steps. -/ meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do p' ← ex_var p, o ← in_exponent $ ex_one, p' ← ex_exp p' o, o ← ex_one, p' ← ex_prod p' o, z ← ex_zero, p' ← ex_sum p' z, pf ← mk_proof ``atom_to_sum_pf [p.1] [], pure $ p'.set_info p.1 pf /-- Compute the sum of two coefficients. Note that the result might not be a valid expression: if `p = -q`, then the result should be `ex.zero : ex sum` instead. The caller must detect when this happens! The returned value is of the form `ex.coeff _ (p + q)`, with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`. -/ meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq_o ← mk_add [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num pq_o, pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩ lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p /-- Compute the product of two coefficients. The returned value is of the form `ex.coeff _ (p * q)`, with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`. -/ meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := match p.1, q.1 with -- Special case to speed up multiplication with 1. | ⟨1, 1, _, _⟩, _ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p], pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩ | _, ⟨1, 1, _, _⟩ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p], pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩ | _, _ := do ctx ← get_context, pq' ← mk_mul [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ end /-- Represents the way in which two products are equal except coefficient. This type is used in the function `add_overlap`. In order to deal with equations of the form `a * 2 + a = 3 * a`, the `add` function will add up overlapping products, turning `a * 2 + a` into `a * 3`. We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this, and the `overlap` type carries the information on how it overlaps. The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`; the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a` (the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`); the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`. We distinguish those two cases because in the second, the whole product reduces to `0`. A potential extension to the tactic would also do this for the base of exponents, e.g. to show `2^n * 2^n = 4^n`. -/ meta inductive overlap : Type | none : overlap | nonzero : ex prod → overlap | zero : ex sum → overlap lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * pq : by rw pq_pf lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * 0 : by rw pq_pf ... = 0 : mul_zero _ /-- Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients). For other arguments, return `overlap.none`. -/ meta def add_overlap : ex prod → ex prod → ring_exp_m overlap | (ex.coeff x_i x) (ex.coeff y_i y) := do xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y | lift $ fail "internal error: add_coeff should return ex.coeff", if xy_c.1 = 0 then do z ← ex_zero, pure $ overlap.zero (z.set_info xy.orig xy.proof) else pure $ overlap.nonzero xy | (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none | (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none | pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q then do pq_ol ← add_overlap ps qs, pqs_o ← add_orig pps qqs, match pq_ol with | overlap.none := pure overlap.none | (overlap.nonzero pq) := do pqs ← ex_prod p pq, pf ← mk_proof ``add_overlap_pf [ps.pretty, qs.pretty, pq.pretty, p.pretty] [pq.info], pure $ overlap.nonzero (pqs.set_info pqs_o pf) | (overlap.zero pq) := do z ← ex_zero, pf ← mk_proof ``add_overlap_pf_zero [ps.pretty, qs.pretty, p.pretty] [pq.info], pure $ overlap.zero (z.set_info pqs_o pf) end else pure overlap.none section addition lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc ps + qs = 0 + qs' : by rw [ps_pf, qs_pf] ... = qs' : zero_add _ lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc ps + qs = ps' + 0 : by rw [ps_pf, qs_pf] ... = ps' : add_zero _ lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} : pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} : pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs := λ pps_pf qqs_pf pq_pf pqs_pf, calc pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf] ... = (p + q) + (ps + qs) : by cc ... = 0 + pqs : by rw [pq_pf, pqs_pf] ... = pqs : zero_add _ lemma add_pf_sum_lt {pps p ps qqs pqs : α} : pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc lemma add_pf_sum_gt {pps qqs q qs pqs : α} : qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc /-- Add two expressions. * `0 + qs = 0` * `ps + 0 = 0` * `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`) * `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`) * `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`) -/ meta def add : ex sum → ex sum → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ qs.set_info pqs_o pf | ps qs@(ex.zero qs_i) := do pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ ps.set_info pqs_o pf | pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do ol ← add_overlap p q, ppqqs_o ← add_orig pps qqs, match ol with | (overlap.nonzero pq) := do pqs ← add ps qs, pqqs ← ex_sum pq pqs, qqs_pf ← qqs.proof_term, pf ← mk_proof ``add_pf_sum_overlap [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf | (overlap.zero pq) := do pqs ← add ps qs, pf ← mk_proof ``add_pf_sum_overlap_zero [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqs.set_info ppqqs_o pf | overlap.none := if p.lt q then do pqs ← add ps qqs, ppqs ← ex_sum p pqs, pf ← mk_proof ``add_pf_sum_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← add pps qs, pqqs ← ex_sum q pqs, pf ← mk_proof ``add_pf_sum_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end end addition section multiplication lemma mul_pf_c_c {ps ps' qs qs' pq : α} : ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc lemma mul_pf_c_prod {ps qqs q qs pqs : α} : qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc lemma mul_pf_prod_c {pps p ps qs pqs : α} : pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} : pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs → p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs := λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, _root_.pow_add, ps_pf, qs_pf]; ac_refl lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} : pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} : qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc /-- Multiply two expressions. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (q * qs) = q * (qs * x)` (for `x` coefficient) * `(p * ps) * y = p * (ps * y)` (for `y` coefficient) * `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)` (if `p_e` and `q_e` are identical except coefficient) * `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`) * `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`) -/ meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do pq ← mul_coeff ps.pretty qs.pretty x y, pq_o ← mul_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c [ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do pqs ← mul_pp ps qs, pqqs ← ex_prod q pqs, pqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_c_prod [ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info pqqs_o pf | pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do pqs ← mul_pp ps qs, ppqs ← ex_prod p pqs, ppqs_o ← mul_orig pps qs, pf ← mk_proof ``mul_pf_prod_c [pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqs_o pf | pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do ppqqs_o ← mul_orig pps qqs, pq_ol ← in_exponent $ add_overlap p_e q_e, match pq_ol, p_b.eq q_b with | (overlap.nonzero pq_e), tt := do psqs ← mul_pp ps qs, pq ← ex_exp p_b pq_e, ppsqqs ← ex_prod pq psqs, pf ← mk_proof ``mul_pp_pf_overlap [pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty] [pps.info, qqs.info, ppsqqs.info], pure $ ppsqqs.set_info ppqqs_o pf | _, _ := if p.lt q then do pqs ← mul_pp ps qqs, ppqs ← ex_prod p pqs, pf ← mk_proof ``mul_pp_pf_prod_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← mul_pp pps qs, pqqs ← ex_prod q pqs, pf ← mk_proof ``mul_pp_pf_prod_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 := λ ps_pf, by rw [ps_pf, zero_mul] lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps → p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc pps * qs = (p + ps) * qs : by rw [pps_pf] ... = p * qs + ps * qs : add_mul _ _ _ ... = ppsqs : ppsqs_pf /-- Multiply two expressions. * `0 * qs = 0` * `(p + ps) * qs = (p * qs) + (ps * qs)` -/ meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info], pure $ z.set_info z_o pf | pps@(ex.sum pps_i p ps) qs := do pqs ← mul_pp p qs >>= prod_to_sum, psqs ← mul_p ps qs, ppsqs ← add pqs psqs, pps_pf ← pps.proof_term, ppsqs_o ← mul_orig pps qs, ppsqs_pf ← ppsqs.proof_term, pf ← mk_proof ``mul_p_pf_sum [pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty] [pps.info, ppsqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 := λ qs_pf, by rw [qs_pf, mul_zero] lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs → ps * qqs = psqqs := λ qs_pf psqqs_pf, calc ps * qqs = ps * (q + qs) : by rw [qs_pf] ... = ps * q + ps * qs : mul_add _ _ _ ... = psqqs : psqqs_pf /-- Multiply two expressions. * `ps * 0 = 0` * `ps * (q + qs) = (ps * q) + (ps * qs)` -/ meta def mul : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info], pure $ z.set_info z_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← mul_p ps q, psqs ← mul ps qs, psqqs ← add psq psqs, psqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_sum [ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end multiplication section exponentiation lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} : pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs := λ pps_pf psqs_pf, calc pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf] ... = p ^ (ps * qs) : symm (pow_mul _ _ _) ... = p ^ psqs : by rw [psqs_pf] /-- Exponentiate two expressions. * `(p ^ ps) ^ qs = p ^ (ps * qs)` -/ meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp) | pps@(ex.exp pps_i p ps) qs := do psqs ← in_exponent $ mul_pp ps qs, ppsqs ← ex_exp p psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_e_pf_exp [pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty] [pps.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 := λ ps_pf, by rw [ps_pf, _root_.one_pow] lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 := by simp; cc lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps → p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs := λ pps_pf pqs_pf psqs_pf, calc pps ^ qs = (p * ps) ^ qs : by rw [pps_pf] ... = p ^ qs * ps ^ qs : mul_pow _ _ _ ... = pqs * psqs : by rw [pqs_pf, psqs_pf] /-- Exponentiate two expressions. * `1 ^ qs = 1` * `x ^ qs = x ^ qs` (for `x` coefficient) * `(p * ps) ^ qs = p ^ qs + ps ^ qs` -/ meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info], pure $ o.set_info o_o pf | ps@(ex.coeff ps_i x) qs := do ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b, pqs ← ex_exp ps'' qs, pqs_o ← pow_orig ps qs, pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c [ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pqs.info], pqs' ← exp_to_prod pqs, pure $ pqs'.set_info pqs_o pf | pps@(ex.prod pps_i p ps) qs := do pqs ← pow_e p qs, psqs ← pow_pp ps qs, ppsqs ← ex_prod pqs psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_pp_pf_prod [pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig] [pps.info, pqs.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' := λ ps_pf qs_pf, calc ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf] ... = ps' : pow_one _ lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 := λ ps_pf qs_pf, calc ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf] ... = 0 : zero_pow (succ_pos qs') lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} : qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs := λ qs_pf pqqs_pf, calc ps ^ qs = ps ^ succ qs' : by rw [qs_pf] ... = ps * ps ^ qs' : pow_succ _ _ ... = pqqs : by rw [pqqs_pf] lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} : pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs := λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf] lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc /-- Exponentiate two expressions. * `ps ^ 1 = ps` * `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`) * `(p + 0) ^ qs = p ^ qs` * `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`) * `ps ^ qs = ps ^ qs` (otherwise) -/ meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum) | ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do ps_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pure $ ps.set_info ps_o pf | ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do ctx ← get_context, z ← ex_zero, qs_pred ← lift $ expr.of_nat ctx.info_e.α y, pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info], z_o ← pow_orig ps qs, pure $ z.set_info z_o pf | pps@(ex.sum pps_i p (ex.zero _)) qqs := do pqs ← pow_pp p qqs, pqs_o ← pow_orig pps qqs, pf ← mk_proof ``pow_p_pf_singleton [pps.orig, p.pretty, pqs.pretty, qqs.orig] [pps.info, pqs.info], prod_to_sum $ pqs.set_info pqs_o pf | ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩, pqs ← pow_p ps qs', pqqs ← mul ps pqs, pqqs_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_succ [ps.orig, pqqs.pretty, qs.orig, qs'.pretty] [qs.info, pqqs.info], pure $ pqqs.set_info pqqs_o pf | pps qqs := do -- fallback: treat them as atoms pps' ← ex_sum_b pps, psqs ← ex_exp pps' qqs, psqs_o ← pow_orig pps qqs, pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons [pps.orig, pps.pretty, qqs.orig, qqs.pretty] [pps.info, qqs.info], exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc ps ^ qs = ps ^ 0 : by rw [qs_pf] ... = 1 : pow_zero _ lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs → ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf] ... = ps ^ q * ps ^ qs : pow_add _ _ _ ... = psqqs : psqqs_pf /-- Exponentiate two expressions. * `ps ^ 0 = 1` * `ps ^ (q + qs) = ps ^ q * ps ^ qs` -/ meta def pow : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info], prod_to_sum $ o.set_info o_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← pow_p ps q, psqs ← pow ps qs, psqqs ← mul psq psqs, psqqs_o ← pow_orig ps qqs, pf ← mk_proof ``pow_pf_sum [ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end exponentiation lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp /-- Give a simpler, more human-readable representation of the normalized expression. Normalized expressions might have the form `a^1 * 1 + 0`, since the dummy operations reduce special cases in pattern-matching. Humans prefer to read `a` instead. This tactic gets rid of the dummy additions, multiplications and exponentiations. -/ meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr) | sum pps@(ex.sum pps_i p (ex.zero _)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf] | sum (ex.sum pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_add [p_p, ps_p] <*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf] | prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := prod.mk pps.pretty <$> pps.proof_term | (some ringi) := do (p_p, p_pf) ← p.simple, prod.mk <$> lift (mk_app ``has_neg.neg [p_p]) <*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf] end | prod (ex.prod pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_mul [p_p, ps_p] <*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | base (ex.sum_b pps_i ps) := ps.simple | exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf] | exp (ex.exp pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← in_exponent $ ps.simple, prod.mk <$> mk_pow [p_p, ps_p] <*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | et ps := prod.mk ps.pretty <$> ps.proof_term /-- Performs a lookup of the atom `a` in the list of known atoms, or allocates a new one. If `a` is not definitionally equal to any of the list's entries, a new atom is appended to the list and returned. The index of this atom is kept track of in the second inductive argument. This function is mostly useful in `resolve_atom`, which updates the state with the new list of atoms. -/ meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom) | [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm]) | bas@(b :: as) n := do ctx ← get_context, (lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do (atm, as') ← resolve_atom_aux as (succ n), pure (atm, b :: as') /-- Convert the expression to an atom: either look up a definitionally equal atom, or allocate it as a new atom. You probably want to use `eval_base` if `eval` doesn't work instead of directly calling `resolve_atom`, since `eval_base` can also handle numerals. -/ meta def resolve_atom (a : expr) : ring_exp_m atom := do atoms ← reader_t.lift $ state_t.get, (atm, atoms') ← resolve_atom_aux a atoms 0, reader_t.lift $ state_t.put atoms', pure atm /-- Treat the expression atomically: as a coefficient or atom. Handles cases where `eval` cannot treat the expression as a known operation because it is just a number or single variable. -/ meta def eval_base (ps : expr) : ring_exp_m (ex sum) := match ps.to_rat with | some ⟨0, 1, _, _⟩ := ex_zero | some x := ex_coeff x >>= prod_to_sum | none := do a ← resolve_atom ps, atom_to_sum a end lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp /-- Negate an expression by multiplying with `-1`. Only works if there is a `ring` instance; otherwise it will `fail`. -/ meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := lift $ fail "internal error: negate called in semiring" | (some ring_instance) := do minus_one ← ex_coeff (-1) >>= prod_to_sum, ps' ← mul minus_one ps, ps_pf ← ps'.proof_term, pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf], ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig], pure $ ps'.set_info ps'_o pf end lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} : ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' := by cc /-- Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom. Only works if there is a `division_ring` instance; otherwise it will `fail`. -/ meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only supported in a division ring" | (some dri) := pure dri end, (ps_simple, ps_simple_pf) ← ps.simple, e ← lift $ mk_app ``has_inv.inv [ps_simple], (e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)), e'' ← eval_base e', ps_pf ← ps.proof_term, e''_pf ← e''.proof_term, pf ← mk_app_class ``inverse_pf dri [ ps.orig, ps.pretty, ps_simple, e', e''.pretty, ps_pf, ps_simple_pf, e_pf, e''_pf], e''_o ← lift $ mk_app ``has_inv.inv [ps.orig], pure $ e''.set_info e''_o pf lemma sub_pf {α} [ring α] {ps qs psqs : α} : ps + -qs = psqs → ps - qs = psqs := id lemma div_pf {α} [division_ring α] {ps qs psqs : α} : ps * qs⁻¹ = psqs → ps / qs = psqs := id end operations section wiring /-! ### `wiring` section This section deals with going from `expr` to `ex` and back. The main attraction is `eval`, which uses `add`, `mul`, etc. to calculate an `ex` from a given `expr`. Other functions use `ex`es to produce `expr`s together with a proof, or produce the context to run `ring_exp_m` from an `expr`. -/ open tactic open ex_type /-- Compute a normalized form (of type `ex`) from an expression (of type `expr`). This is the main driver of the `ring_exp` tactic, calling out to `add`, `mul`, `pow`, etc. to parse the `expr`. -/ meta def eval : expr → ring_exp_m (ex sum) | e@`(%%ps + %%qs) := do ps' ← eval ps, qs' ← eval qs, add ps' qs' | e@`(%%ps - %%qs) := (do ctx ← get_context, ri ← match ctx.info_b.ring_instance with | none := lift $ fail "subtraction is not directly supported in a semiring" | (some ri) := pure ri end, ps' ← eval ps, qs' ← eval qs >>= negate, psqs ← add ps' qs', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(- %%ps) := do ps' ← eval ps, negate ps' <|> eval_base e | e@`(%%ps * %%qs) := do ps' ← eval ps, qs' ← eval qs, mul ps' qs' | e@`(has_inv.inv %%ps) := do ps' ← eval ps, inverse ps' <|> eval_base e | e@`(%%ps / %%qs) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only directly supported in a division ring" | (some dri) := pure dri end, ps' ← eval ps, qs' ← eval qs, (do qs'' ← inverse qs', psqs ← mul ps' qs'', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do ps' ← eval ps, qs' ← in_exponent $ eval qs, psqs ← pow ps' qs', psqs_pf ← psqs.proof_term, (do has_pow_pf ← match hp_instance with | `(monoid.has_pow) := lift $ mk_eq_refl e | `(nat.has_pow) := lift $ mk_app ``nat.pow_eq_pow [ps, qs] >>= mk_eq_symm | _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow" end, pf ← lift $ mk_eq_trans has_pow_pf psqs_pf, pure $ psqs.set_info e pf) <|> eval_base e | ps := eval_base ps /-- Run `eval` on the expression and return the result together with normalization proof. See also `eval_simple` if you want something that behaves like `norm_num`. -/ meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do e' ← eval e, prod.mk e' <$> e'.proof_term /-- Run `eval` on the expression and simplify the result. Returns a simplified normalized expression, together with an equality proof. See also `eval_with_proof` if you just want to check the equality of two expressions. -/ meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do (complicated, complicated_pf) ← eval_with_proof e, (simple, simple_pf) ← complicated.simple, prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf) /-- Compute the `eval_info` for a given type `α`. -/ meta def make_eval_info (α : expr) : tactic eval_info := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance, ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none), dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none), ha_instance ← mk_app ``has_add [α] >>= mk_instance, hm_instance ← mk_app ``has_mul [α] >>= mk_instance, hp_instance ← mk_mapp ``monoid.has_pow [some α, none], z ← mk_mapp ``has_zero.zero [α, none], o ← mk_mapp ``has_one.one [α, none], pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩ /-- Use `e` to build the context for running `mx`. -/ meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do info_b ← infer_type e >>= make_eval_info, info_e ← mk_const ``nat >>= make_eval_info, (λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) []) /-- Repeatedly apply `eval_simple` on (sub)expressions. -/ meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do (_, e', pf') ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (e'', pf) ← run_ring_exp transp e $ eval_simple e, guard (¬ e'' =ₐ e), return ((), e'', some pf, ff)) (λ _ _ _ _ _, failed) `eq e, pure (e', pf') end wiring end tactic.ring_exp namespace tactic.interactive open interactive interactive.types lean.parser tactic tactic.ring_exp local postfix `?`:9001 := optional /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. This version of `ring_exp` fails if the target is not an equality. The variant `ring_exp_eq!` will use a more aggressive reducibility setting to determine equality of atoms. -/ meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do `(eq %%ps %%qs) ← target >>= whnf, let transp := if red.is_some then semireducible else reducible, ((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $ prod.mk <$> eval_with_proof ps <*> eval_with_proof qs, if ps'.eq qs' then do qs_pf_inv ← mk_eq_symm qs_pf, pf ← mk_eq_trans ps_pf qs_pf_inv, tactic.interactive.exact ``(%%pf) else fail "ring_exp failed to prove equality" /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. This tactic extends `ring`: it should solve every goal that `ring` can solve. Additionally, it knows how to evaluate expressions with complicated exponents (where `ring` only understands constant exponents). The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine equality of atoms. For example: ```lean example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp example (x y : ℕ) : x + id y = y + id x := by ring_exp! ``` -/ meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := ring_exp_eq red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp) ns loc.include_goal | fail "ring_exp failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "ring_exp", category := doc_category.tactic, decl_names := [`tactic.interactive.ring_exp], tags := ["arithmetic", "simplification", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive open tactic tactic.interactive (ring_exp_eq) open tactic.ring_exp (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring_exp`. -/ meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring_exp_eq red) <|> replace_lhs (normalize transp) <|> fail "ring_exp failed to simplify" end conv.interactive
d8a1981a351b040955bb22d094f9537259dbe8f7
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Elab/Command.lean
370683e5bc153f0e84c7c0217c370026d244f6ba
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,536
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.Elab.Alias import Init.Lean.Elab.Log import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Term import Init.Lean.Elab.TermBinders namespace Lean namespace Elab namespace Command structure Context := (fileName : String) (fileMap : FileMap) structure Scope := (kind : String) (header : String) (opts : Options := {}) (currNamespace : Name := Name.anonymous) (openDecls : List OpenDecl := []) (univNames : List Name := []) (varDecls : Array Syntax := #[]) instance Scope.inhabited : Inhabited Scope := ⟨{ kind := "", header := "" }⟩ structure State := (env : Environment) (messages : MessageLog := {}) (cmdPos : String.Pos := 0) (scopes : List Scope := [{ kind := "root", header := "" }]) instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _ }⟩ def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env, messages := messages, scopes := [{ kind := "root", header := "", opts := opts }] } abbrev CommandElabM := ReaderT Context (EStateM Exception State) abbrev CommandElab := SyntaxNode → CommandElabM Unit instance CommandElabM.monadLog : MonadLog CommandElabM := { getCmdPos := do s ← get; pure s.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } } abbrev CommandElabTable := ElabFnTable CommandElab def mkBuiltinCommandElabTable : IO (IO.Ref CommandElabTable) := IO.mkRef {} @[init mkBuiltinCommandElabTable] constant builtinCommandElabTable : IO.Ref CommandElabTable := arbitrary _ def addBuiltinCommandElab (k : SyntaxNodeKind) (declName : Name) (elab : CommandElab) : IO Unit := do m ← builtinCommandElabTable.get; when (m.contains k) $ throw (IO.userError ("invalid builtin command elaborator, elaborator for '" ++ toString k ++ "' has already been defined")); builtinCommandElabTable.modify $ fun m => m.insert k elab def declareBuiltinCommandElab (env : Environment) (kind : SyntaxNodeKind) (declName : Name) : IO Environment := let name := `_regBuiltinCommandElab ++ declName; let type := mkApp (mkConst `IO) (mkConst `Unit); let val := mkAppN (mkConst `Lean.Elab.Command.addBuiltinCommandElab) #[toExpr kind, toExpr declName, mkConst declName]; let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false }; match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error _ => throw (IO.userError ("failed to emit registration code for builtin command elaborator '" ++ toString declName ++ "'")) | Except.ok env => IO.ofExcept (setInitAttr env name) @[init] def registerBuiltinCommandElabAttr : IO Unit := registerAttribute { name := `builtinCommandElab, descr := "Builtin command elaborator", add := fun env declName arg persistent => do { unless persistent $ throw (IO.userError ("invalid attribute 'builtinCommandElab', must be persistent")); kind ← IO.ofExcept $ syntaxNodeKindOfAttrParam env `Lean.Parser.Command arg; match env.find? declName with | none => throw "unknown declaration" | some decl => match decl.type with | Expr.const `Lean.Elab.Command.CommandElab _ _ => declareBuiltinCommandElab env kind declName | _ => throw (IO.userError ("unexpected command elaborator type at '" ++ toString declName ++ "' `CommandElab` expected")) }, applicationTime := AttributeApplicationTime.afterCompilation } abbrev CommandElabAttribute := ElabAttribute CommandElab def mkCommandElabAttribute : IO CommandElabAttribute := mkElabAttribute CommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" builtinCommandElabTable @[init mkCommandElabAttribute] constant commandElabAttribute : CommandElabAttribute := arbitrary _ def elabCommand (stx : Syntax) : CommandElabM Unit := stx.ifNode (fun n => do s ← get; let table := (commandElabAttribute.ext.getState s.env).table; let k := n.getKind; match table.find? k with | some elab => elab n | none => throwError stx ("command '" ++ toString k ++ "' has not been implemented")) (fun _ => throwError stx ("unexpected command")) private def mkTermContext (ctx : Context) (s : State) : Term.Context := let scope := s.scopes.head!; { config := { opts := scope.opts, foApprox := true, ctxApprox := true, quasiPatternApprox := true, isDefEqStuckEx := true }, fileName := ctx.fileName, fileMap := ctx.fileMap, cmdPos := s.cmdPos, currNamespace := scope.currNamespace, univNames := scope.univNames, openDecls := scope.openDecls } private def mkTermState (s : State) : Term.State := { env := s.env, messages := s.messages } private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls private def toCommandResult {α} (ctx : Context) (s : State) (result : EStateM.Result Term.Exception Term.State α) : EStateM.Result Exception State α := match result with | EStateM.Result.ok a newS => EStateM.Result.ok a { env := newS.env, messages := newS.messages, .. s } | EStateM.Result.error (Term.Exception.error ex) newS => EStateM.Result.error ex { env := newS.env, messages := newS.messages, .. s } | EStateM.Result.error Term.Exception.postpone newS => unreachable! @[inline] def runTermElabM {α} (x : TermElabM α) : CommandElabM α := fun ctx s => toCommandResult ctx s $ (Term.elabBinders (getVarDecls s) (fun _ => x)) (mkTermContext ctx s) (mkTermState s) def dbgTrace {α} [HasToString α] (a : α) : CommandElabM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () def getEnv : CommandElabM Environment := do s ← get; pure s.env def setEnv (newEnv : Environment) : CommandElabM Unit := modify $ fun s => { env := newEnv, .. s } def getScope : CommandElabM Scope := do s ← get; pure s.scopes.head! def getOptions : CommandElabM Options := do scope ← getScope; pure scope.opts def getCurrNamespace : CommandElabM Name := do scope ← getScope; pure scope.currNamespace private def addScope (kind : String) (header : String) (newNamespace : Name) : CommandElabM Unit := modify $ fun s => { env := s.env.registerNamespace newNamespace, scopes := { kind := kind, header := header, currNamespace := newNamespace, .. s.scopes.head! } :: s.scopes, .. s } private def addScopes (kind : String) (updateNamespace : Bool) : Name → CommandElabM Unit | Name.anonymous => pure () | Name.str p header _ => do addScopes p; currNamespace ← getCurrNamespace; addScope kind header (if updateNamespace then currNamespace ++ header else currNamespace) | _ => unreachable! @[builtinCommandElab «namespace»] def elabNamespace : CommandElab := fun n => do let header := n.getIdAt 1; addScopes "namespace" true header @[builtinCommandElab «section»] def elabSection : CommandElab := fun n => do let header? := (n.getArg 1).getOptionalIdent; match header? with | some header => addScopes "section" false header | none => do currNamespace ← getCurrNamespace; addScope "section" "" currNamespace def getScopes : CommandElabM (List Scope) := do s ← get; pure s.scopes private def checkAnonymousScope : List Scope → Bool | { header := "", .. } :: _ => true | _ => false private def checkEndHeader : Name → List Scope → Bool | Name.anonymous, _ => true | Name.str p s _, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes | _, _ => false @[builtinCommandElab «end»] def elabEnd : CommandElab := fun n => do let header? := (n.getArg 1).getOptionalIdent; let endSize := match header? with | none => 1 | some n => n.getNumParts; scopes ← getScopes; if endSize < scopes.length then modify $ fun s => { scopes := s.scopes.drop endSize, .. s } else do { -- we keep "root" scope modify $ fun s => { scopes := s.scopes.drop (s.scopes.length - 1), .. s }; throwError n.val "invalid 'end', insufficient scopes" }; match header? with | none => unless (checkAnonymousScope scopes) $ throwError n.val "invalid 'end', name is missing" | some header => unless (checkEndHeader header scopes) $ throwError n.val "invalid 'end', name mismatch" @[specialize] def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify $ fun s => { scopes := match s.scopes with | h::t => f h :: t | [] => unreachable!, .. s } def getUniverseNames : CommandElabM (List Name) := do scope ← getScope; pure scope.univNames def addUniverse (idStx : Syntax) : CommandElabM Unit := do let id := idStx.getId; univs ← getUniverseNames; if univs.elem id then throwError idStx ("a universe named '" ++ toString id ++ "' has already been declared in this Scope") else modifyScope $ fun scope => { univNames := id :: scope.univNames, .. scope } @[builtinCommandElab «universe»] def elabUniverse : CommandElab := fun n => do addUniverse (n.getArg 1) @[builtinCommandElab «universes»] def elabUniverses : CommandElab := fun n => do let idsStx := n.getArg 1; idsStx.forArgsM addUniverse @[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab := fun stx => do env ← getEnv; match env.addDecl Declaration.quotDecl with | Except.ok env => setEnv env | Except.error ex => do opts ← getOptions; throwError stx.val (ex.toMessageData opts) def getOpenDecls : CommandElabM (List OpenDecl) := do scope ← getScope; pure scope.openDecls def logUnknownDecl (stx : Syntax) (declName : Name) : CommandElabM Unit := logError stx ("unknown declaration '" ++ toString declName ++ "'") def resolveNamespace (id : Name) : CommandElabM Name := do env ← getEnv; currNamespace ← getCurrNamespace; openDecls ← getOpenDecls; match Elab.resolveNamespace env currNamespace openDecls id with | some ns => pure ns | none => throwErrorUsingCmdPos ("unknown namespace '" ++ toString id ++ "'") @[builtinCommandElab «export»] def elabExport : CommandElab := fun stx => do -- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")") let id := stx.getIdAt 1; ns ← resolveNamespace id; currNamespace ← getCurrNamespace; when (ns == currNamespace) $ throwError stx.val "invalid 'export', self export"; env ← getEnv; let ids := (stx.getArg 3).getArgs; aliases ← ids.foldlM (fun (aliases : List (Name × Name)) (idStx : Syntax) => do { let id := idStx.getId; let declName := ns ++ id; if env.contains declName then pure $ (currNamespace ++ id, declName) :: aliases else do logUnknownDecl idStx declName; pure aliases }) []; modify $ fun s => { env := aliases.foldl (fun env p => addAlias env p.1 p.2) s.env, .. s } def addOpenDecl (d : OpenDecl) : CommandElabM Unit := modifyScope $ fun scope => { openDecls := d :: scope.openDecls, .. scope } def elabOpenSimple (n : SyntaxNode) : CommandElabM Unit := -- `open` id+ let nss := n.getArg 0; nss.forArgsM $ fun ns => do ns ← resolveNamespace ns.getId; addOpenDecl (OpenDecl.simple ns []) -- `open` id `(` id+ `)` def elabOpenOnly (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let ids := n.getArg 2; ids.forArgsM $ fun idStx => do let id := idStx.getId; let declName := ns ++ id; env ← getEnv; if env.contains declName then addOpenDecl (OpenDecl.explicit id declName) else logUnknownDecl idStx declName -- `open` id `hiding` id+ def elabOpenHiding (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let idsStx := n.getArg 2; env ← getEnv; ids : List Name ← idsStx.foldArgsM (fun idStx ids => do let id := idStx.getId; let declName := ns ++ id; if env.contains declName then pure (id::ids) else do logUnknownDecl idStx declName; pure ids) []; addOpenDecl (OpenDecl.simple ns ids) -- `open` id `renaming` sepBy (id `->` id) `,` def elabOpenRenaming (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let rs := (n.getArg 2); rs.forSepArgsM $ fun stx => do let fromId := stx.getIdAt 0; let toId := stx.getIdAt 2; let declName := ns ++ fromId; env ← getEnv; if env.contains declName then addOpenDecl (OpenDecl.explicit toId declName) else logUnknownDecl stx declName @[builtinCommandElab «open»] def elabOpen : CommandElab := fun n => do let body := (n.getArg 1).asNode; let k := body.getKind; if k == `Lean.Parser.Command.openSimple then elabOpenSimple body else if k == `Lean.Parser.Command.openOnly then elabOpenOnly body else if k == `Lean.Parser.Command.openHiding then elabOpenHiding body else elabOpenRenaming body /- We just ignore Lean3 notation declaration commands. -/ @[builtinCommandElab «mixfix»] def elabMixfix : CommandElab := fun _ => pure () @[builtinCommandElab «reserve»] def elabReserve : CommandElab := fun _ => pure () @[builtinCommandElab «notation»] def elabNotation : CommandElab := fun _ => pure () @[builtinCommandElab «variable»] def elabVariable : CommandElab := fun n => do -- `variable` bracktedBinder let binder := n.getArg 1; -- Try to elaborate `binder` for sanity checking runTermElabM $ Term.elabBinder binder $ fun _ => pure (); modifyScope $ fun scope => { varDecls := scope.varDecls.push binder, .. scope } @[builtinCommandElab «variables»] def elabVariables : CommandElab := fun n => do -- `variables` bracktedBinder+ let binders := (n.getArg 1).getArgs; -- Try to elaborate `binders` for sanity checking runTermElabM $ Term.elabBinders binders $ fun _ => pure (); modifyScope $ fun scope => { varDecls := scope.varDecls ++ binders, .. scope } @[builtinCommandElab «check»] def elabCheck : CommandElab := fun stx => do let term := stx.getArg 1; runTermElabM $ do e ← Term.elabTerm term none; Term.synthesizeSyntheticMVars false; type ← Term.inferType stx.val e; e ← Term.instantiateMVars stx.val e; type ← Term.instantiateMVars stx.val type; logInfo stx.val (e ++ " : " ++ type); pure () end Command end Elab end Lean
f9158ae49cec7b92256251828ab66d97d62629f2
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/IndPredBelow.lean
18e3fccd755111c45d1f4bed1ef0a0e8cd28a49d
[ "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
25,783
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import Lean.Meta.Constructions import Lean.Meta.Transform import Lean.Meta.Tactic import Lean.Meta.Match.Match import Lean.Meta.Reduce namespace Lean.Meta.IndPredBelow open Match register_builtin_option maxBackwardChainingDepth : Nat := { defValue := 10 descr := "The maximum search depth used in the backwards chaining part of the proof of `brecOn` for inductive predicates." } /-- The context used in the creation of the `below` scheme for inductive predicates. -/ structure Context where motives : Array (Name × Expr) typeInfos : Array InductiveVal belowNames : Array Name headers : Array Expr numParams : Nat /-- Collection of variables used to keep track of the positions of binders in the construction of `below` motives and constructors. -/ structure Variables where target : Array Expr indVal : Array Expr params : Array Expr args : Array Expr motives : Array Expr innerType : Expr deriving Inhabited /-- Collection of variables used to keep track of the local context used in the `brecOn` proof. -/ structure BrecOnVariables where params : Array FVarId motives : Array FVarId indices : Array FVarId witness : FVarId indHyps : Array FVarId def mkContext (declName : Name) : MetaM Context := do let indVal ← getConstInfoInduct declName let typeInfos ← indVal.all.toArray.mapM getConstInfoInduct let motiveTypes ← typeInfos.mapM motiveType let motives ← motiveTypes.mapIdxM fun j motive => do (← motiveName motiveTypes j.val, motive) let headers ← typeInfos.mapM $ mkHeader motives indVal.numParams return { motives := motives typeInfos := typeInfos numParams := indVal.numParams headers := headers belowNames := (← indVal.all.toArray.map (· ++ `below)) } where motiveName (motiveTypes : Array Expr) (i : Nat) : MetaM Name := if motiveTypes.size > 1 then mkFreshUserName s!"motive_{i.succ}" else mkFreshUserName "motive" mkHeader (motives : Array (Name × Expr)) (numParams : Nat) (indVal : InductiveVal) : MetaM Expr := do let header ← forallTelescopeReducing indVal.type fun xs t => do withNewBinderInfos (xs.map fun x => (x.fvarId!, BinderInfo.implicit)) $ mkForallFVars xs (← mkArrow (mkAppN (mkIndValConst indVal) xs) t) addMotives motives numParams header addMotives (motives : Array (Name × Expr)) (numParams : Nat) : Expr → MetaM Expr := motives.foldrM (fun (motiveName, motive) t => forallTelescopeReducing t fun xs s => do let motiveType ← instantiateForall motive xs[:numParams] withLocalDecl motiveName BinderInfo.implicit motiveType fun motive => do mkForallFVars (xs.insertAt numParams motive) s) motiveType (indVal : InductiveVal) : MetaM Expr := forallTelescopeReducing indVal.type fun xs t => do mkForallFVars xs (← mkArrow (mkAppN (mkIndValConst indVal) xs) (mkSort levelZero)) mkIndValConst (indVal : InductiveVal) : Expr := mkConst indVal.name $ indVal.levelParams.map mkLevelParam partial def mkCtorType (ctx : Context) (belowIdx : Nat) (originalCtor : ConstructorVal) : MetaM Expr := forallTelescopeReducing originalCtor.type fun xs t => addHeaderVars { innerType := t indVal := #[] motives := #[] params := xs[:ctx.numParams] args := xs[ctx.numParams:] target := xs[:ctx.numParams] } where addHeaderVars (vars : Variables) := do let headersWithNames ← ctx.headers.mapIdxM fun idx header => (ctx.belowNames[idx], fun _ : Array Expr => pure header) withLocalDeclsD headersWithNames fun xs => addMotives { vars with indVal := xs } addMotives (vars : Variables) := do let motiveBuilders ← ctx.motives.mapM fun (motiveName, motiveType) => (motiveName, BinderInfo.implicit, fun _ : Array Expr => instantiateForall motiveType vars.params) withLocalDecls motiveBuilders fun xs => modifyBinders { vars with target := vars.target ++ xs, motives := xs } 0 modifyBinders (vars : Variables) (i : Nat) := do if i < vars.args.size then let binder := vars.args[i] let binderType ← inferType binder if (← checkCount binderType) then mkBelowBinder vars binder binderType fun indValIdx x => mkMotiveBinder vars indValIdx binder binderType fun y => withNewBinderInfos #[(binder.fvarId!, BinderInfo.implicit)] do modifyBinders { vars with target := vars.target ++ #[binder, x, y]} i.succ else modifyBinders { vars with target := vars.target.push binder } i.succ else rebuild vars rebuild (vars : Variables) := vars.innerType.withApp fun f args => do let hApp := mkAppN (mkConst originalCtor.name $ ctx.typeInfos[0].levelParams.map mkLevelParam) (vars.params ++ vars.args) let innerType := mkAppN vars.indVal[belowIdx] $ vars.params ++ vars.motives ++ args[ctx.numParams:] ++ #[hApp] let x ← mkForallFVars vars.target innerType replaceTempVars vars x replaceTempVars (vars : Variables) (ctor : Expr) := let levelParams := ctx.typeInfos[0].levelParams.map mkLevelParam ctor.replaceFVars vars.indVal $ ctx.belowNames.map fun indVal => mkConst indVal levelParams checkCount (domain : Expr) : MetaM Bool := do let run (x : StateRefT Nat MetaM Expr) : MetaM (Expr × Nat) := StateRefT'.run x 0 let (_, cnt) ← run $ transform domain fun e => do if let some name := e.constName? then if let some idx := ctx.typeInfos.findIdx? fun indVal => indVal.name == name then modify (. + 1) TransformStep.visit e if cnt > 1 then throwError "only arrows are allowed as premises. Multiple recursive occurrences detected:{indentExpr domain}" return cnt == 1 mkBelowBinder (vars : Variables) (binder : Expr) (domain : Expr) {α : Type} (k : Nat → Expr → MetaM α) : MetaM α := do forallTelescopeReducing domain fun xs t => do let fail _ := do throwError "only trivial inductive applications supported in premises:{indentExpr t}" t.withApp fun f args => do if let some name := f.constName? then if let some idx := ctx.typeInfos.findIdx? fun indVal => indVal.name == name then let indVal := ctx.typeInfos[idx] let hApp := mkAppN binder xs let t := mkAppN vars.indVal[idx] $ vars.params ++ vars.motives ++ args[ctx.numParams:] ++ #[hApp] let newDomain ← mkForallFVars xs t withLocalDecl (←copyVarName binder.fvarId!) binder.binderInfo newDomain (k idx) else fail () else fail () mkMotiveBinder (vars : Variables) (indValIdx : Nat) (binder : Expr) (domain : Expr) {α : Type} (k : Expr → MetaM α) : MetaM α := do forallTelescopeReducing domain fun xs t => do t.withApp fun f args => do let hApp := mkAppN binder xs let t := mkAppN vars.motives[indValIdx] $ args[ctx.numParams:] ++ #[hApp] let newDomain ← mkForallFVars xs t withLocalDecl (←copyVarName binder.fvarId!) binder.binderInfo newDomain k copyVarName (oldName : FVarId) : MetaM Name := do let binderDecl ← getLocalDecl oldName mkFreshUserName binderDecl.userName def mkConstructor (ctx : Context) (i : Nat) (ctor : Name) : MetaM Constructor := do let ctorInfo ← getConstInfoCtor ctor let name := ctor.updatePrefix ctx.belowNames[i] let type ← mkCtorType ctx i ctorInfo return { name := name type := type } def mkInductiveType (ctx : Context) (i : Fin ctx.typeInfos.size) (indVal : InductiveVal) : MetaM InductiveType := do return { name := ctx.belowNames[i] type := ctx.headers[i] ctors := (← indVal.ctors.mapM (mkConstructor ctx i)) } def mkBelowDecl (ctx : Context) : MetaM Declaration := do let lparams := ctx.typeInfos[0].levelParams Declaration.inductDecl lparams (ctx.numParams + ctx.motives.size) (←ctx.typeInfos.mapIdxM $ mkInductiveType ctx).toList ctx.typeInfos[0].isUnsafe partial def backwardsChaining (m : MVarId) (depth : Nat) : MetaM Bool := do if depth = 0 then false else withMVarContext m do let lctx ← getLCtx let mTy ← getMVarType m lctx.anyM fun localDecl => if localDecl.isAuxDecl then false else commitWhen do let (mvars, _, t) ← forallMetaTelescope localDecl.type if ←isDefEq mTy t then assignExprMVar m (mkAppN localDecl.toExpr mvars) mvars.allM fun v => isExprMVarAssigned v.mvarId! <||> backwardsChaining v.mvarId! (depth - 1) else false partial def proveBrecOn (ctx : Context) (indVal : InductiveVal) (type : Expr) : MetaM Expr := do let main ← mkFreshExprSyntheticOpaqueMVar type let (m, vars) ← intros main.mvarId! let [m] ← applyIH m vars | throwError "applying the induction hypothesis should only return one goal" let ms ← induction m vars let ms ← applyCtors ms let maxDepth := maxBackwardChainingDepth.get $ ←getOptions ms.forM (closeGoal vars maxDepth) instantiateMVars main where intros (m : MVarId) : MetaM (MVarId × BrecOnVariables) := do let (params, m) ← introNP m indVal.numParams let (motives, m) ← introNP m ctx.motives.size let (indices, m) ← introNP m indVal.numIndices let (witness, m) ← intro1P m let (indHyps, m) ← introNP m ctx.motives.size return (m, ⟨params, motives, indices, witness, indHyps⟩) applyIH (m : MVarId) (vars : BrecOnVariables) : MetaM (List MVarId) := do match (← vars.indHyps.findSomeM? fun ih => do try some $ (←apply m $ mkFVar ih) catch ex => none) with | some goals => goals | none => throwError "cannot apply induction hypothesis: {MessageData.ofGoal m}" induction (m : MVarId) (vars : BrecOnVariables) : MetaM (List MVarId) := do let params := vars.params.map mkFVar let motives := vars.motives.map mkFVar let levelParams := indVal.levelParams.map mkLevelParam let motives ← ctx.motives.mapIdxM fun idx (_, motive) => do let motive ← instantiateForall motive params forallTelescopeReducing motive fun xs _ => do mkLambdaFVars xs $ mkAppN (mkConst ctx.belowNames[idx] levelParams) $ (params ++ motives ++ xs) let recursorInfo ← getConstInfo $ mkRecName indVal.name let recLevels := if recursorInfo.numLevelParams > levelParams.length then levelZero::levelParams else levelParams let recursor ← mkAppN (mkConst recursorInfo.name $ recLevels) $ params ++ motives apply m recursor applyCtors (ms : List MVarId) : MetaM $ List MVarId := do let mss ← ms.toArray.mapIdxM fun idx m => do let m ← introNPRec m (← getMVarType m).withApp fun below args => withMVarContext m do args.back.withApp fun ctor ctorArgs => do let ctorName := ctor.constName!.updatePrefix below.constName! let ctor := mkConst ctorName below.constLevels! let ctorInfo ← getConstInfoCtor ctorName let (mvars, _, t) ← forallMetaTelescope ctorInfo.type let ctor := mkAppN ctor mvars apply m ctor return mss.foldr List.append [] introNPRec (m : MVarId) : MetaM MVarId := do if (← getMVarType m).isForall then introNPRec (←intro1P m).2 else m closeGoal (vars : BrecOnVariables) (maxDepth : Nat) (m : MVarId) : MetaM Unit := do unless (← isExprMVarAssigned m) do let m ← introNPRec m unless (← backwardsChaining m maxDepth) do withMVarContext m do throwError "couldn't solve by backwards chaining ({``maxBackwardChainingDepth} = {maxDepth}): {MessageData.ofGoal m}" def mkBrecOnDecl (ctx : Context) (idx : Nat) : MetaM Declaration := do let type ← mkType let indVal := ctx.typeInfos[idx] let name := indVal.name ++ brecOnSuffix Declaration.thmDecl { name := name levelParams := indVal.levelParams type := type value := ←proveBrecOn ctx indVal type } where mkType : MetaM Expr := forallTelescopeReducing ctx.headers[idx] fun xs t => do let params := xs[:ctx.numParams] let motives := xs[ctx.numParams:ctx.numParams + ctx.motives.size].toArray let indices := xs[ctx.numParams + ctx.motives.size:] let motiveBinders ← ctx.motives.mapIdxM $ mkIH params motives withLocalDeclsD motiveBinders fun ys => do mkForallFVars (xs ++ ys) (mkAppN motives[idx] indices) mkIH (params : Array Expr) (motives : Array Expr) (idx : Fin ctx.motives.size) (motive : Name × Expr) : MetaM $ Name × (Array Expr → MetaM Expr) := do let name := if ctx.motives.size > 1 then mkFreshUserName s!"ih_{idx.val.succ}" else mkFreshUserName "ih" let ih ← instantiateForall motive.2 params let mkDomain (_ : Array Expr) : MetaM Expr := forallTelescopeReducing ih fun ys t => do let levels := ctx.typeInfos[idx].levelParams.map mkLevelParam let args := params ++ motives ++ ys let premise := mkAppN (mkConst ctx.belowNames[idx.val] levels) args let conclusion := mkAppN motives[idx] ys mkForallFVars ys (←mkArrow premise conclusion) (←name, mkDomain) /-- Given a constructor name, find the indices of the corresponding `below` version thereof. -/ partial def getBelowIndices (ctorName : Name) : MetaM $ Array Nat := do let ctorInfo ← getConstInfoCtor ctorName let belowCtorInfo ← getConstInfoCtor (ctorName.updatePrefix $ ctorInfo.induct ++ `below) let belowInductInfo ← getConstInfoInduct belowCtorInfo.induct forallTelescopeReducing ctorInfo.type fun xs t => do loop xs belowCtorInfo.type #[] 0 0 where loop (xs : Array Expr) (rest : Expr) (belowIndices : Array Nat) (xIdx yIdx : Nat) : MetaM $ Array Nat := do if xIdx ≥ xs.size then belowIndices else let x := xs[xIdx] let xTy ← inferType x let yTy := rest.bindingDomain! if (← isDefEq xTy yTy) then let rest ← instantiateForall rest #[x] loop xs rest (belowIndices.push yIdx) (xIdx + 1) (yIdx + 1) else forallBoundedTelescope rest (some 1) fun ys rest => loop xs rest belowIndices xIdx (yIdx + 1) private def belowType (motive : Expr) (xs : Array Expr) (idx : Nat) : MetaM $ Name × Expr := do (← inferType xs[idx]).withApp fun type args => do let indName := type.constName! let indInfo ← getConstInfoInduct indName let belowArgs := args[:indInfo.numParams] ++ #[motive] ++ args[indInfo.numParams:] ++ #[xs[idx]] let belowType := mkAppN (mkConst (indName ++ `below) type.constLevels!) belowArgs (indName, belowType) /-- This function adds an additional `below` discriminant to a matcher application. It is used for modifying the patterns, such that the structural recursion can use the new `below` predicate instead of the original one and thus be used prove structural recursion. It takes as parameters: - matcherApp: a matcher application - belowMotive: the motive, that the `below` type should carry - below: an expression from the local context that is the `below` version of a predicate and can be used for structural recursion - idx: the index of the original predicate discriminant. It returns: - A matcher application as an expression - A side-effect for adding the matcher to the environment -/ partial def mkBelowMatcher (matcherApp : MatcherApp) (belowMotive : Expr) (below : Expr) (idx : Nat) : MetaM $ Expr × MetaM Unit := do let mkMatcherInput ← getMkMatcherInputInContext matcherApp let (indName, belowType, motive, matchType) ← forallBoundedTelescope mkMatcherInput.matchType mkMatcherInput.numDiscrs fun xs t => do let (indName, belowType) ← belowType belowMotive xs idx let matchType ← withLocalDeclD (←mkFreshUserName `h_below) belowType fun h_below => do mkForallFVars (xs.push h_below) t let motive ← newMotive belowType xs (indName, belowType.replaceFVars xs matcherApp.discrs, motive, matchType) let lhss ← mkMatcherInput.lhss.mapM $ addBelowPattern indName let alts ← mkMatcherInput.lhss.zip lhss |>.toArray.zip matcherApp.alts |>.mapIdxM fun idx ((oldLhs, lhs), alt) => do withExistingLocalDecls (oldLhs.fvarDecls ++ lhs.fvarDecls) do lambdaTelescope alt fun xs t => do let oldFVars := oldLhs.fvarDecls.toArray let fvars := lhs.fvarDecls.toArray.map (·.toExpr) let xs := -- special case: if we had no free vars, i.e. there was a unit added and no we do have free vars, we get rid of the unit. match oldFVars.size, fvars.size with | 0, n+1 => xs[1:] | _, _ => xs let t := t.replaceFVars xs[:oldFVars.size] fvars[:oldFVars.size] trace[Meta.IndPredBelow.match] "xs = {xs}; oldFVars = {oldFVars.map (·.toExpr)}; fvars = {fvars}; new = {fvars[:oldFVars.size] ++ xs[oldFVars.size:] ++ fvars[oldFVars.size:]}" let newAlt ← mkLambdaFVars (fvars[:oldFVars.size] ++ xs[oldFVars.size:] ++ fvars[oldFVars.size:]) t trace[Meta.IndPredBelow.match] "alt {idx}:\n{alt} ↦ {newAlt}" newAlt let matcherName ← mkFreshUserName mkMatcherInput.matcherName withExistingLocalDecls (lhss.foldl (init := []) fun s v => s ++ v.fvarDecls) do for lhs in lhss do trace[Meta.IndPredBelow.match] "{←lhs.patterns.mapM (·.toMessageData)}" let res ← Match.mkMatcher { matcherName, matchType, numDiscrs := (mkMatcherInput.numDiscrs + 1), lhss } res.addMatcher -- if a wrong index is picked, the resulting matcher can be type-incorrect. -- we check here, so that errors can propagate higher up the call stack. check res.matcher let args := #[motive] ++ matcherApp.discrs.push below ++ alts let newApp := mkApp res.matcher motive let newApp := mkAppN newApp $ matcherApp.discrs.push below let newApp := mkAppN newApp alts (newApp, res.addMatcher) where addBelowPattern (indName : Name) (lhs : AltLHS) : MetaM AltLHS := do withExistingLocalDecls lhs.fvarDecls do let patterns := lhs.patterns.toArray let originalPattern := patterns[idx] let (fVars, belowPattern) ← convertToBelow indName patterns[idx] withExistingLocalDecls fVars.toList do let patterns := patterns.push belowPattern let patterns := patterns.set! idx (←toInaccessible originalPattern) { lhs with patterns := patterns.toList, fvarDecls := lhs.fvarDecls ++ fVars.toList } /-- this function changes the type of the pattern from the original type to the `below` version thereof. Most of the cases don't apply. In order to change the type and the pattern to be type correct, we don't simply recursively change all occurrences, but rather, we recursively change occurences of the constructor. As such there are only a few cases: - the pattern is a constructor from the original type. Here we need to: - replace the constructor - copy original recursive patterns and convert them to below and reintroduce them in the correct position - turn original recursive patterns inaccessible - introduce free variables as needed. - it is an `as` pattern. Here the contstructor could be hidden inside of it. - it is a variable. Here you we need to introduce a fresh variable of a different type. -/ convertToBelow (indName : Name) (originalPattern : Pattern) : MetaM $ Array LocalDecl × Pattern := do match originalPattern with | Pattern.ctor ctorName us params fields => let ctorInfo ← getConstInfoCtor ctorName let belowCtor ← getConstInfoCtor $ ctorName.updatePrefix $ ctorInfo.induct ++ `below let belowIndices ← IndPredBelow.getBelowIndices ctorName let belowIndices := belowIndices[ctorInfo.numParams:].toArray.map (· - belowCtor.numParams) -- belowFieldOpts starts off with an array of empty fields. -- We then go over pattern's fields and set the appropriate fields to values. -- In general, there are fewer `fields` than `belowFieldOpts`, because the -- `belowCtor` carries a `below`, a non-`below` and a `motive` version of each -- field that occurs in a recursive application of the inductive predicate. -- `belowIndices` is a mapping from non-`below` to the `below` version of each field. let mut belowFieldOpts := mkArray belowCtor.numFields none let fields := fields.toArray for fieldIdx in [:fields.size] do belowFieldOpts := belowFieldOpts.set! belowIndices[fieldIdx] (some fields[fieldIdx]) let belowParams := params.toArray.push belowMotive let belowCtorExpr := mkAppN (mkConst belowCtor.name us) belowParams let (additionalFVars, belowFields) ← transformFields belowCtorExpr indName belowFieldOpts withExistingLocalDecls additionalFVars.toList do let ctor := Pattern.ctor belowCtor.name us belowParams.toList belowFields.toList trace[Meta.IndPredBelow.match] "{originalPattern.toMessageData} ↦ {ctor.toMessageData}" (additionalFVars, ctor) | Pattern.as varId p => let (additionalFVars, p) ← convertToBelow indName p (additionalFVars, Pattern.as varId p) | Pattern.var varId => let var := mkFVar varId (←inferType var).withApp fun ind args => do let (_, tgtType) ← belowType belowMotive #[var] 0 withLocalDeclD (←mkFreshUserName `h) tgtType fun h => do let localDecl ← getFVarLocalDecl h (#[localDecl], Pattern.var h.fvarId!) | p => (#[], p) transformFields belowCtor indName belowFieldOpts := let rec loop (belowCtor : Expr) (belowFieldOpts : Array $ Option Pattern) (belowFields : Array Pattern) (additionalFVars : Array LocalDecl) : MetaM (Array LocalDecl × Array Pattern) := do if belowFields.size ≥ belowFieldOpts.size then (additionalFVars, belowFields) else if let some belowField := belowFieldOpts[belowFields.size] then let belowFieldExpr ← belowField.toExpr let belowCtor := mkApp belowCtor belowFieldExpr let patTy ← inferType belowFieldExpr patTy.withApp fun f args => do let constName := f.constName? if constName == indName then let (fvars, transformedField) ← convertToBelow indName belowField withExistingLocalDecls fvars.toList do let belowFieldOpts := belowFieldOpts.set! (belowFields.size + 1) transformedField let belowField := match belowField with | Pattern.ctor .. => Pattern.inaccessible belowFieldExpr | _ => belowField loop belowCtor belowFieldOpts (belowFields.push belowField) (additionalFVars ++ fvars) else loop belowCtor belowFieldOpts (belowFields.push belowField) additionalFVars else let ctorType ← inferType belowCtor withLocalDeclD (←mkFreshUserName `a) ctorType.bindingDomain! fun a => do let localDecl ← getFVarLocalDecl a loop (mkApp belowCtor a) belowFieldOpts (belowFields.push $ Pattern.var a.fvarId!) (additionalFVars.push localDecl) loop belowCtor belowFieldOpts #[] #[] toInaccessible : Pattern → MetaM Pattern | Pattern.inaccessible p => Pattern.inaccessible p | Pattern.var v => Pattern.var v | p => do Pattern.inaccessible $ ←p.toExpr newMotive (belowType : Expr) (ys : Array Expr) : MetaM Expr := lambdaTelescope matcherApp.motive fun xs t => do let numDiscrs := matcherApp.discrs.size withLocalDeclD (←mkFreshUserName `h_below) (←belowType.replaceFVars ys xs) fun h_below => do let motive ← mkLambdaFVars (xs[:numDiscrs] ++ #[h_below] ++ xs[numDiscrs:]) t trace[Meta.IndPredBelow.match] "motive := {motive}" motive def findBelowIdx (xs : Array Expr) (motive : Expr) : MetaM $ Option (Expr × Nat) := do xs.findSomeM? fun x => do let xTy ← inferType x xTy.withApp fun f args => match f.constName?, xs.indexOf? x with | some name, some idx => do if (← isInductivePredicate name) then let (_, belowTy) ← belowType motive xs idx let below ← mkFreshExprSyntheticOpaqueMVar belowTy try trace[Meta.IndPredBelow.match] "{←Meta.ppGoal below.mvarId!}" if (← backwardsChaining below.mvarId! 10) then trace[Meta.IndPredBelow.match] "Found below term in the local context: {below}" if (← xs.anyM (isDefEq below)) then none else (below, idx.val) else trace[Meta.IndPredBelow.match] "could not find below term in the local context" none catch _ => none else none | _, _ => none def mkBelow (declName : Name) : MetaM Unit := do if (← isInductivePredicate declName) then let x ← getConstInfoInduct declName if x.isRec then let ctx ← IndPredBelow.mkContext declName let decl ← IndPredBelow.mkBelowDecl ctx addDecl decl trace[Meta.IndPredBelow] "added {ctx.belowNames}" ctx.belowNames.forM Lean.mkCasesOn for i in [:ctx.typeInfos.size] do try let decl ← IndPredBelow.mkBrecOnDecl ctx i addDecl decl catch e => trace[Meta.IndPredBelow] "failed to prove brecOn for {ctx.belowNames[i]}\n{e.toMessageData}" else trace[Meta.IndPredBelow] "Not recursive" else trace[Meta.IndPredBelow] "Not inductive predicate" builtin_initialize registerTraceClass `Meta.IndPredBelow registerTraceClass `Meta.IndPredBelow.match end Lean.Meta.IndPredBelow
172220186433955b250c1a341ec7958fa37db195
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sites/pretopology.lean
85c835126e84c4e5be6cba437c2990eca3a82014
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,592
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.grothendieck /-! # Grothendieck pretopologies > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Definition and lemmas about Grothendieck pretopologies. A Grothendieck pretopology for a category `C` is a set of families of morphisms with fixed codomain, satisfying certain closure conditions. We show that a pretopology generates a genuine Grothendieck topology, and every topology has a maximal pretopology which generates it. The pretopology associated to a topological space is defined in `spaces.lean`. ## Tags coverage, pretopology, site ## References * [nLab, *Grothendieck pretopology*](https://ncatlab.org/nlab/show/Grothendieck+pretopology) * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * [Stacks, *00VG*](https://stacks.math.columbia.edu/tag/00VG) -/ universes v u noncomputable theory namespace category_theory open category_theory category limits presieve variables {C : Type u} [category.{v} C] [has_pullbacks C] variables (C) /-- A (Grothendieck) pretopology on `C` consists of a collection of families of morphisms with a fixed target `X` for every object `X` in `C`, called "coverings" of `X`, which satisfies the following three axioms: 1. Every family consisting of a single isomorphism is a covering family. 2. The collection of covering families is stable under pullback. 3. Given a covering family, and a covering family on each domain of the former, the composition is a covering family. In some sense, a pretopology can be seen as Grothendieck topology with weaker saturation conditions, in that each covering is not necessarily downward closed. See: https://ncatlab.org/nlab/show/Grothendieck+pretopology, or https://stacks.math.columbia.edu/tag/00VH, or [MM92] Chapter III, Section 2, Definition 2. Note that Stacks calls a category together with a pretopology a site, and [MM92] calls this a basis for a topology. -/ @[ext] structure pretopology := (coverings : Π (X : C), set (presieve X)) (has_isos : ∀ ⦃X Y⦄ (f : Y ⟶ X) [is_iso f], presieve.singleton f ∈ coverings X) (pullbacks : ∀ ⦃X Y⦄ (f : Y ⟶ X) S, S ∈ coverings X → pullback_arrows f S ∈ coverings Y) (transitive : ∀ ⦃X : C⦄ (S : presieve X) (Ti : Π ⦃Y⦄ (f : Y ⟶ X), S f → presieve Y), S ∈ coverings X → (∀ ⦃Y⦄ f (H : S f), Ti f H ∈ coverings Y) → S.bind Ti ∈ coverings X) namespace pretopology instance : has_coe_to_fun (pretopology C) (λ _, Π X : C, set (presieve X)) := ⟨coverings⟩ variable {C} instance : has_le (pretopology C) := { le := λ K₁ K₂, (K₁ : Π (X : C), set (presieve X)) ≤ K₂ } lemma le_def {K₁ K₂ : pretopology C} : K₁ ≤ K₂ ↔ (K₁ : Π (X : C), set (presieve X)) ≤ K₂ := iff.rfl variable (C) instance : partial_order (pretopology C) := { le_refl := λ K, le_def.mpr le_rfl, le_trans := λ K₁ K₂ K₃ h₁₂ h₂₃, le_def.mpr (le_trans h₁₂ h₂₃), le_antisymm := λ K₁ K₂ h₁₂ h₂₁, pretopology.ext _ _ (le_antisymm h₁₂ h₂₁), ..pretopology.has_le } instance : order_top (pretopology C) := { top := { coverings := λ _, set.univ, has_isos := λ _ _ _ _, set.mem_univ _, pullbacks := λ _ _ _ _ _, set.mem_univ _, transitive := λ _ _ _ _ _, set.mem_univ _ }, le_top := λ K X S hS, set.mem_univ _ } instance : inhabited (pretopology C) := ⟨⊤⟩ /-- A pretopology `K` can be completed to a Grothendieck topology `J` by declaring a sieve to be `J`-covering if it contains a family in `K`. See <https://stacks.math.columbia.edu/tag/00ZC>, or [MM92] Chapter III, Section 2, Equation (2). -/ def to_grothendieck (K : pretopology C) : grothendieck_topology C := { sieves := λ X S, ∃ R ∈ K X, R ≤ (S : presieve _), top_mem' := λ X, ⟨presieve.singleton (𝟙 _), K.has_isos _, λ _ _ _, ⟨⟩⟩, pullback_stable' := λ X Y S g, begin rintro ⟨R, hR, RS⟩, refine ⟨_, K.pullbacks g _ hR, _⟩, rw [← sieve.sets_iff_generate, sieve.pullback_arrows_comm], apply sieve.pullback_monotone, rwa sieve.gi_generate.gc, end, transitive' := begin rintro X S ⟨R', hR', RS⟩ R t, choose t₁ t₂ t₃ using t, refine ⟨_, K.transitive _ _ hR' (λ _ f hf, t₂ (RS _ hf)), _⟩, rintro Y _ ⟨Z, g, f, hg, hf, rfl⟩, apply t₃ (RS _ hg) _ hf, end } lemma mem_to_grothendieck (K : pretopology C) (X S) : S ∈ to_grothendieck C K X ↔ ∃ R ∈ K X, R ≤ (S : presieve X) := iff.rfl /-- The largest pretopology generating the given Grothendieck topology. See [MM92] Chapter III, Section 2, Equations (3,4). -/ def of_grothendieck (J : grothendieck_topology C) : pretopology C := { coverings := λ X R, sieve.generate R ∈ J X, has_isos := λ X Y f i, by exactI J.covering_of_eq_top (by simp), pullbacks := λ X Y f R hR, begin rw [set.mem_def, sieve.pullback_arrows_comm], apply J.pullback_stable f hR, end, transitive := λ X S Ti hS hTi, begin apply J.transitive hS, intros Y f, rintros ⟨Z, g, f, hf, rfl⟩, rw sieve.pullback_comp, apply J.pullback_stable g, apply J.superset_covering _ (hTi _ hf), rintro Y g ⟨W, h, g, hg, rfl⟩, exact ⟨_, h, _, ⟨_, _, _, hf, hg, rfl⟩, by simp⟩, end } /-- We have a galois insertion from pretopologies to Grothendieck topologies. -/ def gi : galois_insertion (to_grothendieck C) (of_grothendieck C) := { gc := λ K J, begin split, { intros h X R hR, exact h _ ⟨_, hR, sieve.le_generate R⟩ }, { rintro h X S ⟨R, hR, RS⟩, apply J.superset_covering _ (h _ hR), rwa sieve.gi_generate.gc } end, le_l_u := λ J X S hS, ⟨S, J.superset_covering S.le_generate hS, le_rfl⟩, choice := λ x hx, to_grothendieck C x, choice_eq := λ _ _, rfl } /-- The trivial pretopology, in which the coverings are exactly singleton isomorphisms. This topology is also known as the indiscrete, coarse, or chaotic topology. See <https://stacks.math.columbia.edu/tag/07GE> -/ def trivial : pretopology C := { coverings := λ X S, ∃ Y (f : Y ⟶ X) (h : is_iso f), S = presieve.singleton f, has_isos := λ X Y f i, ⟨_, _, i, rfl⟩, pullbacks := λ X Y f S, begin rintro ⟨Z, g, i, rfl⟩, refine ⟨pullback g f, pullback.snd, _, _⟩, { resetI, refine ⟨⟨pullback.lift (f ≫ inv g) (𝟙 _) (by simp), ⟨_, by tidy⟩⟩⟩, apply pullback.hom_ext, { rw [assoc, pullback.lift_fst, ←pullback.condition_assoc], simp }, { simp } }, { apply pullback_singleton }, end, transitive := begin rintro X S Ti ⟨Z, g, i, rfl⟩ hS, rcases hS g (singleton_self g) with ⟨Y, f, i, hTi⟩, refine ⟨_, f ≫ g, _, _⟩, { resetI, apply_instance }, ext W k, split, { rintro ⟨V, h, k, ⟨_⟩, hh, rfl⟩, rw hTi at hh, cases hh, apply singleton.mk }, { rintro ⟨_⟩, refine bind_comp g presieve.singleton.mk _, rw hTi, apply presieve.singleton.mk } end } instance : order_bot (pretopology C) := { bot := trivial C, bot_le := λ K X R, begin rintro ⟨Y, f, hf, rfl⟩, exactI K.has_isos f, end } /-- The trivial pretopology induces the trivial grothendieck topology. -/ lemma to_grothendieck_bot : to_grothendieck C ⊥ = ⊥ := (gi C).gc.l_bot end pretopology end category_theory
f3768e0c7f0acc7d4b25a1d0981eb35d2346f940
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level10.lean
27543a88e2e5d434f744ef5c9d90984d79ddb456
[ "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
865
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- #Calculating ## Level 10: Multiple rewrites We now introduce some useful features of Lean. First, multiple rewrite commands can be carried out with a single command, by listing the relevant identities within square brackets. The command we want is `rw [h', ←mul_assoc, h, mul_assoc]`. -/ /- Lemma : no-side-bar For all natural numbers $a$, we have $$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$ -/ lemma example10 (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', ←mul_assoc, h, mul_assoc] end /- You still see the incremental progress by placing the cursor after a comma in any list of rewrites. -/ end calculating -- hide
3555f14c887cb3895c3d031b6c9fc91b901b4f59
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/override_on_equations.lean
1f1e5241d5e4ec90808204dee3d096116418e807
[ "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
348
lean
open nat inductive expr := | zero : expr | one : expr | add : expr → expr → expr namespace expr infix `+` := expr.add set_option pp.notation false definition ev : expr → nat | zero := 0 | one := 1 | #expr (a + b) := ev a + ev b definition foo : expr := add zero (add one one) example : ev foo = 2 := rfl end expr
8dabea5682bc1708ac57c96f6a645e6c4bdb794c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/completionPrefixIssue.lean
e4c48804373376c67826ad19039ffa3f790e7b06
[ "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
210
lean
def veryLongDefinitionNameVeryLongDefinitionName := 1 def test (veryLongDefinitionName : Nat) := veryLongDefinitionName --^ textDocument/completion
81d69c0c57cb80afe656616e7139013887500111
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/group_theory/quotient_group.lean
1e9de543767f38446b9bab8ba34ed46f7e002e68
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
3,667
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset universes u v variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H] namespace quotient_group instance : group (quotient N) := { one := (1 : G), mul := λ a b, quotient.lift_on₂' a b (λ a b, ((a * b : G) : quotient N)) (λ a₁ a₂ b₁ b₂ hab₁ hab₂, quot.sound ((is_subgroup.mul_mem_cancel_left N (is_subgroup.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃' a b c (λ a b c, congr_arg mk (mul_assoc a b c)), one_mul := λ a, quotient.induction_on' a (λ a, congr_arg mk (one_mul a)), mul_one := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_one a)), inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N)) (λ a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_left_inv a)) } instance : is_group_hom (mk : G → quotient N) := ⟨λ _ _, rfl⟩ instance {G : Type*} [comm_group G] (s : set G) [is_subgroup s] : comm_group (quotient s) := { mul_comm := λ a b, quotient.induction_on₂' a b (λ a b, congr_arg mk (mul_comm a b)), ..@quotient_group.group _ _ s (normal_subgroup_of_comm_group s) } @[simp] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl @[simp] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl @[simp] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.pow _ _ _ _ mk _ a n @[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.gpow _ _ _ _ mk _ a n local notation ` Q ` := quotient N instance is_group_hom_quotient_group_mk : is_group_hom (mk : G → Q) := by refine {..}; intros; refl def lift (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (q : Q) : H := q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : by simp ... = φ a * φ (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab ... = φ (a * (a⁻¹ * b)) : by rw is_group_hom.mul φ a (a⁻¹ * b) ... = φ b : by simp) @[simp] lemma lift_mk {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (g : Q) = φ g := rfl @[simp] lemma lift_mk' {φ : G → H} [is_group_hom φ] (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk g : Q) = φ g := rfl variables (φ : G → H) [is_group_hom φ] (HN : ∀x∈N, φ x = 1) instance is_group_hom_quotient_lift : is_group_hom (lift N φ HN) := ⟨λ q r, quotient.induction_on₂' q r $ λ a b, show φ (a * b) = φ a * φ b, from is_group_hom.mul φ a b⟩ open function is_group_hom lemma injective_ker_lift : injective (lift (ker φ) φ $ λ x h, (mem_ker φ).1 h) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker φ, is_group_hom.mul φ, ← h, is_group_hom.inv φ, inv_mul_self] end quotient_group
bc4580bb9971eafeb2097d44a156f122e956e330
b3c7090f393c11bd47c82d2f8bb4edf8213173f5
/src/slice_lattice.lean
f4d5a98ac3dc46017f18cbe839f70e576e5e84dd
[]
no_license
ImperialCollegeLondon/lean-groups
964b197478f0313d826073576a3e0ae8b166a584
9a82d2a66ef7f549107fcb4e1504d734c43ebb33
refs/heads/master
1,592,371,184,330
1,567,197,270,000
1,567,197,270,000
195,810,480
4
0
null
null
null
null
UTF-8
Lean
false
false
2,456
lean
import order.complete_lattice open lattice example {α : Type*} [partial_order α] (b : α) : partial_order {x // b ≤ x} := by apply_instance -- why is subtype.ext an iff? instance slice.semilattice_sup {α : Type*} [semilattice_sup α] (b : α) : semilattice_sup {x // b ≤ x} := { sup := λ x y, ⟨x.val ⊔ y.val, le_sup_left_of_le x.2⟩, le_sup_left := λ _ _, le_sup_left, le_sup_right := λ _ _, le_sup_right, sup_le := λ _ _ _, sup_le, ..subtype.partial_order _} instance slice.semilattice_inf {α : Type*} [semilattice_inf α] (b : α) : semilattice_inf {x // b ≤ x} := { inf := λ x y, ⟨x.val ⊓ y.val, le_inf x.2 y.2⟩, inf_le_left := λ _ _, inf_le_left, inf_le_right := λ _ _, inf_le_right, le_inf := λ _ _ _, le_inf, ..subtype.partial_order _} instance slice.lattice {α : Type*} [lattice α] (b : α) : lattice {x // b ≤ x} := { ..slice.semilattice_inf b, ..slice.semilattice_sup b} instance slice.order_top {α : Type*} [order_top α] (b : α) : order_top {x // b ≤ x} := { top := ⟨⊤, le_top⟩, le_top := λ _, le_top, ..subtype.partial_order _ } instance slice.order_bot {α : Type*} [partial_order α] (b : α) : order_bot {x // b ≤ x} := { bot := ⟨b, le_refl b⟩, bot_le := subtype.property, ..subtype.partial_order _ } instance slice.bounded_lattice {α : Type*} [bounded_lattice α] (b : α) : bounded_lattice {x // b ≤ x} := { ..slice.order_top b, ..slice.order_bot b, ..slice.lattice b} instance slice.has_Sup {α : Type*} [complete_lattice α] (b : α) : has_Sup {x // b ≤ x} := ⟨λ X, ⟨Sup $ set.insert b (set.image subtype.val X), le_Sup $ set.mem_insert b _⟩⟩ instance slice.has_Inf {α : Type*} [complete_lattice α] (b : α) : has_Inf {x // b ≤ x} := ⟨λ X, ⟨Inf $ set.image subtype.val X, le_Inf $ by {rintro _ ⟨y, _, rfl⟩, exact y.2}⟩⟩ instance slice.complete_lattice {α : Type*} [complete_lattice α] (b : α) : complete_lattice {x // b ≤ x} := { le_Sup := λ X y h, le_Sup $ set.mem_insert_of_mem _ ⟨y, h, rfl⟩, Sup_le := λ X y h, Sup_le $ λ x h2, begin change x ∈ insert b _ at h2, rw set.mem_insert_iff at h2, rcases h2 with ⟨rfl, h2⟩, exact y.2, rcases h2 with ⟨_, h2, rfl⟩, exact h _ h2, end, Inf_le := λ X y h, Inf_le ⟨y, h, rfl⟩, le_Inf := λ X y h, le_Inf $ by {rintro _ ⟨x, hx, rfl⟩, exact h _ hx}, ..slice.bounded_lattice b, ..slice.has_Sup b, ..slice.has_Inf b }
996ac57cf4cf16e9014f096652e2bb296178d8c8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/pi_nat.lean
0a7287c0e7b4fb72baf1135249f67fa804341e64
[ "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
41,429
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import tactic.ring_exp import topology.metric_space.hausdorff_distance /-! # Topological study of spaces `Π (n : ℕ), E n` When `E n` are topological spaces, the space `Π (n : ℕ), E n` is naturally a topological space (with the product topology). When `E n` are uniform spaces, it also inherits a uniform structure. However, it does not inherit a canonical metric space structure of the `E n`. Nevertheless, one can put a noncanonical metric space structure (or rather, several of them). This is done in this file. ## Main definitions and results One can define a combinatorial distance on `Π (n : ℕ), E n`, as follows: * `pi_nat.cylinder x n` is the set of points `y` with `x i = y i` for `i < n`. * `pi_nat.first_diff x y` is the first index at which `x i ≠ y i`. * `pi_nat.dist x y` is equal to `(1/2) ^ (first_diff x y)`. It defines a distance on `Π (n : ℕ), E n`, compatible with the topology when the `E n` have the discrete topology. * `pi_nat.metric_space`: the metric space structure, given by this distance. Not registered as an instance. This space is a complete metric space. * `pi_nat.metric_space_of_discrete_uniformity`: the same metric space structure, but adjusting the uniformity defeqness when the `E n` already have the discrete uniformity. Not registered as an instance * `pi_nat.metric_space_nat_nat`: the particular case of `ℕ → ℕ`, not registered as an instance. These results are used to construct continuous functions on `Π n, E n`: * `pi_nat.exists_retraction_of_is_closed`: given a nonempty closed subset `s` of `Π (n : ℕ), E n`, there exists a retraction onto `s`, i.e., a continuous map from the whole space to `s` restricting to the identity on `s`. * `exists_nat_nat_continuous_surjective_of_complete_space`: given any nonempty complete metric space with second-countable topology, there exists a continuous surjection from `ℕ → ℕ` onto this space. One can also put distances on `Π (i : ι), E i` when the spaces `E i` are metric spaces (not discrete in general), and `ι` is countable. * `pi_countable.dist` is the distance on `Π i, E i` given by `dist x y = ∑' i, min (1/2)^(encode i) (dist (x i) (y i))`. * `pi_countable.metric_space` is the corresponding metric space structure, adjusted so that the uniformity is definitionally the product uniformity. Not registered as an instance. -/ noncomputable theory open_locale classical topological_space filter open topological_space set metric filter function local attribute [simp] pow_le_pow_iff one_lt_two inv_le_inv variable {E : ℕ → Type*} namespace pi_nat /-! ### The first_diff function -/ /-- In a product space `Π n, E n`, then `first_diff x y` is the first index at which `x` and `y` differ. If `x = y`, then by convention we set `first_diff x x = 0`. -/ @[irreducible, pp_nodot] def first_diff (x y : Π n, E n) : ℕ := if h : x ≠ y then nat.find (ne_iff.1 h) else 0 lemma apply_first_diff_ne {x y : Π n, E n} (h : x ≠ y) : x (first_diff x y) ≠ y (first_diff x y) := begin rw [first_diff, dif_pos h], exact nat.find_spec (ne_iff.1 h), end lemma apply_eq_of_lt_first_diff {x y : Π n, E n} {n : ℕ} (hn : n < first_diff x y) : x n = y n := begin rw first_diff at hn, split_ifs at hn, { convert nat.find_min (ne_iff.1 h) hn, simp }, { exact (not_lt_zero' hn).elim } end lemma first_diff_comm (x y : Π n, E n) : first_diff x y = first_diff y x := begin rcases eq_or_ne x y with rfl|hxy, { refl }, rcases lt_trichotomy (first_diff x y) (first_diff y x) with h|h|h, { exact (apply_first_diff_ne hxy (apply_eq_of_lt_first_diff h).symm).elim }, { exact h }, { exact (apply_first_diff_ne hxy.symm (apply_eq_of_lt_first_diff h).symm).elim } end lemma min_first_diff_le (x y z : Π n, E n) (h : x ≠ z) : min (first_diff x y) (first_diff y z) ≤ first_diff x z := begin by_contra' H, have : x (first_diff x z) = z (first_diff x z), from calc x (first_diff x z) = y (first_diff x z) : apply_eq_of_lt_first_diff (H.trans_le (min_le_left _ _)) ... = z ((first_diff x z)) : apply_eq_of_lt_first_diff (H.trans_le (min_le_right _ _)), exact (apply_first_diff_ne h this).elim, end /-! ### Cylinders -/ /-- In a product space `Π n, E n`, the cylinder set of length `n` around `x`, denoted `cylinder x n`, is the set of sequences `y` that coincide with `x` on the first `n` symbols, i.e., such that `y i = x i` for all `i < n`. -/ def cylinder (x : Π n, E n) (n : ℕ) : set (Π n, E n) := {y | ∀ i, i < n → y i = x i} lemma cylinder_eq_pi (x : Π n, E n) (n : ℕ) : cylinder x n = set.pi (finset.range n : set ℕ) (λ (i : ℕ), {x i}) := by { ext y, simp [cylinder] } @[simp] lemma cylinder_zero (x : Π n, E n) : cylinder x 0 = univ := by simp [cylinder_eq_pi] lemma cylinder_anti (x : Π n, E n) {m n : ℕ} (h : m ≤ n) : cylinder x n ⊆ cylinder x m := λ y hy i hi, hy i (hi.trans_le h) @[simp] lemma mem_cylinder_iff {x y : Π n, E n} {n : ℕ} : y ∈ cylinder x n ↔ ∀ i, i < n → y i = x i := iff.rfl lemma self_mem_cylinder (x : Π n, E n) (n : ℕ) : x ∈ cylinder x n := by simp lemma mem_cylinder_iff_eq {x y : Π n, E n} {n : ℕ} : y ∈ cylinder x n ↔ cylinder y n = cylinder x n := begin split, { assume hy, apply subset.antisymm, { assume z hz i hi, rw ← hy i hi, exact hz i hi }, { assume z hz i hi, rw hy i hi, exact hz i hi } }, { assume h, rw ← h, exact self_mem_cylinder _ _ } end lemma mem_cylinder_comm (x y : Π n, E n) (n : ℕ) : y ∈ cylinder x n ↔ x ∈ cylinder y n := by simp [mem_cylinder_iff_eq, eq_comm] lemma mem_cylinder_iff_le_first_diff {x y : Π n, E n} (hne : x ≠ y) (i : ℕ) : x ∈ cylinder y i ↔ i ≤ first_diff x y := begin split, { assume h, by_contra', exact apply_first_diff_ne hne (h _ this) }, { assume hi j hj, exact apply_eq_of_lt_first_diff (hj.trans_le hi) } end lemma mem_cylinder_first_diff (x y : Π n, E n) : x ∈ cylinder y (first_diff x y) := λ i hi, apply_eq_of_lt_first_diff hi lemma cylinder_eq_cylinder_of_le_first_diff (x y : Π n, E n) {n : ℕ} (hn : n ≤ first_diff x y) : cylinder x n = cylinder y n := begin rw ← mem_cylinder_iff_eq, assume i hi, exact apply_eq_of_lt_first_diff (hi.trans_le hn), end lemma Union_cylinder_update (x : Π n, E n) (n : ℕ) : (⋃ k, cylinder (update x n k) (n+1)) = cylinder x n := begin ext y, simp only [mem_cylinder_iff, mem_Union], split, { rintros ⟨k, hk⟩ i hi, simpa [hi.ne] using hk i (nat.lt_succ_of_lt hi) }, { assume H, refine ⟨y n, λ i hi, _⟩, rcases nat.lt_succ_iff_lt_or_eq.1 hi with h'i|rfl, { simp [H i h'i, h'i.ne] }, { simp } }, end lemma update_mem_cylinder (x : Π n, E n) (n : ℕ) (y : E n) : update x n y ∈ cylinder x n := mem_cylinder_iff.2 (λ i hi, by simp [hi.ne]) /-! ### A distance function on `Π n, E n` We define a distance function on `Π n, E n`, given by `dist x y = (1/2)^n` where `n` is the first index at which `x` and `y` differ. When each `E n` has the discrete topology, this distance will define the right topology on the product space. We do not record a global `has_dist` instance nor a `metric_space`instance, as other distances may be used on these spaces, but we register them as local instances in this section. -/ /-- The distance function on a product space `Π n, E n`, given by `dist x y = (1/2)^n` where `n` is the first index at which `x` and `y` differ. -/ protected def has_dist : has_dist (Π n, E n) := ⟨λ x y, if h : x ≠ y then (1/2 : ℝ) ^ (first_diff x y) else 0⟩ local attribute [instance] pi_nat.has_dist lemma dist_eq_of_ne {x y : Π n, E n} (h : x ≠ y) : dist x y = (1/2 : ℝ) ^ (first_diff x y) := by simp [dist, h] protected lemma dist_self (x : Π n, E n) : dist x x = 0 := by simp [dist] protected lemma dist_comm (x y : Π n, E n) : dist x y = dist y x := by simp [dist, @eq_comm _ x y, first_diff_comm] protected lemma dist_nonneg (x y : Π n, E n) : 0 ≤ dist x y := begin rcases eq_or_ne x y with rfl|h, { simp [dist] }, { simp [dist, h] } end lemma dist_triangle_nonarch (x y z : Π n, E n) : dist x z ≤ max (dist x y) (dist y z) := begin rcases eq_or_ne x z with rfl|hxz, { simp [pi_nat.dist_self x, pi_nat.dist_nonneg] }, rcases eq_or_ne x y with rfl|hxy, { simp }, rcases eq_or_ne y z with rfl|hyz, { simp }, simp only [dist_eq_of_ne, hxz, hxy, hyz, inv_le_inv, one_div, inv_pow, zero_lt_bit0, ne.def, not_false_iff, le_max_iff, zero_lt_one, pow_le_pow_iff, one_lt_two, pow_pos, min_le_iff.1 (min_first_diff_le x y z hxz)], end protected lemma dist_triangle (x y z : Π n, E n) : dist x z ≤ dist x y + dist y z := calc dist x z ≤ max (dist x y) (dist y z) : dist_triangle_nonarch x y z ... ≤ dist x y + dist y z : max_le_add_of_nonneg (pi_nat.dist_nonneg _ _) (pi_nat.dist_nonneg _ _) protected lemma eq_of_dist_eq_zero (x y : Π n, E n) (hxy : dist x y = 0) : x = y := begin rcases eq_or_ne x y with rfl|h, { refl }, simp [dist_eq_of_ne h] at hxy, exact (two_ne_zero (pow_eq_zero hxy)).elim end lemma mem_cylinder_iff_dist_le {x y : Π n, E n} {n : ℕ} : y ∈ cylinder x n ↔ dist y x ≤ (1/2)^n := begin rcases eq_or_ne y x with rfl|hne, { simp [pi_nat.dist_self] }, suffices : (∀ (i : ℕ), i < n → y i = x i) ↔ n ≤ first_diff y x, by simpa [dist_eq_of_ne hne], split, { assume hy, by_contra' H, exact apply_first_diff_ne hne (hy _ H) }, { assume h i hi, exact apply_eq_of_lt_first_diff (hi.trans_le h) } end lemma apply_eq_of_dist_lt {x y : Π n, E n} {n : ℕ} (h : dist x y < (1/2) ^ n) {i : ℕ} (hi : i ≤ n) : x i = y i := begin rcases eq_or_ne x y with rfl|hne, { refl }, have : n < first_diff x y, by simpa [dist_eq_of_ne hne, inv_lt_inv, pow_lt_pow_iff, one_lt_two] using h, exact apply_eq_of_lt_first_diff (hi.trans_lt this), end /-- A function to a pseudo-metric-space is `1`-Lipschitz if and only if points in the same cylinder of length `n` are sent to points within distance `(1/2)^n`. Not expressed using `lipschitz_with` as we don't have a metric space structure -/ lemma lipschitz_with_one_iff_forall_dist_image_le_of_mem_cylinder {α : Type*} [pseudo_metric_space α] {f : (Π n, E n) → α} : (∀ (x y : Π n, E n), dist (f x) (f y) ≤ dist x y) ↔ (∀ x y n, y ∈ cylinder x n → dist (f x) (f y) ≤ (1/2)^n) := begin split, { assume H x y n hxy, apply (H x y).trans, rw pi_nat.dist_comm, exact mem_cylinder_iff_dist_le.1 hxy }, { assume H x y, rcases eq_or_ne x y with rfl|hne, { simp [pi_nat.dist_nonneg] }, rw dist_eq_of_ne hne, apply H x y (first_diff x y), rw first_diff_comm, exact mem_cylinder_first_diff _ _ } end variables (E) [∀ n, topological_space (E n)] [∀ n, discrete_topology (E n)] lemma is_topological_basis_cylinders : is_topological_basis {s : set (Π n, E n) | ∃ (x : Π n, E n) (n : ℕ), s = cylinder x n} := begin apply is_topological_basis_of_open_of_nhds, { rintros u ⟨x, n, rfl⟩, rw cylinder_eq_pi, exact is_open_set_pi (finset.range n).finite_to_set (λ a ha, is_open_discrete _) }, { assume x u hx u_open, obtain ⟨v, ⟨U, F, hUF, rfl⟩, xU, Uu⟩ : ∃ (v : set (Π (i : ℕ), E i)) (H : v ∈ {S : set (Π (i : ℕ), E i) | ∃ (U : Π (i : ℕ), set (E i)) (F : finset ℕ), (∀ (i : ℕ), i ∈ F → U i ∈ {s : set (E i) | is_open s}) ∧ S = (F : set ℕ).pi U}), x ∈ v ∧ v ⊆ u := (is_topological_basis_pi (λ (n : ℕ), is_topological_basis_opens)).exists_subset_of_mem_open hx u_open, rcases finset.bdd_above F with ⟨n, hn⟩, refine ⟨cylinder x (n+1), ⟨x, n+1, rfl⟩, self_mem_cylinder _ _, subset.trans _ Uu⟩, assume y hy, suffices : ∀ (i : ℕ), i ∈ F → y i ∈ U i, by simpa, assume i hi, have : y i = x i := mem_cylinder_iff.1 hy i ((hn hi).trans_lt (lt_add_one n)), rw this, simp only [set.mem_pi, finset.mem_coe] at xU, exact xU i hi } end variable {E} lemma is_open_iff_dist (s : set (Π n, E n)) : is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s := begin split, { assume hs x hx, obtain ⟨v, ⟨y, n, rfl⟩, h'x, h's⟩ : ∃ (v : set (Π (n : ℕ), E n)) (H : v ∈ {s | ∃ (x : Π (n : ℕ), E n) (n : ℕ), s = cylinder x n}), x ∈ v ∧ v ⊆ s := (is_topological_basis_cylinders E).exists_subset_of_mem_open hx hs, rw ← mem_cylinder_iff_eq.1 h'x at h's, exact ⟨(1/2 : ℝ)^n, by simp, λ y hy, h's (λ i hi, (apply_eq_of_dist_lt hy hi.le).symm)⟩ }, { assume h, apply (is_topological_basis_cylinders E).is_open_iff.2 (λ x hx, _), rcases h x hx with ⟨ε, εpos, hε⟩, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2 : ℝ) ^ n < ε := exists_pow_lt_of_lt_one εpos one_half_lt_one, refine ⟨cylinder x n, ⟨x, n, rfl⟩, self_mem_cylinder x n, λ y hy, hε y _⟩, rw pi_nat.dist_comm, exact (mem_cylinder_iff_dist_le.1 hy).trans_lt hn } end /-- Metric space structure on `Π (n : ℕ), E n` when the spaces `E n` have the discrete topology, where the distance is given by `dist x y = (1/2)^n`, where `n` is the smallest index where `x` and `y` differ. Not registered as a global instance by default. Warning: this definition makes sure that the topology is defeq to the original product topology, but it does not take care of a possible uniformity. If the `E n` have a uniform structure, then there will be two non-defeq uniform structures on `Π n, E n`, the product one and the one coming from the metric structure. In this case, use `metric_space_of_discrete_uniformity` instead. -/ protected def metric_space : metric_space (Π n, E n) := metric_space.of_metrizable dist pi_nat.dist_self pi_nat.dist_comm pi_nat.dist_triangle is_open_iff_dist pi_nat.eq_of_dist_eq_zero /-- Metric space structure on `Π (n : ℕ), E n` when the spaces `E n` have the discrete uniformity, where the distance is given by `dist x y = (1/2)^n`, where `n` is the smallest index where `x` and `y` differ. Not registered as a global instance by default. -/ protected def metric_space_of_discrete_uniformity {E : ℕ → Type*} [∀ n, uniform_space (E n)] (h : ∀ n, uniformity (E n) = 𝓟 id_rel) : metric_space (Π n, E n) := begin haveI : ∀ n, discrete_topology (E n) := λ n, discrete_topology_of_discrete_uniformity (h n), exact { dist_triangle := pi_nat.dist_triangle, dist_comm := pi_nat.dist_comm, dist_self := pi_nat.dist_self, eq_of_dist_eq_zero := pi_nat.eq_of_dist_eq_zero, to_uniform_space := Pi.uniform_space _, uniformity_dist := begin simp [Pi.uniformity, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal, pseudo_metric_space.uniformity_dist, h, id_rel], apply le_antisymm, { simp only [le_infi_iff, le_principal_iff], assume ε εpos, obtain ⟨n, hn⟩ : ∃ n, (1/2 : ℝ)^n < ε := exists_pow_lt_of_lt_one εpos (by norm_num), apply @mem_infi_of_Inter _ _ _ _ _ (finset.range n).finite_to_set (λ i, {p : (Π (n : ℕ), E n) × Π (n : ℕ), E n | p.fst i = p.snd i}), { simp only [mem_principal, set_of_subset_set_of, imp_self, implies_true_iff] }, { rintros ⟨x, y⟩ hxy, simp only [finset.mem_coe, finset.mem_range, Inter_coe_set, mem_Inter, mem_set_of_eq] at hxy, apply lt_of_le_of_lt _ hn, rw [← mem_cylinder_iff_dist_le, mem_cylinder_iff], exact hxy } }, { simp only [le_infi_iff, le_principal_iff], assume n, refine mem_infi_of_mem ((1/2)^n) _, refine mem_infi_of_mem (by positivity) _, simp only [mem_principal, set_of_subset_set_of, prod.forall], assume x y hxy, exact apply_eq_of_dist_lt hxy le_rfl } end } end /-- Metric space structure on `ℕ → ℕ` where the distance is given by `dist x y = (1/2)^n`, where `n` is the smallest index where `x` and `y` differ. Not registered as a global instance by default. -/ def metric_space_nat_nat : metric_space (ℕ → ℕ) := pi_nat.metric_space_of_discrete_uniformity (λ n, rfl) local attribute [instance] pi_nat.metric_space protected lemma complete_space : complete_space (Π n, E n) := begin refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) (by simp) _, assume u hu, refine ⟨λ n, u n n, tendsto_pi_nhds.2 (λ i, _)⟩, refine tendsto_const_nhds.congr' _, filter_upwards [filter.Ici_mem_at_top i] with n hn, exact apply_eq_of_dist_lt (hu i i n le_rfl hn) le_rfl, end /-! ### Retractions inside product spaces We show that, in a space `Π (n : ℕ), E n` where each `E n` is discrete, there is a retraction on any closed nonempty subset `s`, i.e., a continuous map `f` from the whole space to `s` restricting to the identity on `s`. The map `f` is defined as follows. For `x ∈ s`, let `f x = x`. Otherwise, consider the longest prefix `w` that `x` shares with an element of `s`, and let `f x = z_w` where `z_w` is an element of `s` starting with `w`. -/ lemma exists_disjoint_cylinder {s : set (Π n, E n)} (hs : is_closed s) {x : Π n, E n} (hx : x ∉ s) : ∃ n, disjoint s (cylinder x n) := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne }, { exact ⟨0, by simp⟩ }, have A : 0 < inf_dist x s := (hs.not_mem_iff_inf_dist_pos hne).1 hx, obtain ⟨n, hn⟩ : ∃ n, (1/2 : ℝ)^n < inf_dist x s := exists_pow_lt_of_lt_one A (one_half_lt_one), refine ⟨n, _⟩, apply disjoint_left.2 (λ y ys hy, _), apply lt_irrefl (inf_dist x s), calc inf_dist x s ≤ dist x y : inf_dist_le_dist_of_mem ys ... ≤ (1/2)^n : by { rw mem_cylinder_comm at hy, exact mem_cylinder_iff_dist_le.1 hy } ... < inf_dist x s : hn end /-- Given a point `x` in a product space `Π (n : ℕ), E n`, and `s` a subset of this space, then `shortest_prefix_diff x s` if the smallest `n` for which there is no element of `s` having the same prefix of length `n` as `x`. If there is no such `n`, then use `0` by convention. -/ def shortest_prefix_diff {E : ℕ → Type*} (x : (Π n, E n)) (s : set (Π n, E n)) : ℕ := if h : ∃ n, disjoint s (cylinder x n) then nat.find h else 0 lemma first_diff_lt_shortest_prefix_diff {s : set (Π n, E n)} (hs : is_closed s) {x y : (Π n, E n)} (hx : x ∉ s) (hy : y ∈ s) : first_diff x y < shortest_prefix_diff x s := begin have A := exists_disjoint_cylinder hs hx, rw [shortest_prefix_diff, dif_pos A], have B := nat.find_spec A, contrapose! B, rw not_disjoint_iff_nonempty_inter, refine ⟨y, hy, _⟩, rw mem_cylinder_comm, exact cylinder_anti y B (mem_cylinder_first_diff x y) end lemma shortest_prefix_diff_pos {s : set (Π n, E n)} (hs : is_closed s) (hne : s.nonempty) {x : (Π n, E n)} (hx : x ∉ s) : 0 < shortest_prefix_diff x s := begin rcases hne with ⟨y, hy⟩, exact (zero_le _).trans_lt (first_diff_lt_shortest_prefix_diff hs hx hy) end /-- Given a point `x` in a product space `Π (n : ℕ), E n`, and `s` a subset of this space, then `longest_prefix x s` if the largest `n` for which there is an element of `s` having the same prefix of length `n` as `x`. If there is no such `n`, use `0` by convention. -/ def longest_prefix {E : ℕ → Type*} (x : (Π n, E n)) (s : set (Π n, E n)) : ℕ := shortest_prefix_diff x s - 1 lemma first_diff_le_longest_prefix {s : set (Π n, E n)} (hs : is_closed s) {x y : (Π n, E n)} (hx : x ∉ s) (hy : y ∈ s) : first_diff x y ≤ longest_prefix x s := begin rw [longest_prefix, le_tsub_iff_right], { exact first_diff_lt_shortest_prefix_diff hs hx hy }, { exact shortest_prefix_diff_pos hs ⟨y, hy⟩ hx } end lemma inter_cylinder_longest_prefix_nonempty {s : set (Π n, E n)} (hs : is_closed s) (hne : s.nonempty) (x : (Π n, E n)) : (s ∩ cylinder x (longest_prefix x s)).nonempty := begin by_cases hx : x ∈ s, { exact ⟨x, hx, self_mem_cylinder _ _⟩ }, have A := exists_disjoint_cylinder hs hx, have B : longest_prefix x s < shortest_prefix_diff x s := nat.pred_lt (shortest_prefix_diff_pos hs hne hx).ne', rw [longest_prefix, shortest_prefix_diff, dif_pos A] at B ⊢, obtain ⟨y, ys, hy⟩ : ∃ (y : Π (n : ℕ), E n), y ∈ s ∧ x ∈ cylinder y (nat.find A - 1), { have := nat.find_min A B, push_neg at this, simp_rw [not_disjoint_iff, mem_cylinder_comm] at this, exact this }, refine ⟨y, ys, _⟩, rw mem_cylinder_iff_eq at hy ⊢, rw hy end lemma disjoint_cylinder_of_longest_prefix_lt {s : set (Π n, E n)} (hs : is_closed s) {x : (Π n, E n)} (hx : x ∉ s) {n : ℕ} (hn : longest_prefix x s < n) : disjoint s (cylinder x n) := begin rcases eq_empty_or_nonempty s with h's|hne, { simp [h's] }, contrapose! hn, rcases not_disjoint_iff_nonempty_inter.1 hn with ⟨y, ys, hy⟩, apply le_trans _ (first_diff_le_longest_prefix hs hx ys), apply (mem_cylinder_iff_le_first_diff (ne_of_mem_of_not_mem ys hx).symm _).1, rwa mem_cylinder_comm, end /-- If two points `x, y` coincide up to length `n`, and the longest common prefix of `x` with `s` is strictly shorter than `n`, then the longest common prefix of `y` with `s` is the same, and both cylinders of this length based at `x` and `y` coincide. -/ lemma cylinder_longest_prefix_eq_of_longest_prefix_lt_first_diff {x y : Π n, E n} {s : set (Π n, E n)} (hs : is_closed s) (hne : s.nonempty) (H : longest_prefix x s < first_diff x y) (xs : x ∉ s) (ys : y ∉ s) : cylinder x (longest_prefix x s) = cylinder y (longest_prefix y s) := begin have l_eq : longest_prefix y s = longest_prefix x s, { rcases lt_trichotomy (longest_prefix y s) (longest_prefix x s) with L|L|L, { have Ax : (s ∩ cylinder x (longest_prefix x s)).nonempty := inter_cylinder_longest_prefix_nonempty hs hne x, have Z := disjoint_cylinder_of_longest_prefix_lt hs ys L, rw first_diff_comm at H, rw [cylinder_eq_cylinder_of_le_first_diff _ _ H.le] at Z, exact (Ax.not_disjoint Z).elim }, { exact L }, { have Ay : (s ∩ cylinder y (longest_prefix y s)).nonempty := inter_cylinder_longest_prefix_nonempty hs hne y, have A'y : (s ∩ cylinder y (longest_prefix x s).succ).nonempty := Ay.mono (inter_subset_inter_right s (cylinder_anti _ L)), have Z := disjoint_cylinder_of_longest_prefix_lt hs xs (nat.lt_succ_self _), rw cylinder_eq_cylinder_of_le_first_diff _ _ H at Z, exact (A'y.not_disjoint Z).elim } }, rw [l_eq, ← mem_cylinder_iff_eq], exact cylinder_anti y H.le (mem_cylinder_first_diff x y) end /-- Given a closed nonempty subset `s` of `Π (n : ℕ), E n`, there exists a Lipschitz retraction onto this set, i.e., a Lipschitz map with range equal to `s`, equal to the identity on `s`. -/ theorem exists_lipschitz_retraction_of_is_closed {s : set (Π n, E n)} (hs : is_closed s) (hne : s.nonempty) : ∃ f : (Π n, E n) → (Π n, E n), (∀ x ∈ s, f x = x) ∧ (range f = s) ∧ lipschitz_with 1 f := begin /- The map `f` is defined as follows. For `x ∈ s`, let `f x = x`. Otherwise, consider the longest prefix `w` that `x` shares with an element of `s`, and let `f x = z_w` where `z_w` is an element of `s` starting with `w`. All the desired properties are clear, except the fact that `f` is `1`-Lipschitz: if two points `x, y` belong to a common cylinder of length `n`, one should show that their images also belong to a common cylinder of length `n`. This is a case analysis: * if both `x, y ∈ s`, then this is clear. * if `x ∈ s` but `y ∉ s`, then the longest prefix `w` of `y` shared by an element of `s` is of length at least `n` (because of `x`), and then `f y` starts with `w` and therefore stays in the same length `n` cylinder. * if `x ∉ s`, `y ∉ s`, let `w` be the longest prefix of `x` shared by an element of `s`. If its length is `< n`, then it is also the longest prefix of `y`, and we get `f x = f y = z_w`. Otherwise, `f x` remains in the same `n`-cylinder as `x`. Similarly for `y`. Finally, `f x` and `f y` are again in the same `n`-cylinder, as desired. -/ set f := λ x, if x ∈ s then x else (inter_cylinder_longest_prefix_nonempty hs hne x).some with hf, have fs : ∀ x ∈ s, f x = x := λ x xs, by simp [xs], refine ⟨f, fs, _, _⟩, -- check that the range of `f` is `s`. { apply subset.antisymm, { rintros x ⟨y, rfl⟩, by_cases hy : y ∈ s, { rwa fs y hy }, simpa [hf, if_neg hy] using (inter_cylinder_longest_prefix_nonempty hs hne y).some_spec.1 }, { assume x hx, rw ← fs x hx, exact mem_range_self _ } }, -- check that `f` is `1`-Lipschitz, by a case analysis. { apply lipschitz_with.mk_one (λ x y, _), -- exclude the trivial cases where `x = y`, or `f x = f y`. rcases eq_or_ne x y with rfl|hxy, { simp }, rcases eq_or_ne (f x) (f y) with h'|hfxfy, { simp [h', dist_nonneg] }, have I2 : cylinder x (first_diff x y) = cylinder y (first_diff x y), { rw ← mem_cylinder_iff_eq, apply mem_cylinder_first_diff }, suffices : first_diff x y ≤ first_diff (f x) (f y), by simpa [dist_eq_of_ne hxy, dist_eq_of_ne hfxfy], -- case where `x ∈ s` by_cases xs : x ∈ s, { rw [fs x xs] at ⊢ hfxfy, -- case where `y ∈ s`, trivial by_cases ys : y ∈ s, { rw [fs y ys] }, -- case where `y ∉ s` have A : (s ∩ cylinder y (longest_prefix y s)).nonempty := inter_cylinder_longest_prefix_nonempty hs hne y, have fy : f y = A.some, by simp_rw [hf, if_neg ys], have I : cylinder A.some (first_diff x y) = cylinder y (first_diff x y), { rw [← mem_cylinder_iff_eq, first_diff_comm], apply cylinder_anti y _ A.some_spec.2, exact first_diff_le_longest_prefix hs ys xs }, rwa [← fy, ← I2, ← mem_cylinder_iff_eq, mem_cylinder_iff_le_first_diff hfxfy.symm, first_diff_comm _ x] at I }, -- case where `x ∉ s` { by_cases ys : y ∈ s, -- case where `y ∈ s` (similar to the above) { have A : (s ∩ cylinder x (longest_prefix x s)).nonempty := inter_cylinder_longest_prefix_nonempty hs hne x, have fx : f x = A.some, by simp_rw [hf, if_neg xs], have I : cylinder A.some (first_diff x y) = cylinder x (first_diff x y), { rw ← mem_cylinder_iff_eq, apply cylinder_anti x _ A.some_spec.2, apply first_diff_le_longest_prefix hs xs ys }, rw fs y ys at ⊢ hfxfy, rwa [← fx, I2, ← mem_cylinder_iff_eq, mem_cylinder_iff_le_first_diff hfxfy] at I }, -- case where `y ∉ s` { have Ax : (s ∩ cylinder x (longest_prefix x s)).nonempty := inter_cylinder_longest_prefix_nonempty hs hne x, have fx : f x = Ax.some, by simp_rw [hf, if_neg xs], have Ay : (s ∩ cylinder y (longest_prefix y s)).nonempty := inter_cylinder_longest_prefix_nonempty hs hne y, have fy : f y = Ay.some, by simp_rw [hf, if_neg ys], -- case where the common prefix to `x` and `s`, or `y` and `s`, is shorter than the -- common part to `x` and `y` -- then `f x = f y`. by_cases H : longest_prefix x s < first_diff x y ∨ longest_prefix y s < first_diff x y, { have : cylinder x (longest_prefix x s) = cylinder y (longest_prefix y s), { cases H, { exact cylinder_longest_prefix_eq_of_longest_prefix_lt_first_diff hs hne H xs ys }, { symmetry, rw first_diff_comm at H, exact cylinder_longest_prefix_eq_of_longest_prefix_lt_first_diff hs hne H ys xs } }, rw [fx, fy] at hfxfy, apply (hfxfy _).elim, congr' }, -- case where the common prefix to `x` and `s` is long, as well as the common prefix to -- `y` and `s`. Then all points remain in the same cylinders. { push_neg at H, have I1 : cylinder Ax.some (first_diff x y) = cylinder x (first_diff x y), { rw ← mem_cylinder_iff_eq, exact cylinder_anti x H.1 Ax.some_spec.2 }, have I3 : cylinder y (first_diff x y) = cylinder Ay.some (first_diff x y), { rw [eq_comm, ← mem_cylinder_iff_eq], exact cylinder_anti y H.2 Ay.some_spec.2 }, have : cylinder Ax.some (first_diff x y) = cylinder Ay.some (first_diff x y), by rw [I1, I2, I3], rw [← fx, ← fy, ← mem_cylinder_iff_eq, mem_cylinder_iff_le_first_diff hfxfy] at this, exact this } } } } end /-- Given a closed nonempty subset `s` of `Π (n : ℕ), E n`, there exists a retraction onto this set, i.e., a continuous map with range equal to `s`, equal to the identity on `s`. -/ theorem exists_retraction_of_is_closed {s : set (Π n, E n)} (hs : is_closed s) (hne : s.nonempty) : ∃ f : (Π n, E n) → (Π n, E n), (∀ x ∈ s, f x = x) ∧ (range f = s) ∧ continuous f := begin rcases exists_lipschitz_retraction_of_is_closed hs hne with ⟨f, fs, frange, hf⟩, exact ⟨f, fs, frange, hf.continuous⟩ end theorem exists_retraction_subtype_of_is_closed {s : set (Π n, E n)} (hs : is_closed s) (hne : s.nonempty) : ∃ f : (Π n, E n) → s, (∀ x : s, f x = x) ∧ surjective f ∧ continuous f := begin obtain ⟨f, fs, f_range, f_cont⟩ : ∃ f : (Π n, E n) → (Π n, E n), (∀ x ∈ s, f x = x) ∧ (range f = s) ∧ continuous f := exists_retraction_of_is_closed hs hne, have A : ∀ x, f x ∈ s, by simp [← f_range], have B : ∀ (x : s), cod_restrict f s A x = x, { assume x, apply subtype.coe_injective.eq_iff.1, simpa only using fs x.val x.property }, exact ⟨cod_restrict f s A, B, λ x, ⟨x, B x⟩, f_cont.subtype_mk _⟩, end end pi_nat open pi_nat /-- Any nonempty complete second countable metric space is the continuous image of the fundamental space `ℕ → ℕ`. For a version of this theorem in the context of Polish spaces, see `exists_nat_nat_continuous_surjective_of_polish_space`. -/ lemma exists_nat_nat_continuous_surjective_of_complete_space (α : Type*) [metric_space α] [complete_space α] [second_countable_topology α] [nonempty α] : ∃ (f : (ℕ → ℕ) → α), continuous f ∧ surjective f := begin /- First, we define a surjective map from a closed subset `s` of `ℕ → ℕ`. Then, we compose this map with a retraction of `ℕ → ℕ` onto `s` to obtain the desired map. Let us consider a dense sequence `u` in `α`. Then `s` is the set of sequences `xₙ` such that the balls `closed_ball (u xₙ) (1/2^n)` have a nonempty intersection. This set is closed, and we define `f x` there to be the unique point in the intersection. This function is continuous and surjective by design. -/ letI : metric_space (ℕ → ℕ) := pi_nat.metric_space_nat_nat, have I0 : (0 : ℝ) < 1/2, by norm_num, have I1 : (1/2 : ℝ) < 1, by norm_num, rcases exists_dense_seq α with ⟨u, hu⟩, let s : set (ℕ → ℕ) := {x | (⋂ (n : ℕ), closed_ball (u (x n)) ((1/2)^n)).nonempty}, let g : s → α := λ x, x.2.some, have A : ∀ (x : s) (n : ℕ), dist (g x) (u ((x : ℕ → ℕ) n)) ≤ (1/2)^n := λ x n, (mem_Inter.1 x.2.some_mem n : _), have g_cont : continuous g, { apply continuous_iff_continuous_at.2 (λ y, _), apply continuous_at_of_locally_lipschitz zero_lt_one 4 (λ x hxy, _), rcases eq_or_ne x y with rfl|hne, { simp }, have hne' : x.1 ≠ y.1 := subtype.coe_injective.ne hne, have dist' : dist x y = dist x.1 y.1 := rfl, let n := first_diff x.1 y.1 - 1, have diff_pos : 0 < first_diff x.1 y.1, { by_contra' h, apply apply_first_diff_ne hne', rw [le_zero_iff.1 h], apply apply_eq_of_dist_lt _ le_rfl, exact hxy }, have hn : first_diff x.1 y.1 = n + 1 := (nat.succ_pred_eq_of_pos diff_pos).symm, rw [dist', dist_eq_of_ne hne', hn], have B : x.1 n = y.1 n := mem_cylinder_first_diff x.1 y.1 n (nat.pred_lt diff_pos.ne'), calc dist (g x) (g y) ≤ dist (g x) (u (x.1 n)) + dist (g y) (u (x.1 n)) : dist_triangle_right _ _ _ ... = dist (g x) (u (x.1 n)) + dist (g y) (u (y.1 n)) : by rw ← B ... ≤ (1/2)^n + (1/2)^n : add_le_add (A x n) (A y n) ... = 4 * (1 / 2) ^ (n + 1) : by ring_exp }, have g_surj : surjective g, { assume y, have : ∀ (n : ℕ), ∃ j, y ∈ closed_ball (u j) ((1/2)^n), { assume n, rcases hu.exists_dist_lt y (by simp : (0 : ℝ) < (1/2)^n) with ⟨j, hj⟩, exact ⟨j, hj.le⟩ }, choose x hx using this, have I : (⋂ (n : ℕ), closed_ball (u (x n)) ((1 / 2) ^ n)).nonempty := ⟨y, mem_Inter.2 hx⟩, refine ⟨⟨x, I⟩, _⟩, refine dist_le_zero.1 _, have J : ∀ (n : ℕ), dist (g ⟨x, I⟩) y ≤ (1/2)^n + (1/2)^n := λ n, calc dist (g ⟨x, I⟩) y ≤ dist (g ⟨x, I⟩) (u (x n)) + dist y (u (x n)) : dist_triangle_right _ _ _ ... ≤ (1/2)^n + (1/2)^n : add_le_add (A ⟨x, I⟩ n) (hx n), have L : tendsto (λ (n : ℕ), (1/2 : ℝ)^n + (1/2)^n) at_top (𝓝 (0 + 0)) := (tendsto_pow_at_top_nhds_0_of_lt_1 I0.le I1).add (tendsto_pow_at_top_nhds_0_of_lt_1 I0.le I1), rw add_zero at L, exact ge_of_tendsto' L J }, have s_closed : is_closed s, { refine is_closed_iff_cluster_pt.mpr _, assume x hx, have L : tendsto (λ (n : ℕ), diam (closed_ball (u (x n)) ((1 / 2) ^ n))) at_top (𝓝 0), { have : tendsto (λ (n : ℕ), (2 : ℝ) * (1/2)^n) at_top (𝓝 (2 * 0)) := (tendsto_pow_at_top_nhds_0_of_lt_1 I0.le I1).const_mul _, rw mul_zero at this, exact squeeze_zero (λ n, diam_nonneg) (λ n, diam_closed_ball (pow_nonneg I0.le _)) this }, refine nonempty_Inter_of_nonempty_bInter (λ n, is_closed_ball) (λ n, bounded_closed_ball) _ L, assume N, obtain ⟨y, hxy, ys⟩ : ∃ y, y ∈ ball x ((1 / 2) ^ N) ∩ s := cluster_pt_principal_iff.1 hx _ (ball_mem_nhds x (pow_pos I0 N)), have E : (⋂ (n : ℕ) (H : n ≤ N), closed_ball (u (x n)) ((1 / 2) ^ n)) = ⋂ (n : ℕ) (H : n ≤ N), closed_ball (u (y n)) ((1 / 2) ^ n), { congr, ext1 n, congr, ext1 hn, have : x n = y n := apply_eq_of_dist_lt (mem_ball'.1 hxy) hn, rw this }, rw E, apply nonempty.mono _ ys, apply Inter_subset_Inter₂ }, obtain ⟨f, -, f_surj, f_cont⟩ : ∃ f : (ℕ → ℕ) → s, (∀ x : s, f x = x) ∧ surjective f ∧ continuous f, { apply exists_retraction_subtype_of_is_closed s_closed, simpa only [nonempty_coe_sort] using g_surj.nonempty }, exact ⟨g ∘ f, g_cont.comp f_cont, g_surj.comp f_surj⟩, end namespace pi_countable /-! ### Products of (possibly non-discrete) metric spaces -/ variables {ι : Type*} [encodable ι] {F : ι → Type*} [∀ i, metric_space (F i)] open encodable /-- Given a countable family of metric spaces, one may put a distance on their product `Π i, E i`. It is highly non-canonical, though, and therefore not registered as a global instance. The distance we use here is `dist x y = ∑' i, min (1/2)^(encode i) (dist (x i) (y i))`. -/ protected def has_dist : has_dist (Π i, F i) := ⟨λ x y, ∑' (i : ι), min ((1/2)^(encode i)) (dist (x i) (y i))⟩ local attribute [instance] pi_countable.has_dist lemma dist_eq_tsum (x y : Π i, F i) : dist x y = ∑' (i : ι), min ((1/2)^(encode i)) (dist (x i) (y i)) := rfl lemma dist_summable (x y : Π i, F i) : summable (λ (i : ι), min ((1/2)^(encode i)) (dist (x i) (y i))) := begin refine summable_of_nonneg_of_le (λ i, _) (λ i, min_le_left _ _) summable_geometric_two_encode, exact le_min (pow_nonneg (by norm_num) _) (dist_nonneg) end lemma min_dist_le_dist_pi (x y : Π i, F i) (i : ι) : min ((1/2)^(encode i)) (dist (x i) (y i)) ≤ dist x y := le_tsum (dist_summable x y) i (λ j hj, le_min (by simp) (dist_nonneg)) lemma dist_le_dist_pi_of_dist_lt {x y : Π i, F i} {i : ι} (h : dist x y < (1/2)^(encode i)) : dist (x i) (y i) ≤ dist x y := by simpa only [not_le.2 h, false_or] using min_le_iff.1 (min_dist_le_dist_pi x y i) open_locale big_operators topological_space open filter open_locale nnreal variable (E) /-- Given a countable family of metric spaces, one may put a distance on their product `Π i, E i`, defining the right topology and uniform structure. It is highly non-canonical, though, and therefore not registered as a global instance. The distance we use here is `dist x y = ∑' n, min (1/2)^(encode i) (dist (x n) (y n))`. -/ protected def metric_space : metric_space (Π i, F i) := { dist_self := λ x, by simp [dist_eq_tsum], dist_comm := λ x y, by simp [dist_eq_tsum, dist_comm], dist_triangle := λ x y z, begin have I : ∀ i, min ((1/2)^(encode i)) (dist (x i) (z i)) ≤ min ((1/2)^(encode i)) (dist (x i) (y i)) + min ((1/2)^(encode i)) (dist (y i) (z i)) := λ i, calc min ((1/2)^(encode i)) (dist (x i) (z i)) ≤ min ((1/2)^(encode i)) (dist (x i) (y i) + dist (y i) (z i)) : min_le_min le_rfl (dist_triangle _ _ _) ... = min ((1/2)^(encode i)) (min ((1/2)^(encode i)) (dist (x i) (y i)) + min ((1/2)^(encode i)) (dist (y i) (z i))) : begin convert congr_arg (coe : ℝ≥0 → ℝ) (min_add_distrib ((1/2 : ℝ≥0)^(encode i)) (nndist (x i) (y i)) (nndist (y i) (z i))); simp end ... ≤ min ((1/2)^(encode i)) (dist (x i) (y i)) + min ((1/2)^(encode i)) (dist (y i) (z i)) : min_le_right _ _, calc dist x z ≤ ∑' i, (min ((1/2)^(encode i)) (dist (x i) (y i)) + min ((1/2)^(encode i)) (dist (y i) (z i))) : tsum_le_tsum I (dist_summable x z) ((dist_summable x y).add (dist_summable y z)) ... = dist x y + dist y z : tsum_add (dist_summable x y) (dist_summable y z) end, eq_of_dist_eq_zero := begin assume x y hxy, ext1 n, rw [← dist_le_zero, ← hxy], apply dist_le_dist_pi_of_dist_lt, rw hxy, simp end, to_uniform_space := Pi.uniform_space _, uniformity_dist := begin have I0 : (0 : ℝ) ≤ 1/2, by norm_num, have I1 : (1/2 : ℝ) < 1, by norm_num, simp only [Pi.uniformity, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal, pseudo_metric_space.uniformity_dist], apply le_antisymm, { simp only [le_infi_iff, le_principal_iff], assume ε εpos, obtain ⟨K, hK⟩ : ∃ (K : finset ι), ∑' (i : {j // j ∉ K}), (1/2 : ℝ)^(encode (i : ι)) < ε/2 := ((tendsto_order.1 (tendsto_tsum_compl_at_top_zero (λ (i : ι), (1/2 : ℝ)^(encode i)))).2 _ (half_pos εpos)).exists, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ) (δpos : 0 < δ), (K.card : ℝ) * δ ≤ ε/2, { rcases nat.eq_zero_or_pos K.card with hK|hK, { exact ⟨1, zero_lt_one, by simpa only [hK, nat.cast_zero, zero_mul] using (half_pos εpos).le⟩ }, { have Kpos : 0 < (K.card : ℝ) := nat.cast_pos.2 hK, refine ⟨(ε / 2) / (K.card : ℝ), (div_pos (half_pos εpos) Kpos), le_of_eq _⟩, field_simp [Kpos.ne'], ring } }, apply @mem_infi_of_Inter _ _ _ _ _ K.finite_to_set (λ i, {p : (Π (i : ι), F i) × Π (i : ι), F i | dist (p.fst i) (p.snd i) < δ}), { rintros ⟨i, hi⟩, refine mem_infi_of_mem δ (mem_infi_of_mem δpos _), simp only [prod.forall, imp_self, mem_principal] }, { rintros ⟨x, y⟩ hxy, simp only [mem_Inter, mem_set_of_eq, set_coe.forall, finset.mem_range, finset.mem_coe] at hxy, calc dist x y = ∑' (i : ι), min ((1/2)^(encode i)) (dist (x i) (y i)) : rfl ... = ∑ i in K, min ((1/2)^(encode i)) (dist (x i) (y i)) + ∑' (i : (↑K : set ι)ᶜ), min ((1/2)^(encode (i : ι))) (dist (x i) (y i)) : (sum_add_tsum_compl (dist_summable _ _)).symm ... ≤ ∑ i in K, (dist (x i) (y i)) + ∑' (i : (↑K : set ι)ᶜ), (1/2)^(encode (i : ι)) : begin refine add_le_add (finset.sum_le_sum (λ i hi, min_le_right _ _)) _, refine tsum_le_tsum (λ i, min_le_left _ _) _ _, { apply summable.subtype (dist_summable x y) (↑K : set ι)ᶜ }, { apply summable.subtype summable_geometric_two_encode (↑K : set ι)ᶜ } end ... < (∑ i in K, δ) + ε / 2 : begin apply add_lt_add_of_le_of_lt _ hK, apply finset.sum_le_sum (λ i hi, _), apply (hxy i _).le, simpa using hi end ... ≤ ε / 2 + ε / 2 : add_le_add_right (by simpa only [finset.sum_const, nsmul_eq_mul] using hδ) _ ... = ε : add_halves _ } }, { simp only [le_infi_iff, le_principal_iff], assume i ε εpos, refine mem_infi_of_mem (min ((1/2)^(encode i)) ε) _, have : 0 < min ((1/2)^(encode i)) ε := lt_min (by simp) εpos, refine mem_infi_of_mem this _, simp only [and_imp, prod.forall, set_of_subset_set_of, lt_min_iff, mem_principal], assume x y hn hε, calc dist (x i) (y i) ≤ dist x y : dist_le_dist_pi_of_dist_lt hn ... < ε : hε } end } end pi_countable
2b40be572a7c1004511960c019b29a7679753ac8
4fa161becb8ce7378a709f5992a594764699e268
/src/number_theory/dioph.lean
291495d11b036caad3376799f5a767616ec30706
[ "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
36,372
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 number_theory.pell import data.pfun universe u open nat function namespace int lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 := begin refine iff.trans _ mul_eq_zero.symm, refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm, exact ⟨λe, by rw ← e; apply nat_abs_eq, λo, by cases o; subst x; simp [nat_abs_of_nat]⟩ end end int /-- An alternate definition of `fin n` defined as an inductive type instead of a subtype of `nat`. This is useful for its induction principle and different definitional equalities. -/ inductive fin2 : ℕ → Type | fz {n} : fin2 (succ n) | fs {n} : fin2 n → fin2 (succ n) namespace fin2 @[elab_as_eliminator] protected def cases' {n} {C : fin2 (succ n) → Sort u} (H1 : C fz) (H2 : Π n, C (fs n)) : Π (i : fin2 (succ n)), C i | fz := H1 | (fs n) := H2 n def elim0 {C : fin2 0 → Sort u} : Π (i : fin2 0), C i. /-- convert a `fin2` into a `nat` -/ def to_nat : Π {n}, fin2 n → ℕ | ._ (@fz n) := 0 | ._ (@fs n i) := succ (to_nat i) /-- convert a `nat` into a `fin2` if it is in range -/ def opt_of_nat : Π {n} (k : ℕ), option (fin2 n) | 0 _ := none | (succ n) 0 := some fz | (succ n) (succ k) := fs <$> @opt_of_nat n k /-- `i + k : fin2 (n + k)` when `i : fin2 n` and `k : ℕ` -/ def add {n} (i : fin2 n) : Π k, fin2 (n + k) | 0 := i | (succ k) := fs (add k) /-- `left k` is the embedding `fin2 n → fin2 (k + n)` -/ def left (k) : Π {n}, fin2 n → fin2 (k + n) | ._ (@fz n) := fz | ._ (@fs n i) := fs (left i) /-- `insert_perm a` is a permutation of `fin2 n` with the following properties: * `insert_perm a i = i+1` if `i < a` * `insert_perm a a = 0` * `insert_perm a i = i` if `i > a` -/ def insert_perm : Π {n}, fin2 n → fin2 n → fin2 n | ._ (@fz n) (@fz ._) := fz | ._ (@fz n) (@fs ._ j) := fs j | ._ (@fs (succ n) i) (@fz ._) := fs fz | ._ (@fs (succ n) i) (@fs ._ j) := match insert_perm i j with fz := fz | fs k := fs (fs k) end /-- `remap_left f k : fin2 (m + k) → fin2 (n + k)` applies the function `f : fin2 m → fin2 n` to inputs less than `m`, and leaves the right part on the right (that is, `remap_left f k (m + i) = n + i`). -/ def remap_left {m n} (f : fin2 m → fin2 n) : Π k, fin2 (m + k) → fin2 (n + k) | 0 i := f i | (succ k) (@fz ._) := fz | (succ k) (@fs ._ i) := fs (remap_left _ i) /-- This is a simple type class inference prover for proof obligations of the form `m < n` where `m n : ℕ`. -/ class is_lt (m n : ℕ) := (h : m < n) instance is_lt.zero (n) : is_lt 0 (succ n) := ⟨succ_pos _⟩ instance is_lt.succ (m n) [l : is_lt m n] : is_lt (succ m) (succ n) := ⟨succ_lt_succ l.h⟩ /-- Use type class inference to infer the boundedness proof, so that we can directly convert a `nat` into a `fin2 n`. This supports notation like `&1 : fin 3`. -/ def of_nat' : Π {n} m [is_lt m n], fin2 n | 0 m ⟨h⟩ := absurd h (not_lt_zero _) | (succ n) 0 ⟨h⟩ := fz | (succ n) (succ m) ⟨h⟩ := fs (@of_nat' n m ⟨lt_of_succ_lt_succ h⟩) local prefix `&`:max := of_nat' end fin2 open fin2 /-- Alternate definition of `vector` based on `fin2`. -/ def vector3 (α : Type u) (n : ℕ) : Type u := fin2 n → α namespace vector3 /-- The empty vector -/ @[pattern] def nil {α} : vector3 α 0. /-- The vector cons operation -/ @[pattern] def cons {α} {n} (a : α) (v : vector3 α n) : vector3 α (succ n) := λi, by {refine i.cases' _ _, exact a, exact v} /- We do not want to make the following notation global, because then these expressions will be overloaded, and only the expected type will be able to disambiguate the meaning. Worse: Lean will try to insert a coercion from `vector3 α _` to `list α`, if a list is expected. -/ localized "notation `[` l:(foldr `, ` (h t, vector3.cons h t) nil `]`) := l" in vector3 notation a :: b := cons a b @[simp] theorem cons_fz {α} {n} (a : α) (v : vector3 α n) : (a :: v) fz = a := rfl @[simp] theorem cons_fs {α} {n} (a : α) (v : vector3 α n) (i) : (a :: v) (fs i) = v i := rfl /-- Get the `i`th element of a vector -/ @[reducible] def nth {α} {n} (i : fin2 n) (v : vector3 α n) : α := v i /-- Construct a vector from a function on `fin2`. -/ @[reducible] def of_fn {α} {n} (f : fin2 n → α) : vector3 α n := f /-- Get the head of a nonempty vector. -/ def head {α} {n} (v : vector3 α (succ n)) : α := v fz /-- Get the tail of a nonempty vector. -/ def tail {α} {n} (v : vector3 α (succ n)) : vector3 α n := λi, v (fs i) theorem eq_nil {α} (v : vector3 α 0) : v = [] := funext $ λi, match i with end theorem cons_head_tail {α} {n} (v : vector3 α (succ n)) : head v :: tail v = v := funext $ λi, fin2.cases' rfl (λ_, rfl) i def nil_elim {α} {C : vector3 α 0 → Sort u} (H : C []) (v : vector3 α 0) : C v := by rw eq_nil v; apply H def cons_elim {α n} {C : vector3 α (succ n) → Sort u} (H : Π (a : α) (t : vector3 α n), C (a :: t)) (v : vector3 α (succ n)) : C v := by rw ← (cons_head_tail v); apply H @[simp] theorem cons_elim_cons {α n C H a t} : @cons_elim α n C H (a :: t) = H a t := rfl @[elab_as_eliminator] protected def rec_on {α} {C : Π {n}, vector3 α n → Sort u} {n} (v : vector3 α n) (H0 : C []) (Hs : Π {n} (a) (w : vector3 α n), C w → C (a :: w)) : C v := nat.rec_on n (λv, v.nil_elim H0) (λn IH v, v.cons_elim (λa t, Hs _ _ (IH _))) v @[simp] theorem rec_on_nil {α C H0 Hs} : @vector3.rec_on α @C 0 [] H0 @Hs = H0 := rfl @[simp] theorem rec_on_cons {α C H0 Hs n a v} : @vector3.rec_on α @C (succ n) (a :: v) H0 @Hs = Hs a v (@vector3.rec_on α @C n v H0 @Hs) := rfl /-- Append two vectors -/ def append {α} {m} (v : vector3 α m) {n} (w : vector3 α n) : vector3 α (n+m) := nat.rec_on m (λ_, w) (λm IH v, v.cons_elim $ λa t, @fin2.cases' (n+m) (λ_, α) a (IH t)) v local infix ` +-+ `:65 := vector3.append @[simp] theorem append_nil {α} {n} (w : vector3 α n) : [] +-+ w = w := rfl @[simp] theorem append_cons {α} (a : α) {m} (v : vector3 α m) {n} (w : vector3 α n) : (a::v) +-+ w = a :: (v +-+ w) := rfl @[simp] theorem append_left {α} : ∀ {m} (i : fin2 m) (v : vector3 α m) {n} (w : vector3 α n), (v +-+ w) (left n i) = v i | ._ (@fz m) v n w := v.cons_elim (λa t, by simp [*, left]) | ._ (@fs m i) v n w := v.cons_elim (λa t, by simp [*, left]) @[simp] theorem append_add {α} : ∀ {m} (v : vector3 α m) {n} (w : vector3 α n) (i : fin2 n), (v +-+ w) (add i m) = w i | 0 v n w i := rfl | (succ m) v n w i := v.cons_elim (λa t, by simp [*, add]) /-- Insert `a` into `v` at index `i`. -/ def insert {α} (a : α) {n} (v : vector3 α n) (i : fin2 (succ n)) : vector3 α (succ n) := λj, (a :: v) (insert_perm i j) @[simp] theorem insert_fz {α} (a : α) {n} (v : vector3 α n) : insert a v fz = a :: v := by refine funext (λj, j.cases' _ _); intros; refl @[simp] theorem insert_fs {α} (a : α) {n} (b : α) (v : vector3 α n) (i : fin2 (succ n)) : insert a (b :: v) (fs i) = b :: insert a v i := funext $ λj, by { refine j.cases' _ (λj, _); simp [insert, insert_perm], refine fin2.cases' _ _ (insert_perm i j); simp [insert_perm] } theorem append_insert {α} (a : α) {k} (t : vector3 α k) {n} (v : vector3 α n) (i : fin2 (succ n)) (e : succ n + k = succ (n + k)) : insert a (t +-+ v) (eq.rec_on e (i.add k)) = eq.rec_on e (t +-+ insert a v i) := begin refine vector3.rec_on t (λe, _) (λk b t IH e, _) e, refl, have e' := succ_add n k, change insert a (b :: (t +-+ v)) (eq.rec_on (congr_arg succ e') (fs (add i k))) = eq.rec_on (congr_arg succ e') (b :: (t +-+ insert a v i)), rw ← (eq.drec_on e' rfl : fs (eq.rec_on e' (i.add k) : fin2 (succ (n + k))) = eq.rec_on (congr_arg succ e') (fs (i.add k))), simp, rw IH, exact eq.drec_on e' rfl end end vector3 section vector3 open vector3 open_locale vector3 /-- "Curried" exists, i.e. ∃ x1 ... xn, f [x1, ..., xn] -/ def vector_ex {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∃x : α, vector_ex k (λv, f (x :: v)) /-- "Curried" forall, i.e. ∀ x1 ... xn, f [x1, ..., xn] -/ def vector_all {α} : Π k, (vector3 α k → Prop) → Prop | 0 f := f [] | (succ k) f := ∀x : α, vector_all k (λv, f (x :: v)) theorem exists_vector_zero {α} (f : vector3 α 0 → Prop) : Exists f ↔ f [] := ⟨λ⟨v, fv⟩, by rw ← (eq_nil v); exact fv, λf0, ⟨[], f0⟩⟩ theorem exists_vector_succ {α n} (f : vector3 α (succ n) → Prop) : Exists f ↔ ∃x v, f (x :: v) := ⟨λ⟨v, fv⟩, ⟨_, _, by rw cons_head_tail v; exact fv⟩, λ⟨x, v, fxv⟩, ⟨_, fxv⟩⟩ theorem vector_ex_iff_exists {α} : ∀ {n} (f : vector3 α n → Prop), vector_ex n f ↔ Exists f | 0 f := (exists_vector_zero f).symm | (succ n) f := iff.trans (exists_congr (λx, vector_ex_iff_exists _)) (exists_vector_succ f).symm theorem vector_all_iff_forall {α} : ∀ {n} (f : vector3 α n → Prop), vector_all n f ↔ ∀ v, f v | 0 f := ⟨λf0 v, v.nil_elim f0, λal, al []⟩ | (succ n) f := (forall_congr (λx, vector_all_iff_forall (λv, f (x :: v)))).trans ⟨λal v, v.cons_elim al, λal x v, al (x::v)⟩ /-- `vector_allp p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction, i.e. `vector_allp p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ def vector_allp {α} (p : α → Prop) {n} (v : vector3 α n) : Prop := vector3.rec_on v true (λn a v IH, @vector3.rec_on _ (λn v, Prop) _ v (p a) (λn b v' _, p a ∧ IH)) @[simp] theorem vector_allp_nil {α} (p : α → Prop) : vector_allp p [] = true := rfl @[simp] theorem vector_allp_singleton {α} (p : α → Prop) (x : α) : vector_allp p [x] = p x := rfl @[simp] theorem vector_allp_cons {α} (p : α → Prop) {n} (x : α) (v : vector3 α n) : vector_allp p (x :: v) ↔ p x ∧ vector_allp p v := vector3.rec_on v (and_true _).symm (λn a v IH, iff.rfl) theorem vector_allp_iff_forall {α} (p : α → Prop) {n} (v : vector3 α n) : vector_allp p v ↔ ∀ i, p (v i) := begin refine v.rec_on _ _, { exact ⟨λ_, fin2.elim0, λ_, trivial⟩ }, { simp, refine λn a v IH, (and_congr_right (λ_, IH)).trans ⟨λ⟨pa, h⟩ i, by {refine i.cases' _ _, exacts [pa, h]}, λh, ⟨_, λi, _⟩⟩, { have h0 := h fz, simp at h0, exact h0 }, { have hs := h (fs i), simp at hs, exact hs } } end theorem vector_allp.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) {n} {v : vector3 α n} (al : vector_allp p v) : vector_allp q v := (vector_allp_iff_forall _ _).2 (λi, h _ $ (vector_allp_iff_forall _ _).1 al _) end vector3 /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α} (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ list_all l @[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l | [] := (and_true _).symm | (x :: l) := iff.rfl theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ list.ball_nil _).symm | (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l | [] := id | (x :: l) := by simpa using and.imp (h x) list_all.imp @[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l := by induction l; simp * theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l := ⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩ instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) := decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λx : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λx : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x) /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section parameter {α : Type u} instance : has_coe_to_fun (poly α) := ⟨_, λ f, f.1⟩ /-- The underlying function of a `poly` is a polynomial -/ lemma isp (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ lemma ext {f g : poly α} (e : ∀x, f x = g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α := ⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩ @[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] theorem proj_eval (i x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] theorem const_eval (n x) : const n x = n := rfl /-- The zero polynomial -/ def zero : poly α := const 0 instance : has_zero (poly α) := ⟨poly.zero⟩ @[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl /-- The zero polynomial -/ def one : poly α := const 1 instance : has_one (poly α) := ⟨poly.one⟩ @[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl /-- Subtraction of polynomials -/ def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.sub pf pg⟩ instance : has_sub (poly α) := ⟨poly.sub⟩ @[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Negation of a polynomial -/ def neg (f : poly α) : poly α := 0 - f instance : has_neg (poly α) := ⟨poly.neg⟩ @[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x := show (0-f) x = _, by simp /-- Addition of polynomials -/ def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := subst (⟨f, pf⟩ - -⟨g, pg⟩) _ (λx, show f x - (0 - g x) = f x + g x, by simp) instance : has_add (poly α) := ⟨poly.add⟩ @[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Multiplication of polynomials -/ def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.mul pf pg⟩ instance : has_mul (poly α) := ⟨poly.mul⟩ @[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl instance : comm_ring (poly α) := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, .. }; {intros, exact ext (λx, by simp [mul_add, mul_left_comm, mul_comm, add_comm, add_assoc])} lemma induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l | [] := eq_self_iff_true _ | (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ(h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α β} (f : α → β) (g : poly α) : poly β := ⟨λv, g $ v ∘ f, g.induction (λi, by simp; apply is_poly.proj) (λn, by simp; apply is_poly.const) (λf g pf pg, by simp; apply is_poly.sub pf pg) (λf g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ := by {refine sum.rec _ _, exacts [f, g]} end sum local infixr ` ⊗ `:65 := sum.join open sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α β} (a : β) (v : α → β) : option α → β := by {refine option.rec _ _, exacts [a, v]} notation a :: b := cons a b @[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v := funext $ λo, by cases o; refl end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' := eq.rec d $ show S = S', from set.ext H theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S := ⟨ulift empty, p.remap inl, λv, (h v).trans ⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [ show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩, λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔ (∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) := begin simp, refine ⟨λt, _, λt, _⟩; cases t with t ht, { have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl), exact ⟨(0 :: t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λs, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 := ⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩ theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f)) | ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λs, by cases s with a b; refl⟩ theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λs, by cases s with a b; refl]; exact hm, by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λs, by cases s with a b; refl]; exact hq }⟩, λ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λs, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) := dioph_list_all [S, S'] ⟨d, d'⟩ theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v) | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt, (@mul_eq_zero_iff_eq_zero_or_eq_zero _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _, exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none)) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none) theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) := reindex_dioph d (functor.map g) theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x)) | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v)) | ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [ show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) := by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _); apply int.eq_nat_abs_iff_mul theorem proj_dioph (i : α) : dioph_fn (λv, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) := ext (ex1_dioph (and_dioph d df)) $ λv, ⟨λ⟨x, hS, (h: Exists _)⟩, by rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph (λv : α → ℕ, S (f v :: v)) := ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv, ⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩ end section variables {α β γ : Type} open vector3 open_locale vector3 theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) : dioph (λv : vector3 ℕ n, S (cons (f v) v)) := ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [ show option.cons (f v) v ∘ (cons none some) = f v :: v, from funext $ λs, by cases s with a b; refl] theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) := ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [ show (option.cons x v) ∘ (cons none some) = x :: v, from funext $ λs, by cases s with a b; refl] theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph (λv : α → ℕ, S (v ⊗ λi, f i v)) | 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv, by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b} | (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl, have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)), from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $ λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl}, have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)), from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λv, by rw [ show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v, from funext $ λs, by cases s with a b; refl] theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) := dioph_fn_compn (reindex_dioph d inr) df theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi, reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩ localized "notation x ` D∧ `:35 y := dioph.and_dioph x y" in dioph localized "notation x ` D∨ `:35 y := dioph.or_dioph x y" in dioph localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph localized "prefix `&`:max := of_nat'" in dioph theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) := proj_dioph &m localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) localized "prefix `D.`:100 := dioph.const_dioph" in dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λv, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λv, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) theorem eq_dioph : dioph (λv, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) localized "infix ` D= `:50 := dioph.eq_dioph" in dioph theorem add_dioph : dioph_fn (λv, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) localized "infix ` D+ `:80 := dioph.add_dioph" in dioph theorem mul_dioph : dioph_fn (λv, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) localized "infix ` D* `:90 := dioph.mul_dioph" in dioph theorem le_dioph : dioph (λv, f v ≤ g v) := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩) localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg localized "infix ` D< `:50 := dioph.lt_dioph" in dioph theorem ne_dioph : dioph (λv, f v ≠ g v) := ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph theorem sub_dioph : dioph_fn (λv, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λo, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, nat.add_sub_cancel] }, { rw [x0, nat.sub_eq_zero_of_le yz] } end, λh, begin subst x, cases le_total y z with yz zy, { exact or.inr ⟨yz, nat.sub_eq_zero_of_le yz⟩ }, { exact or.inl (nat.sub_add_cancel zy).symm }, end⟩ localized "infix ` D- `:80 := dioph.sub_dioph" in dioph theorem dvd_dioph : dioph (λv, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph theorem mod_dioph : dioph_fn (λv, f v % g v) := have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ localized "infix ` D% `:80 := dioph.mod_dioph" in dioph theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh localized "notation `D≡` := dioph.modeq_dioph" in dioph theorem div_dioph : dioph_fn (λv, f v / g v) := have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λy0, by rw [y0, nat.div_zero]; exact ⟨λo, (o.resolve_right $ λ⟨_, h2⟩, not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩) (λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm) localized "infix ` D/ `:80 := dioph.div_dioph" in dioph omit df dg open pell theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | 1 < v &0 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ 0 < w ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λv, matiyasevic.symm theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨1 < v &0, λh, xn h (v &1)⟩) := have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg theorem pow_dioph : dioph_fn (λv, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
7220fb19ca610c7fabf849fbd13819e99de08a45
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/array/basic.lean
e52b99c6d8046e94439a6c4dae8c5405b4772c55
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
4,460
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ prelude import init.data.nat universes u w structure array (α : Type u) (n : nat) := (data : fin n → α) def mk_array {α} (n) (v : α) : array α n := {data := λ _, v} namespace array variables {α : Type u} {β : Type w} {n : nat} def nil {α} : array α 0 := {data := λ ⟨x, h⟩, absurd h (nat.not_lt_zero x)} def read (a : array α n) (i : fin n) : α := a.data i def read' [inhabited α] (a : array α n) (i : nat) : α := if h : i < n then a.read ⟨i,h⟩ else default α def write (a : array α n) (i : fin n) (v : α) : array α n := {data := λ j, if i = j then v else a.read j} def write' (a : array α n) (i : nat) (v : α) : array α n := if h : i < n then a.write ⟨i, h⟩ v else a lemma read_eq_read' [inhabited α] (a : array α n) (i : nat) (h : i < n) : read a ⟨i, h⟩ = read' a i := by unfold read'; rw [dif_pos h] lemma write_eq_write' (a : array α n) (i : nat) (h : i < n) (v : α) : write a ⟨i, h⟩ v = write' a i v := by unfold write'; rw [dif_pos h] lemma push_back_idx {j n} (h₁ : j < n + 1) (h₂ : j ≠ n) : j < n := nat.lt_of_le_and_ne (nat.le_of_lt_succ h₁) h₂ def push_back (a : array α n) (v : α) : array α (n+1) := {data := λ ⟨j, h₁⟩, if h₂ : j = n then v else a.read ⟨j, push_back_idx h₁ h₂⟩} lemma pop_back_idx {j n} (h : j < n) : j < n + 1 := nat.lt.step h def pop_back (a : array α (n+1)) : array α n := {data := λ ⟨j, h⟩, a.read ⟨j, pop_back_idx h⟩} lemma lt_aux_1 {a b c : nat} (h : a + c < b) : a < b := lt_of_le_of_lt (nat.le_add_right a c) h lemma lt_aux_2 {n} (h : n > 0) : n - 1 < n := have h₁ : 1 > 0, from dec_trivial, nat.sub_lt h h₁ lemma lt_aux_3 {n i} (h : i + 1 < n) : n - 2 - i < n := have n > 0, from lt.trans (nat.zero_lt_succ i) h, have n - 2 < n, from nat.sub_lt this (dec_trivial), lt_of_le_of_lt (nat.sub_le _ _) this @[elab_as_eliminator] theorem write_ind (a : array α n) (i : fin n) (v : α) (C : fin n → α → Sort w) (Hi : C i v) (Hj : ∀j, i ≠ j → C j (a.read j)) (j) : C j ((a.write i v).read j) := show C j (if i = j then v else read a j), from if h : i = j then by rwa [if_pos h, ← h] else by rw [if_neg h]; exact Hj j h def iterate_aux (a : array α n) (f : fin n → α → β → β) : Π (i : nat), i ≤ n → β → β | 0 h b := b | (j+1) h b := let i : fin n := ⟨j, h⟩ in f i (a.read i) (iterate_aux j (le_of_lt h) b) def iterate (a : array α n) (b : β) (fn : fin n → α → β → β) : β := iterate_aux a fn n (le_refl _) b def foreach (a : array α n) (f : fin n → α → α) : array α n := iterate a a (λ i v a', a'.write i (f i v)) def map (f : α → α) (a : array α n) : array α n := foreach a (λ _, f) def map₂ (f : α → α → α) (a b : array α n) : array α n := foreach b (λ i, f (a.read i)) def foldl (a : array α n) (b : β) (f : α → β → β) : β := iterate a b (λ _, f) def rev_list (a : array α n) : list α := a.foldl [] (λ v l, v :: l) def foldl_eq_aux (a : array α n) (b : β) (f : α → β → β) : Π (i : nat) (h : i ≤ n), iterate_aux a (λ _, f) i h b = (iterate_aux a (λ _ v l, v :: l) i h []).foldr f b | 0 h := rfl | (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (foldl_eq_aux j _) def foldl_eq (a : array α n) (b : β) (f : α → β → β) : a.foldl b f = a.rev_list.foldr f b := foldl_eq_aux a b f _ _ def rev_iterate_aux (a : array α n) (f : fin n → α → β → β) : Π (i : nat), i ≤ n → β → β | 0 h b := b | (j+1) h b := let i : fin n := ⟨j, h⟩ in rev_iterate_aux j (le_of_lt h) (f i (a.read i) b) def rev_iterate (a : array α n) (b : β) (fn : fin n → α → β → β) : β := rev_iterate_aux a fn n (le_refl _) b def to_list (a : array α n) : list α := a.rev_iterate [] (λ _ v l, v :: l) protected def mem (v : α) (a : array α n) : Prop := ∃i, read a i = v instance : has_mem α (array α n) := ⟨array.mem⟩ theorem read_mem (a : array α n) (i) : read a i ∈ a := exists.intro i rfl instance [has_repr α] : has_repr (array α n) := ⟨repr ∘ to_list⟩ meta instance [has_to_format α] : has_to_format (array α n) := ⟨to_fmt ∘ to_list⟩ meta instance [has_to_tactic_format α] : has_to_tactic_format (array α n) := ⟨tactic.pp ∘ to_list⟩ end array
78f0c4e0dd299a16c7b3827e6a1b5b315b8b19fc
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/asymptotics/asymptotic_equivalent.lean
b7d397a74d148d52cb0940ba0f1c2d1c8b14a2f9
[ "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
11,407
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics.asymptotics import analysis.normed_space.ordered /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent l u v`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomain `β`. While the definition only requires `β` to be a `normed_add_comm_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent l u v`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_add_comm_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) ## Implementation Notes Note that `is_equivalent` takes the parameters `(l : filter α) (u v : α → β)` in that order. This is to enable `calc` support, as `calc` requires that the last two explicit arguments are `u v`. -/ namespace asymptotics open filter function open_locale topological_space section normed_add_comm_group variables {α β : Type*} [normed_add_comm_group β] /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent (l : filter α) (u v : α → β) := (u - v) =o[l] v localized "notation u ` ~[`:50 l:50 `] `:0 v:50 := asymptotics.is_equivalent l u v" in asymptotics variables {u v w : α → β} {l : filter α} lemma is_equivalent.is_o (h : u ~[l] v) : (u - v) =o[l] v := h lemma is_equivalent.is_O (h : u ~[l] v) : u =O[l] v := (is_O.congr_of_sub h.is_O.symm).mp (is_O_refl _ _) lemma is_equivalent.is_O_symm (h : u ~[l] v) : v =O[l] u := begin convert h.is_o.right_is_O_add, ext, simp end @[refl] lemma is_equivalent.refl : u ~[l] u := begin rw [is_equivalent, sub_self], exact is_o_zero _ _ end @[symm] lemma is_equivalent.symm (h : u ~[l] v) : v ~[l] u := (h.is_o.trans_is_O h.is_O_symm).symm @[trans] lemma is_equivalent.trans {l : filter α} {u v w : α → β} (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := (huv.is_o.trans_is_O hvw.is_O).triangle hvw.is_o lemma is_equivalent.congr_left {u v w : α → β} {l : filter α} (huv : u ~[l] v) (huw : u =ᶠ[l] w) : w ~[l] v := huv.congr' (huw.sub (eventually_eq.refl _ _)) (eventually_eq.refl _ _) lemma is_equivalent.congr_right {u v w : α → β} {l : filter α} (huv : u ~[l] v) (hvw : v =ᶠ[l] w) : u ~[l] w := (huv.symm.congr_left hvw).symm lemma is_equivalent_zero_iff_eventually_zero : u ~[l] 0 ↔ u =ᶠ[l] 0 := begin rw [is_equivalent, sub_zero], exact is_o_zero_right_iff end lemma is_equivalent_zero_iff_is_O_zero : u ~[l] 0 ↔ u =O[l] (0 : α → β) := begin refine ⟨is_equivalent.is_O, λ h, _⟩, rw [is_equivalent_zero_iff_eventually_zero, eventually_eq_iff_exists_mem], exact ⟨{x : α | u x = 0}, is_O_zero_right_iff.mp h, λ x hx, hx⟩, end lemma is_equivalent_const_iff_tendsto {c : β} (h : c ≠ 0) : u ~[l] const _ c ↔ tendsto u l (𝓝 c) := begin rw [is_equivalent, is_o_const_iff h], split; intro h; [ { have := h.sub tendsto_const_nhds, rw zero_sub (-c) at this }, { have := h.sub tendsto_const_nhds, rw ← sub_self c} ]; convert this; try { ext }; simp end lemma is_equivalent.tendsto_const {c : β} (hu : u ~[l] const _ c) : tendsto u l (𝓝 c) := begin rcases (em $ c = 0) with ⟨rfl, h⟩, { exact (tendsto_congr' $ is_equivalent_zero_iff_eventually_zero.mp hu).mpr tendsto_const_nhds }, { exact (is_equivalent_const_iff_tendsto h).mp hu } end lemma is_equivalent.tendsto_nhds {c : β} (huv : u ~[l] v) (hu : tendsto u l (𝓝 c)) : tendsto v l (𝓝 c) := begin by_cases h : c = 0, { subst c, rw ← is_o_one_iff ℝ at hu ⊢, simpa using (huv.symm.is_o.trans hu).add hu }, { rw ← is_equivalent_const_iff_tendsto h at hu ⊢, exact huv.symm.trans hu } end lemma is_equivalent.tendsto_nhds_iff {c : β} (huv : u ~[l] v) : tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c) := ⟨huv.tendsto_nhds, huv.symm.tendsto_nhds⟩ lemma is_equivalent.add_is_o (huv : u ~[l] v) (hwv : w =o[l] v) : (w + u) ~[l] v := by simpa only [is_equivalent, pi.sub_apply, add_sub] using hwv.add huv lemma is_o.add_is_equivalent (hu : u =o[l] w) (hv : v ~[l] w) : (u + v) ~[l] w := add_comm u v ▸ hv.add_is_o hu lemma is_o.is_equivalent (huv : (u - v) =o[l] v) : u ~[l] v := huv lemma is_equivalent.neg (huv : u ~[l] v) : (λ x, - u x) ~[l] (λ x, - v x) := begin rw is_equivalent, convert huv.is_o.neg_left.neg_right, ext, simp, end end normed_add_comm_group open_locale asymptotics section normed_field variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent_iff_exists_eq_mul : u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := begin rw [is_equivalent, is_o_iff_exists_eq_mul], split; rintros ⟨φ, hφ, h⟩; [use (φ + 1), use (φ - 1)]; split, { conv in (𝓝 _) { rw ← zero_add (1 : β) }, exact hφ.add (tendsto_const_nhds) }, { convert h.add (eventually_eq.refl l v); ext; simp [add_mul] }, { conv in (𝓝 _) { rw ← sub_self (1 : β) }, exact hφ.sub (tendsto_const_nhds) }, { convert h.sub (eventually_eq.refl l v); ext; simp [sub_mul] } end lemma is_equivalent.exists_eq_mul (huv : u ~[l] v) : ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := is_equivalent_iff_exists_eq_mul.mp huv lemma is_equivalent_of_tendsto_one (hz : ∀ᶠ x in l, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := begin rw is_equivalent_iff_exists_eq_mul, refine ⟨u/v, huv, hz.mono $ λ x hz', (div_mul_cancel_of_imp hz').symm⟩, end lemma is_equivalent_of_tendsto_one' (hz : ∀ x, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := is_equivalent_of_tendsto_one (eventually_of_forall hz) huv lemma is_equivalent_iff_tendsto_one (hz : ∀ᶠ x in l, v x ≠ 0) : u ~[l] v ↔ tendsto (u/v) l (𝓝 1) := begin split, { intro hequiv, have := hequiv.is_o.tendsto_div_nhds_zero, simp only [pi.sub_apply, sub_div] at this, have key : tendsto (λ x, v x / v x) l (𝓝 1), { exact (tendsto_congr' $ hz.mono $ λ x hnz, @div_self _ _ (v x) hnz).mpr tendsto_const_nhds }, convert this.add key, { ext, simp }, { norm_num } }, { exact is_equivalent_of_tendsto_one (hz.mono $ λ x hnvz hz, (hnvz hz).elim) } end end normed_field section smul lemma is_equivalent.smul {α E 𝕜 : Type*} [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] {a b : α → 𝕜} {u v : α → E} {l : filter α} (hab : a ~[l] b) (huv : u ~[l] v) : (λ x, a x • u x) ~[l] (λ x, b x • v x) := begin rcases hab.exists_eq_mul with ⟨φ, hφ, habφ⟩, have : (λ (x : α), a x • u x) - (λ (x : α), b x • v x) =ᶠ[l] λ x, b x • ((φ x • u x) - v x), { convert (habφ.comp₂ (•) $ eventually_eq.refl _ u).sub (eventually_eq.refl _ (λ x, b x • v x)), ext, rw [pi.mul_apply, mul_comm, mul_smul, ← smul_sub] }, refine (is_o_congr this.symm $ eventually_eq.rfl).mp ((is_O_refl b l).smul_is_o _), rcases huv.is_O.exists_pos with ⟨C, hC, hCuv⟩, rw is_equivalent at *, rw is_o_iff at *, rw is_O_with at hCuv, simp only [metric.tendsto_nhds, dist_eq_norm] at hφ, intros c hc, specialize hφ ((c/2)/C) (div_pos (by linarith) hC), specialize huv (show 0 < c/2, by linarith), refine hφ.mp (huv.mp $ hCuv.mono $ λ x hCuvx huvx hφx, _), have key := calc ∥φ x - 1∥ * ∥u x∥ ≤ (c/2) / C * ∥u x∥ : mul_le_mul_of_nonneg_right hφx.le (norm_nonneg $ u x) ... ≤ (c/2) / C * (C*∥v x∥) : mul_le_mul_of_nonneg_left hCuvx (div_pos (by linarith) hC).le ... = c/2 * ∥v x∥ : by {field_simp [hC.ne.symm], ring}, calc ∥((λ (x : α), φ x • u x) - v) x∥ = ∥(φ x - 1) • u x + (u x - v x)∥ : by simp [sub_smul, sub_add] ... ≤ ∥(φ x - 1) • u x∥ + ∥u x - v x∥ : norm_add_le _ _ ... = ∥φ x - 1∥ * ∥u x∥ + ∥u x - v x∥ : by rw norm_smul ... ≤ c / 2 * ∥v x∥ + ∥u x - v x∥ : add_le_add_right key _ ... ≤ c / 2 * ∥v x∥ + c / 2 * ∥v x∥ : add_le_add_left huvx _ ... = c * ∥v x∥ : by ring, end end smul section mul_inv variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent.mul (htu : t ~[l] u) (hvw : v ~[l] w) : t * v ~[l] u * w := htu.smul hvw lemma is_equivalent.inv (huv : u ~[l] v) : (λ x, (u x)⁻¹) ~[l] (λ x, (v x)⁻¹) := begin rw is_equivalent_iff_exists_eq_mul at *, rcases huv with ⟨φ, hφ, h⟩, rw ← inv_one, refine ⟨λ x, (φ x)⁻¹, tendsto.inv₀ hφ (by norm_num) , _⟩, convert h.inv, ext, simp [mul_inv] end lemma is_equivalent.div (htu : t ~[l] u) (hvw : v ~[l] w) : (λ x, t x / v x) ~[l] (λ x, u x / w x) := by simpa only [div_eq_mul_inv] using htu.mul hvw.inv end mul_inv section normed_linear_ordered_field variables {α β : Type*} [normed_linear_ordered_field β] {u v : α → β} {l : filter α} lemma is_equivalent.tendsto_at_top [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_top) : tendsto v l at_top := let ⟨φ, hφ, h⟩ := huv.symm.exists_eq_mul in tendsto.congr' h.symm ((mul_comm u φ) ▸ (hu.at_top_mul zero_lt_one hφ)) lemma is_equivalent.tendsto_at_top_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_top ↔ tendsto v l at_top := ⟨huv.tendsto_at_top, huv.symm.tendsto_at_top⟩ lemma is_equivalent.tendsto_at_bot [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_bot) : tendsto v l at_bot := begin convert tendsto_neg_at_top_at_bot.comp (huv.neg.tendsto_at_top $ tendsto_neg_at_bot_at_top.comp hu), ext, simp end lemma is_equivalent.tendsto_at_bot_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_bot ↔ tendsto v l at_bot := ⟨huv.tendsto_at_bot, huv.symm.tendsto_at_bot⟩ end normed_linear_ordered_field end asymptotics open filter asymptotics open_locale asymptotics variables {α β : Type*} [normed_add_comm_group β] lemma filter.eventually_eq.is_equivalent {u v : α → β} {l : filter α} (h : u =ᶠ[l] v) : u ~[l] v := is_equivalent.congr_right (is_o_refl_left _ _) h
f830ea68b910f21b8958d4ed86b97b045c5f9a23
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/e_closure.hlean
36c32f4757fafef00f3c9ded549525a607fa1920
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
10,833
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn The "equivalence closure" of a type-valued relation. A more appropriate intuition is the type of words formed from the relation, and inverses, concatenations and reflexivity -/ import algebra.relation eq2 arity cubical.pathover2 open eq equiv function inductive e_closure {A : Type} (R : A → A → Type) : A → A → Type := | of_rel : Π{a a'} (r : R a a'), e_closure R a a' | of_path : Π{a a'} (pp : a = a'), e_closure R a a' | symm : Π{a a'} (r : e_closure R a a'), e_closure R a' a | trans : Π{a a' a''} (r : e_closure R a a') (r' : e_closure R a' a''), e_closure R a a'' namespace e_closure infix ` ⬝r `:75 := e_closure.trans postfix `⁻¹ʳ`:(max+10) := e_closure.symm notation `[`:max a `]`:0 := e_closure.of_rel a notation `<`:max p `>`:0 := e_closure.of_path _ p abbreviation rfl [constructor] {A : Type} {R : A → A → Type} {a : A} := of_path R (idpath a) end e_closure open e_closure namespace relation section parameters {A : Type} {R : A → A → Type} local abbreviation T := e_closure R variables ⦃a a' a'' : A⦄ {s : R a a'} {r : T a a} {B C : Type} protected definition e_closure.elim [unfold 8] {f : A → B} (e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : f a = f a' := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, exact e r, exact ap f pp, exact IH⁻¹, exact IH₁ ⬝ IH₂ end definition ap_e_closure_elim_h [unfold 12] {B C : Type} {f : A → B} {g : B → C} (e : Π⦃a a' : A⦄, R a a' → f a = f a') {e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')} (p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a') : ap g (e_closure.elim e t) = e_closure.elim e' t := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, apply p, induction pp, reflexivity, exact ap_inv g (e_closure.elim e r) ⬝ inverse2 IH, exact ap_con g (e_closure.elim e r) (e_closure.elim e r') ⬝ (IH₁ ◾ IH₂) end definition ap_e_closure_elim_h_symm [unfold_full] {B C : Type} {f : A → B} {g : B → C} {e : Π⦃a a' : A⦄, R a a' → f a = f a'} {e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')} (p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a') : ap_e_closure_elim_h e p t⁻¹ʳ = ap_inv g (e_closure.elim e t) ⬝ (ap_e_closure_elim_h e p t)⁻² := by reflexivity definition ap_e_closure_elim_h_trans [unfold_full] {B C : Type} {f : A → B} {g : B → C} {e : Π⦃a a' : A⦄, R a a' → f a = f a'} {e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')} (p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a') (t' : T a' a'') : ap_e_closure_elim_h e p (t ⬝r t') = ap_con g (e_closure.elim e t) (e_closure.elim e t') ⬝ (ap_e_closure_elim_h e p t ◾ ap_e_closure_elim_h e p t') := by reflexivity definition ap_e_closure_elim [unfold 10] {B C : Type} {f : A → B} (g : B → C) (e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : ap g (e_closure.elim e t) = e_closure.elim (λa a' r, ap g (e r)) t := ap_e_closure_elim_h e (λa a' s, idp) t definition ap_e_closure_elim_symm [unfold_full] {B C : Type} {f : A → B} (g : B → C) (e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : ap_e_closure_elim g e t⁻¹ʳ = ap_inv g (e_closure.elim e t) ⬝ (ap_e_closure_elim g e t)⁻² := by reflexivity definition ap_e_closure_elim_trans [unfold_full] {B C : Type} {f : A → B} (g : B → C) (e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') (t' : T a' a'') : ap_e_closure_elim g e (t ⬝r t') = ap_con g (e_closure.elim e t) (e_closure.elim e t') ⬝ (ap_e_closure_elim g e t ◾ ap_e_closure_elim g e t') := by reflexivity definition e_closure_elim_eq [unfold 8] {f : A → B} {e e' : Π⦃a a' : A⦄, R a a' → f a = f a'} (p : e ~3 e') (t : T a a') : e_closure.elim e t = e_closure.elim e' t := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, apply p, reflexivity, exact IH⁻², exact IH₁ ◾ IH₂ end -- TODO: formulate and prove this without using function extensionality, -- and modify the proofs using this to also not use function extensionality -- strategy: use `e_closure_elim_eq` instead of `ap ... (eq_of_homotopy3 p)` definition ap_e_closure_elim_h_eq {B C : Type} {f : A → B} {g : B → C} (e : Π⦃a a' : A⦄, R a a' → f a = f a') {e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')} (p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a') : ap_e_closure_elim_h e p t = ap_e_closure_elim g e t ⬝ ap (λx, e_closure.elim x t) (eq_of_homotopy3 p) := begin fapply homotopy3.rec_on p, intro q, esimp at q, induction q, esimp, rewrite eq_of_homotopy3_id end theorem ap_ap_e_closure_elim_h {B C D : Type} {f : A → B} {g : B → C} (h : C → D) (e : Π⦃a a' : A⦄, R a a' → f a = f a') {e' : Π⦃a a' : A⦄, R a a' → g (f a) = g (f a')} (p : Π⦃a a' : A⦄ (s : R a a'), ap g (e s) = e' s) (t : T a a') : square (ap (ap h) (ap_e_closure_elim_h e p t)) (ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t) (ap_compose h g (e_closure.elim e t))⁻¹ (ap_e_closure_elim_h e' (λa a' s, (ap (ap h) (p s))⁻¹) t) := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, { esimp, apply square_of_eq, exact !con.right_inv ⬝ !con.left_inv⁻¹}, { induction pp, apply ids}, { rewrite [▸*,ap_con (ap h)], refine (transpose !ap_compose_inv)⁻¹ᵛ ⬝h _, rewrite [con_inv,inv_inv,-inv2_inv], exact !ap_inv2 ⬝v square_inv2 IH}, { rewrite [▸*,ap_con (ap h)], refine (transpose !ap_compose_con)⁻¹ᵛ ⬝h _, rewrite [con_inv,inv_inv,con2_inv], refine !ap_con2 ⬝v square_con2 IH₁ IH₂}, end theorem ap_ap_e_closure_elim {B C D : Type} {f : A → B} (g : B → C) (h : C → D) (e : Π⦃a a' : A⦄, R a a' → f a = f a') (t : T a a') : square (ap (ap h) (ap_e_closure_elim g e t)) (ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t) (ap_compose h g (e_closure.elim e t))⁻¹ (ap_e_closure_elim h (λa a' r, ap g (e r)) t) := !ap_ap_e_closure_elim_h definition ap_e_closure_elim_h_zigzag {B C D : Type} {f : A → B} {g : B → C} (h : C → D) (e : Π⦃a a' : A⦄, R a a' → f a = f a') {e' : Π⦃a a' : A⦄, R a a' → h (g (f a)) = h (g (f a'))} (p : Π⦃a a' : A⦄ (s : R a a'), ap (h ∘ g) (e s) = e' s) (t : T a a') : ap_e_closure_elim h (λa a' s, ap g (e s)) t ⬝ (ap_e_closure_elim_h e (λa a' s, ap_compose h g (e s)) t)⁻¹ ⬝ ap_e_closure_elim_h e p t = ap_e_closure_elim_h (λa a' s, ap g (e s)) (λa a' s, (ap_compose h g (e s))⁻¹ ⬝ p s) t := begin refine whisker_right _ (eq_of_square (ap_ap_e_closure_elim g h e t)⁻¹ʰ)⁻¹ ⬝ _, refine !con.assoc ⬝ _, apply inv_con_eq_of_eq_con, apply eq_of_square, apply transpose, -- the rest of the proof is almost the same as the proof of ap_ap_e_closure_elim[_h]. -- Is there a connection between these theorems? induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, { esimp, apply square_of_eq, apply idp_con}, { induction pp, apply ids}, { rewrite [▸*,ap_con (ap h)], refine (transpose !ap_compose_inv)⁻¹ᵛ ⬝h _, rewrite [con_inv,inv_inv,-inv2_inv], exact !ap_inv2 ⬝v square_inv2 IH}, { rewrite [▸*,ap_con (ap h)], refine (transpose !ap_compose_con)⁻¹ᵛ ⬝h _, rewrite [con_inv,inv_inv,con2_inv], refine !ap_con2 ⬝v square_con2 IH₁ IH₂}, end definition is_equivalence_e_closure : is_equivalence T := begin constructor, intro a, exact rfl, intro a a' t, exact t⁻¹ʳ, intro a a' a'' t t', exact t ⬝r t', end /- dependent elimination -/ variables {P : B → Type} {Q : C → Type} {f : A → B} {g : B → C} {f' : Π(a : A), P (f a)} protected definition e_closure.elimo [unfold 11] (p : Π⦃a a' : A⦄, R a a' → f a = f a') (po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a') : f' a =[e_closure.elim p t] f' a' := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, exact po r, induction pp, constructor, exact IH⁻¹ᵒ, exact IH₁ ⬝o IH₂ end definition elimo_symm [unfold_full] (p : Π⦃a a' : A⦄, R a a' → f a = f a') (po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a') : e_closure.elimo p po t⁻¹ʳ = (e_closure.elimo p po t)⁻¹ᵒ := by reflexivity definition elimo_trans [unfold_full] (p : Π⦃a a' : A⦄, R a a' → f a = f a') (po : Π⦃a a' : A⦄ (s : R a a'), f' a =[p s] f' a') (t : T a a') (t' : T a' a'') : e_closure.elimo p po (t ⬝r t') = e_closure.elimo p po t ⬝o e_closure.elimo p po t' := by reflexivity definition ap_e_closure_elimo_h [unfold 12] {g' : Πb, Q (g b)} (p : Π⦃a a' : A⦄, R a a' → f a = f a') (po : Π⦃a a' : A⦄ (s : R a a'), g' (f a) =[p s] g' (f a')) (q : Π⦃a a' : A⦄ (s : R a a'), apd g' (p s) = po s) (t : T a a') : apd g' (e_closure.elim p t) = e_closure.elimo p po t := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, apply q, induction pp, reflexivity, esimp [e_closure.elim], exact apd_inv g' (e_closure.elim p r) ⬝ IH⁻²ᵒ, exact apd_con g' (e_closure.elim p r) (e_closure.elim p r') ⬝ (IH₁ ◾o IH₂) end theorem e_closure_elimo_ap {g' : Π(a : A), Q (g (f a))} (p : Π⦃a a' : A⦄, R a a' → f a = f a') (po : Π⦃a a' : A⦄ (s : R a a'), g' a =[ap g (p s)] g' a') (t : T a a') : e_closure.elimo p (λa a' s, pathover_of_pathover_ap Q g (po s)) t = pathover_of_pathover_ap Q g (change_path (ap_e_closure_elim g p t)⁻¹ (e_closure.elimo (λa a' r, ap g (p r)) po t)) := begin induction t with a a' r a a' pp a a' r IH a a' a'' r r' IH₁ IH₂, { reflexivity}, { induction pp; reflexivity}, { rewrite [+elimo_symm, ap_e_closure_elim_symm, IH, con_inv, change_path_con, ▸*, -inv2_inv, change_path_invo, pathover_of_pathover_ap_invo]}, { rewrite [+elimo_trans, ap_e_closure_elim_trans, IH₁, IH₂, con_inv, change_path_con, ▸*, con2_inv, change_path_cono, pathover_of_pathover_ap_cono]}, end end end relation
cd3068c4c9004fba12b1c5346d86ad47cd07b7cb
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/PrettyPrinter/Delaborator/Options.lean
39b6e4c763c2b23e0862b1b64273d896ad9f9b1c
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,911
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Data.Options namespace Lean register_builtin_option pp.all : Bool := { defValue := false group := "pp" descr := "(pretty printer) display coercions, implicit parameters, proof terms, fully qualified names, universe, " ++ "and disable beta reduction and notations during pretty printing" } register_builtin_option pp.notation : Bool := { defValue := true group := "pp" descr := "(pretty printer) disable/enable notation (infix, mixfix, postfix operators and unicode characters)" } register_builtin_option pp.coercions : Bool := { defValue := true group := "pp" descr := "(pretty printer) hide coercion applications" } register_builtin_option pp.universes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display universe" } register_builtin_option pp.fullNames : Bool := { defValue := false group := "pp" descr := "(pretty printer) display fully qualified names" } register_builtin_option pp.privateNames : Bool := { defValue := false group := "pp" descr := "(pretty printer) display internal names assigned to private declarations" } register_builtin_option pp.binderTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display types of lambda and Pi parameters" } register_builtin_option pp.letVarTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display types of let-bound variables" } register_builtin_option pp.instantiateMVars : Bool := { defValue := false -- TODO: default to true? group := "pp" descr := "(pretty printer) instantiate mvars before delaborating" } register_builtin_option pp.structureInstances : Bool := { defValue := true group := "pp" -- TODO: implement second part descr := "(pretty printer) display structure instances using the '{ fieldName := fieldValue, ... }' notation " ++ "or '⟨fieldValue, ... ⟩' if structure is tagged with [pp_using_anonymous_constructor] attribute" } register_builtin_option pp.structureProjections : Bool := { defValue := true group := "pp" descr := "(pretty printer) display structure projections using field notation" } register_builtin_option pp.explicit : Bool := { defValue := false group := "pp" descr := "(pretty printer) display implicit arguments" } register_builtin_option pp.structureInstanceTypes : Bool := { defValue := false group := "pp" descr := "(pretty printer) display type of structure instances" } register_builtin_option pp.safeShadowing : Bool := { defValue := true group := "pp" descr := "(pretty printer) allow variable shadowing if there is no collision" } register_builtin_option pp.proofs : Bool := { defValue := false group := "pp" descr := "(pretty printer) if set to false, replace proofs appearing as an argument to a function with a placeholder" } register_builtin_option pp.proofs.withType : Bool := { defValue := true group := "pp" descr := "(pretty printer) when eliding a proof (see `pp.proofs`), show its type instead" } register_builtin_option pp.motives.pi : Bool := { defValue := true group := "pp" descr := "(pretty printer) print all motives that return pi types" } register_builtin_option pp.motives.nonConst : Bool := { defValue := false group := "pp" descr := "(pretty printer) print all motives that are not constant functions" } register_builtin_option pp.motives.all : Bool := { defValue := false group := "pp" descr := "(pretty printer) print all motives" } -- TODO: /- register_builtin_option g_pp_max_depth : Nat := { defValue := false group := "pp" descr := "(pretty printer) maximum expression depth, after that it will use ellipsis" } register_builtin_option g_pp_max_steps : Nat := { defValue := false group := "pp" descr := "(pretty printer) maximum number of visited expressions, after that it will use ellipsis" } register_builtin_option g_pp_locals_full_names : Bool := { defValue := false group := "pp" descr := "(pretty printer) show full names of locals" } register_builtin_option g_pp_beta : Bool := { defValue := false group := "pp" descr := "(pretty printer) apply beta-reduction when pretty printing" } register_builtin_option g_pp_goal_compact : Bool := { defValue := false group := "pp" descr := "(pretty printer) try to display goal in a single line when possible" } register_builtin_option g_pp_goal_max_hyps : Nat := { defValue := false group := "pp" descr := "(pretty printer) maximum number of hypotheses to be displayed" } register_builtin_option g_pp_annotations : Bool := { defValue := false group := "pp" descr := "(pretty printer) display internal annotations (for debugging purposes only)" } register_builtin_option g_pp_compact_let : Bool := { defValue := false group := "pp" descr := "(pretty printer) minimal indentation at `let`-declarations" } -/ def getPPAll (o : Options) : Bool := o.get pp.all.name false def getPPBinderTypes (o : Options) : Bool := o.get pp.binderTypes.name (getPPAll o) def getPPLetVarTypes (o : Options) : Bool := o.get pp.letVarTypes.name (getPPAll o) def getPPCoercions (o : Options) : Bool := o.get pp.coercions.name (!getPPAll o) def getPPExplicit (o : Options) : Bool := o.get pp.explicit.name (getPPAll o) def getPPNotation (o : Options) : Bool := o.get pp.notation.name (!getPPAll o) def getPPStructureProjections (o : Options) : Bool := o.get pp.structureProjections.name (!getPPAll o) def getPPStructureInstances (o : Options) : Bool := o.get pp.structureInstances.name (!getPPAll o) def getPPStructureInstanceType (o : Options) : Bool := o.get pp.structureInstanceTypes.name (getPPAll o) def getPPUniverses (o : Options) : Bool := o.get pp.universes.name (getPPAll o) def getPPFullNames (o : Options) : Bool := o.get pp.fullNames.name (getPPAll o) def getPPPrivateNames (o : Options) : Bool := o.get pp.privateNames.name (getPPAll o) def getPPInstantiateMVars (o : Options) : Bool := o.get pp.instantiateMVars.name pp.instantiateMVars.defValue def getPPSafeShadowing (o : Options) : Bool := o.get pp.safeShadowing.name pp.safeShadowing.defValue def getPPProofs (o : Options) : Bool := o.get pp.proofs.name (getPPAll o) def getPPProofsWithType (o : Options) : Bool := o.get pp.proofs.withType.name pp.proofs.withType.defValue def getPPMotivesPi (o : Options) : Bool := o.get pp.motives.pi.name pp.motives.pi.defValue def getPPMotivesNonConst (o : Options) : Bool := o.get pp.motives.nonConst.name pp.motives.nonConst.defValue def getPPMotivesAll (o : Options) : Bool := o.get pp.motives.all.name pp.motives.all.defValue end Lean
178808a48a75adbd502600608507ff400dbad743
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/print_poly.lean
c7a0e18daaf8647933306d52f32be685808e4e8b
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
151
lean
open nat print pp.max_depth print + print - print nat print nat.zero print nat.add print nat.rec print classical.em print quot.lift print nat.of_num
553a64cb71c709e287cd53101e61c7895e60843d
928e43dd755d83a0986ba91420df8ad05b8d7c9f
/1_definitions.lean
67c155bb1a30939b156ebafc44f8ecd99e611c0a
[]
no_license
zmactep/llfgg
ea222b377095a42e0de5cf8d4846aff806ce0f31
ed684ae69b94a4a042615c412fef68bdec8fc80c
refs/heads/master
1,585,131,334,279
1,533,894,322,000
1,533,894,322,000
143,688,771
1
0
null
null
null
null
UTF-8
Lean
false
false
12,879
lean
-- Константы constant n : ℕ -- n — челочисленная константа (\nat для написания ℕ) constant x1 : bool -- x1 объявлена как булева константа constants m k : nat -- m и k также являются константами из ℕ (мы можем писать nat вместо ℕ) constants (x2 : bool) -- через команду constants можно объявить и одну константу, -- если взять её объявление в скобки constants α β : Type -- мы также можем объявлять новые типы, например α (\alpha или \a) и β (\beta или \b) constant f : α → β → α -- наш контекст упорядочен, так что мы можем использовать объявленные -- типы для новых объявлений constants (a : α) (b : β) -- мы можем делать несколько объявлений разного типа в одной строке, -- например a типа α и b типа β constant F : Type → Type -- мы можем объявлять функторы — стрелки над типами -- Проверки типов #check n -- ℕ -- #check возвращает тип выражения #check f -- α → β → α -- аналогично возвращаем тип f #check ℕ -- Type -- ℕ имеет тип Type (иначе говорят, живет во вселенной Type) #check α → β → α -- Type -- любой стрелочный тип живет там же, где и сами типы #check Type -- Type 1 -- Type имеет тип Type 1 (живет во вслеленной Type 1) #check Type 0 -- Type 1 -- Type — это алиас для Type 0 #check Type → Type -- Type 1 -- аналогично строке 22, стрелка из Type в Type живет в Type 1 #check Prop -- Type -- Prop — вселенная, где живут высказывания, сама она живет в Type -- Применение #check f a -- β → α -- мы можем проверить тип прмиенения функции f к аргументу a #check f a b -- α -- применять можно сразу к нескольким аргументам, как в λ-исчислении #check n + 42 -- ℕ -- операторы - это тоже функции (+ определен в стандартной библиотеке) #check F α -- Type -- функторы применяются к типам аналогично функциям #check prod α β -- Type -- в стандартной библиотеке определено произведение типов #check α × β -- Type -- prod == × (\x) #check sum α β -- Type -- в стандартной библиотеке определена сумма типов #check α ⊕ β -- Type -- sum == ⊕ (\o+) #check (a,b) -- α × β -- тип пары значений α и β — произведение типов α и β -- (,) можно читать как функцию, применяемую к a и b -- Вселенные universe u -- аналогично константам можно ввести произвольную вселенную u constant γ : Type u -- γ (\gamma or \g) в такой записи населяет вселенную Type u -- Абстракция #check fun x : α, x -- α → α -- мы можем использовать λ-абстракцию, -- рассматривая fun как лямбду, а запятую как точку #check λ x : α, x -- α → α -- fun == λ (\lambda или \fun) #check λ x : α, λ y : β, x -- α → β → α -- классическая вложенная λ-абстракция #check λ (x : α) (y : β), x -- α → β → α -- синтаксический сахар для вложенной абстракции #check λ (x y : α), x -- α → α → α -- синтаксический сахар для вложенной абстракции -- с одинаковыми типами аргументов #check λ (f : α → β → γ) (g : α → β) (x : α), f x (g x) -- ... -- сложный пример абстракции #check (λ x : α, x) a -- α -- пример сочетания абстракции и апликации в одном примере -- Редукция #reduce (λ x : α, x) a -- a -- упрощает выражение до β-NF (нормальной формы) #reduce (λ x : α, b) (f a b) -- b -- упрощает выражение до β-NF #reduce tt -- tt -- tt - это true для типа bool из стандартной библиотеки #reduce ff -- ff -- ff - это false для типа bool из стандартной библиотеки #reduce x1 ∨ tt -- tt -- любое булевское значение или (\or для ∨) true - это true #reduce x1 ∧ ff -- ff -- любое булевское значение и (\and для ∧) false - это false #reduce n + 0 -- n -- любое натуральное число плюс ноль дает себя же #reduce 0 + n -- 0 + n -- а ноль плюс число не дает, почему, поймем позже #reduce 40 + 2 -- 42 -- мы можем делать арифметические вычисления над числами #reduce (λ x : nat, x + 5) 3 -- 8 -- и комбинировать их с λ-исчислением -- Определения def foo : ℕ := 5 -- определение константной ℕ функции foo с телом 5 def bar : (ℕ → ℕ) → ℕ := -- определение функции bar с типом возвращаемого значения (ℕ → ℕ) → ℕ λ f : ℕ → ℕ, f 0 -- и телом λ f, f 0 (тип f можно опустить, он будет выведен) def bar' := λ f : ℕ → ℕ, f 0 -- в таком случае тип функции также будет выведен def double (x : ℕ) : ℕ := x + x -- определение функции, принимающей один аргумент (x : ℕ) -- и удваивающей его def double' : ℕ → ℕ := λ x : ℕ , x + x -- та же функция в форме без явного именования аргумента def sqrsum (x : ℕ) (y : ℕ) : ℕ := -- определение функции, принимающей два аргумента типа ℕ x * x + y * y -- и возвращающей сумму их квадратов def sqrsum' (x y : ℕ) : ℕ := -- синтаксический сахар для записи аргументов одного типа x * x + y * y def compose (α β γ : Type) -- определение функции композиции, абстрактной по типам функций (f : β → γ) -- определяется каждая из двух функций, подходящих по типу, (g : α → β) : α → γ := -- и как их композировать на произвольном аргументе λ x : α, f (g x) def curry (α β γ : Type) -- функции можно не определять, написав вместо их значений sorry (f : α × β → γ) : α → β → γ := sorry -- реальное значение будет λ (x : α) (y : β), f (x, y) -- Локальное определение #reduce let y := (a, b) in (y, y) -- ... -- локальное связывание y со значением (a, b) def t(x : ℕ) : ℕ := -- локальное связывание y внутри функции let y := x + x - 2 in y #reduce let x := t 4, y := 2 in x + y -- локальное связывание двух переменных: x и y def flet := -- локальное связывание имени a с типом ℕ и его let a := ℕ in λ x : a, x -- дальнейшее использование в абстракции #check flet -- ℕ → ℕ -- тип функции при этом может быть выведен автоматически -- Печать #print "hello" -- командой print можно напечатать любую строку #print double -- а еще тело любой функции можно напечатать -- Переменные variable α1 : Type -- часто используемые объявления в именах функций можно заводить отдельно variables α2 α3 : Type -- аналогично можно заводить сразу по несколько переменных def f_compose (f : α2 → α3) -- объявленные переменные могут использоваться в функции (g : α1 → α2) : α1 → α3 := -- (сравните с функцией compose на 97 строке, где они объявлены по месту) λ x : α1, f (g x) #check compose -- типы обеих функций выглядят одинаково #check f_compose -- Секции section my -- чтоб не засорять общее пространство имен можно ввести именованную (my) секцию variable α : Type -- объявленные тут переменные будут видны только внутри секции variable list : Type → Type def cons (a : α) -- аналогично и с функциями (tail : list α) : list α := sorry section your -- секции могут быть вложенными variable β : Type def nil : list β := sorry -- при этом все переменные внешний секций также будут доступны end your end my #check cons -- объявленные в секции функции доступны извне её -- Пространства имен namespace my -- чтоб не засорять пространство имен функций вводят namespaces def foo' : ℕ := 5 -- функция внтури namespace может быть использована def bar' : ℕ := foo + 1 -- любой другой функцией внутри того же namespace namespace your -- пространства имен также как и секции могут быть вложенными def quz : ℕ := foo' -- элементы родительского пространства могут использоваться end your end my #reduce my.your.quz -- для доступа из вне требуется указать полное имя namespace my -- закрытое пространство имен может быть переоткрыто -- в том числе в другом файле def qux : ℕ := bar' * 2 end my open my -- с помощью команды open можно поднять все определения в текущий scope #reduce foo' + your.quz -- и использовать содержимое по короткому имени
5f7d42d54ffe43930e41e27990a7f88988d64588
947b78d97130d56365ae2ec264df196ce769371a
/src/Init.lean
8d425ad15e621ff899ca206fcd89033645236288
[ "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
337
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.Control import Init.Data.Basic import Init.WF import Init.Data import Init.System import Init.Util import Init.Fix import Init.LeanInit
a8c399b566ce0bb1569c7c1a488fafdc3d0948b4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/logic/small.lean
b461367d22fe25426a10853c7d1dab9d88e3795d
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,028
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.equiv.basic /-! # Small types A type is `w`-small if there exists an equivalence to some `S : Type w`. We provide a noncomputable model `shrink α : Type w`, and `equiv_shrink α : α ≃ shrink α`. A subsingleton type is `w`-small for any `w`. If `α ≃ β`, then `small.{w} α ↔ small.{w} β`. -/ universes u w v /-- A type is `small.{w}` if there exists an equivalence to some `S : Type w`. -/ class small (α : Type v) : Prop := (equiv_small : ∃ (S : Type w), nonempty (α ≃ S)) /-- Constructor for `small α` from an explicit witness type and equivalence. -/ lemma small.mk' {α : Type v} {S : Type w} (e : α ≃ S) : small.{w} α := ⟨⟨S, ⟨e⟩⟩⟩ /-- An arbitrarily chosen model in `Type w` for a `w`-small type. -/ @[nolint has_inhabited_instance] def shrink (α : Type v) [small.{w} α] : Type w := classical.some (@small.equiv_small α _) /-- The noncomputable equivalence between a `w`-small type and a model. -/ noncomputable def equiv_shrink (α : Type v) [small.{w} α] : α ≃ shrink α := nonempty.some (classical.some_spec (@small.equiv_small α _)) @[priority 100] instance small_self (α : Type v) : small.{v} α := small.mk' (equiv.refl _) @[priority 100] instance small_max (α : Type v) : small.{max w v} α := small.mk' equiv.ulift.{w}.symm instance small_ulift (α : Type v) : small.{v} (ulift.{w} α) := small.mk' equiv.ulift theorem small_type : small.{max (u+1) v} (Type u) := small_max.{max (u+1) v} _ section open_locale classical theorem small_congr {α : Type*} {β : Type*} (e : α ≃ β) : small.{w} α ↔ small.{w} β := begin fsplit, { rintro ⟨S, ⟨f⟩⟩, exact small.mk' (e.symm.trans f), }, { rintro ⟨S, ⟨f⟩⟩, exact small.mk' (e.trans f), }, end instance small_subtype (α : Type v) [small.{w} α] (P : α → Prop) : small.{w} { x // P x } := begin rw small_congr (equiv_shrink α).subtype_equiv_of_subtype', apply_instance, end theorem small_of_injective {α : Type*} {β : Type*} [small.{w} β] (f : α → β) (hf : function.injective f) : small.{w} α := begin rw small_congr (equiv.of_injective f hf), apply_instance, end @[priority 100] instance small_subsingleton (α : Type v) [subsingleton α] : small.{w} α := begin rcases is_empty_or_nonempty α; resetI, { rw small_congr (equiv.equiv_pempty α), apply small_self, }, { rw small_congr equiv.punit_of_nonempty_of_subsingleton, apply small_self, assumption, assumption, }, end /-! We don't define `small_of_fintype` or `small_of_encodable` in this file, to keep imports to `logic` to a minimum. -/ instance small_Pi {α} (β : α → Type*) [small.{w} α] [∀ a, small.{w} (β a)] : small.{w} (Π a, β a) := ⟨⟨Π a' : shrink α, shrink (β ((equiv_shrink α).symm a')), ⟨equiv.Pi_congr (equiv_shrink α) (λ a, by simpa using equiv_shrink (β a))⟩⟩⟩ instance small_sigma {α} (β : α → Type*) [small.{w} α] [∀ a, small.{w} (β a)] : small.{w} (Σ a, β a) := ⟨⟨Σ a' : shrink α, shrink (β ((equiv_shrink α).symm a')), ⟨equiv.sigma_congr (equiv_shrink α) (λ a, by simpa using equiv_shrink (β a))⟩⟩⟩ instance small_prod {α β} [small.{w} α] [small.{w} β] : small.{w} (α × β) := ⟨⟨shrink α × shrink β, ⟨equiv.prod_congr (equiv_shrink α) (equiv_shrink β)⟩⟩⟩ instance small_sum {α β} [small.{w} α] [small.{w} β] : small.{w} (α ⊕ β) := ⟨⟨shrink α ⊕ shrink β, ⟨equiv.sum_congr (equiv_shrink α) (equiv_shrink β)⟩⟩⟩ instance small_set {α} [small.{w} α] : small.{w} (set α) := ⟨⟨set (shrink α), ⟨equiv.set.congr (equiv_shrink α)⟩⟩⟩ theorem not_small_type : ¬ small.{u} (Type (max u v)) | ⟨⟨S, ⟨e⟩⟩⟩ := @function.cantor_injective (Σ α, e.symm α) (λ a, ⟨_, cast (e.3 _).symm a⟩) (λ a b e, (cast_inj _).1 $ eq_of_heq (sigma.mk.inj e).2) end
a5570fd9c2001833fa03b14b1c138ffc047a88b6
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.6.lean
40fd00e5006b117aae1fc775aad090f26dce1300
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
1,179
lean
/- page 49 -/ import standard variables (A : Type) (p q : A → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (assume H : ∀ x, p x ∧ q x, and.intro (take x : A, and.left (H x)) (take x : A, and.right (H x))) (assume H : (∀ x, p x) ∧ (∀ x, q x), take x : A, and.intro (and.left H x) (and.right H x)) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := assume H : ∀ x, p x → q x, assume H' : ∀ x, p x, take x : A, show q x, from H x (H' x) example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := or.rec (λ H x, or.inl (H x)) (λ H x, or.inr (H x)) /- In this last example, the reverse implication is not derivable, because it is not valid. The hypothesis would be that, given any x, either p x or q x holds. In particular, for any x, either p or q may not hold, as long as the other does. But the conclusion would have either p x for all x, or q x for all x. That is, either p x, always, or q x, always. -/
ca881b643e671bdfd49d6dbc62162c880970d550
9028d228ac200bbefe3a711342514dd4e4458bff
/src/algebra/order.lean
be9578bb30e2c7ffa383d7ee861f5e5cab9d005c
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,163
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 tactic.alias import tactic.lint /-! # Lemmas about inequalities This file contains some lemmas about `≤`/`≥`/`<`/`>`, and `cmp`. * We simplify `a ≥ b` and `a > b` to `b ≤ a` and `b < a`, respectively. This way we can formulate all lemmas using `≤`/`<` avoiding duplication. * In some cases we introduce dot syntax aliases so that, e.g., from `(hab : a ≤ b) (hbc : b ≤ c) (hbc' : b < c)` one can prove `hab.trans hbc : a ≤ c` and `hab.trans_lt hbc' : a < c`. -/ universe u variables {α : Type u} alias le_trans ← has_le.le.trans alias lt_of_le_of_lt ← has_le.le.trans_lt alias le_antisymm ← has_le.le.antisymm alias lt_of_le_of_ne ← has_le.le.lt_of_ne alias lt_of_le_not_le ← has_le.le.lt_of_not_le alias lt_or_eq_of_le ← has_le.le.lt_or_eq alias le_of_lt ← has_lt.lt.le alias lt_trans ← has_lt.lt.trans alias lt_of_lt_of_le ← has_lt.lt.trans_le alias ne_of_lt ← has_lt.lt.ne alias lt_asymm ← has_lt.lt.asymm has_lt.lt.not_lt alias le_of_eq ← eq.le /-- A version of `le_refl` where the argument is implicit -/ lemma le_rfl [preorder α] {x : α} : x ≤ x := le_refl x namespace eq /-- If `x = y` then `y ≤ x`. Note: this lemma uses `y ≤ x` instead of `x ≥ y`, because `le` is used almost exclusively in mathlib. -/ protected lemma ge [preorder α] {x y : α} (h : x = y) : y ≤ x := h.symm.le lemma trans_le [preorder α] {x y z : α} (h1 : x = y) (h2 : y ≤ z) : x ≤ z := h1.le.trans h2 end eq namespace has_le.le @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma ge [has_le α] {x y : α} (h : x ≤ y) : y ≥ x := h lemma trans_eq [preorder α] {x y z : α} (h1 : x ≤ y) (h2 : y = z) : x ≤ z := h1.trans h2.le lemma lt_iff_ne [partial_order α] {x y : α} (h : x ≤ y) : x < y ↔ x ≠ y := ⟨λ h, h.ne, h.lt_of_ne⟩ lemma le_iff_eq [partial_order α] {x y : α} (h : x ≤ y) : y ≤ x ↔ y = x := ⟨λ h', h'.antisymm h, eq.le⟩ end has_le.le namespace has_lt namespace lt @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma gt [has_lt α] {x y : α} (h : x < y) : y > x := h protected lemma false [preorder α] {x : α} : x < x → false := lt_irrefl x end lt end has_lt namespace ge @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma le [has_le α] {x y : α} (h : x ≥ y) : y ≤ x := h end ge namespace gt @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma lt [has_lt α] {x y : α} (h : x > y) : y < x := h end gt @[nolint ge_or_gt] -- see Note [nolint_ge] theorem ge_of_eq [preorder α] {a b : α} (h : a = b) : a ≥ b := h.ge @[simp, nolint ge_or_gt] -- see Note [nolint_ge] lemma ge_iff_le [preorder α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl @[simp, nolint ge_or_gt] -- see Note [nolint_ge] lemma gt_iff_lt [preorder α] {a b : α} : a > b ↔ b < a := iff.rfl lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right alias not_le_of_lt ← has_lt.lt.not_le lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a | hab := hab.not_le h alias not_lt_of_le ← has_le.le.not_lt lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or.comm lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b := ⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, h1.lt_of_ne h2⟩ lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b := ⟨λ h, ⟨h.le, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, h₁.antisymm $ classical.by_contradiction $ λ h₃, h₂ (h₁.lt_of_not_le h₃)⟩ lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := h.lt_or_eq.symm alias eq_or_lt_of_le ← has_le.le.eq_or_lt lemma ne.le_iff_lt [partial_order α] {a b : α} (h : a ≠ b) : a ≤ b ↔ a < b := ⟨λ h', lt_of_le_of_ne h' h, λ h, h.le⟩ lemma lt_of_not_ge' [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b := ((le_total _ _).resolve_right h).lt_of_not_le h lemma lt_iff_not_ge' [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_gt, lt_of_not_ge'⟩ lemma le_of_not_lt [linear_order α] {a b : α} : ¬ a < b → b ≤ a := not_lt.1 lemma lt_or_le [linear_order α] : ∀ a b : α, a < b ∨ b ≤ a := lt_or_ge lemma le_or_lt [linear_order α] : ∀ a b : α, a ≤ b ∨ b < a := le_or_gt lemma ne.lt_or_lt [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := lt_or_gt_of_ne h lemma has_le.le.lt_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a < c ∨ c ≤ b := (lt_or_le a c).imp id $ λ hc, hc.trans h lemma has_le.le.le_or_lt [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c < b := (le_or_lt a c).imp id $ λ hc, hc.trans_le h lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a := not_lt.trans $ le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | or.inl h := ⟨_, h, le_rfl⟩ | or.inr h := ⟨_, le_rfl, h⟩ end lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_ge' $ λ h', (H h').not_lt h lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_gt $ λ h', (H h').not_le h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans $ (not_congr H).trans $ not_le lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩ lemma eq_of_forall_le_iff [partial_order α] {a b : α} (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := le_antisymm ((H _).1 (le_refl _)) ((H _).2 (le_refl _)) lemma le_of_forall_le [preorder α] {a b : α} (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ (le_refl _) lemma le_of_forall_le' [preorder α] {a b : α} (H : ∀ c, a ≤ c → b ≤ c) : b ≤ a := H _ (le_refl _) lemma le_of_forall_lt [linear_order α] {a b : α} (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le [linear_order α] {a b : α} : (∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b := ⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩ lemma le_of_forall_lt' [linear_order α] {a b : α} (H : ∀ c, a < c → b < c) : b ≤ a := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le' [linear_order α] {a b : α} : (∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a := ⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩ lemma eq_of_forall_ge_iff [partial_order α] {a b : α} (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := le_antisymm ((H _).2 (le_refl _)) ((H _).1 (le_refl _)) /-- monotonicity of `≤` with respect to `→` -/ lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (h₀ : c ≤ a) (h₁ : b ≤ d) : a ≤ b → c ≤ d := assume h₂ : a ≤ b, calc c ≤ a : h₀ ... ≤ b : h₂ ... ≤ d : h₁ namespace decidable -- See Note [decidable namespace] lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ -- See Note [decidable namespace] lemma le_iff_le_iff_lt_iff_lt {β} [decidable_linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩ end decidable namespace ordering /-- `compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined -/ @[simp] def compares [has_lt α] : ordering → α → α → Prop | lt a b := a < b | eq a b := a = b | gt a b := a > b theorem compares.eq_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = lt ↔ a < b) | lt a b h := ⟨λ _, h, λ _, rfl⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h' h).elim⟩ | gt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ theorem compares.eq_eq [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = eq ↔ a = b) | lt a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h h').elim⟩ | eq a b h := ⟨λ _, h, λ _, rfl⟩ | gt a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h h').elim⟩ theorem compares.eq_gt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = gt ↔ b < a) | lt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h' h).elim⟩ | gt a b h := ⟨λ _, h, λ _, rfl⟩ theorem compares.inj [preorder α] {o₁} : ∀ {o₂} {a b : α}, compares o₁ a b → compares o₂ a b → o₁ = o₂ | lt a b h₁ h₂ := h₁.eq_lt.2 h₂ | eq a b h₁ h₂ := h₁.eq_eq.2 h₂ | gt a b h₁ h₂ := h₁.eq_gt.2 h₂ theorem compares_iff_of_compares_impl {β : Type*} [linear_order α] [preorder β] {a b : α} {a' b' : β} (h : ∀ {o}, compares o a b → compares o a' b') (o) : compares o a b ↔ compares o a' b' := begin refine ⟨h, λ ho, _⟩, cases lt_trichotomy a b with hab hab, { change compares ordering.lt a b at hab, rwa [ho.inj (h hab)] }, { cases hab with hab hab, { change compares ordering.eq a b at hab, rwa [ho.inj (h hab)] }, { change compares ordering.gt a b at hab, rwa [ho.inj (h hab)] } } end theorem swap_or_else (o₁ o₂) : (or_else o₁ o₂).swap = or_else o₁.swap o₂.swap := by cases o₁; try {refl}; cases o₂; refl theorem or_else_eq_lt (o₁ o₂) : or_else o₁ o₂ = lt ↔ o₁ = lt ∨ (o₁ = eq ∧ o₂ = lt) := by cases o₁; cases o₂; exact dec_trivial end ordering theorem cmp_compares [decidable_linear_order α] (a b : α) : (cmp a b).compares a b := begin unfold cmp cmp_using, by_cases a < b; simp [h], by_cases h₂ : b < a; simp [h₂, gt], exact (lt_or_eq_of_le (le_of_not_gt h₂)).resolve_left h end theorem cmp_swap [preorder α] [@decidable_rel α (<)] (a b : α) : (cmp a b).swap = cmp b a := begin unfold cmp cmp_using, by_cases a < b; by_cases h₂ : b < a; simp [h, h₂, gt, ordering.swap], exact lt_asymm h h₂ end
1c6f4342d4dad66c68499e9b1d644215b7aaf026
ae9f8bf05de0928a4374adc7d6b36af3411d3400
/src/formal_ml/real_random_variable.lean
b0161c685018336d0a486505200425c270e3ad7a
[ "Apache-2.0" ]
permissive
NeoTim/formal-ml
bc42cf6beba9cd2ed56c1cd054ab4eb5402ed445
c9cbad2837104160a9832a29245471468748bb8d
refs/heads/master
1,671,549,160,900
1,601,362,989,000
1,601,362,989,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
89,878
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import measure_theory.measurable_space import measure_theory.measure_space import measure_theory.outer_measure import measure_theory.lebesgue_measure import measure_theory.integration import measure_theory.borel_space import data.set.countable import formal_ml.measurable_space import formal_ml.probability_space import formal_ml.real_measurable_space import formal_ml.nnreal import formal_ml.semiring import topology.instances.real import formal_ml.classical /- This file should be vetted for results in borel_space.lean. borel_space also has a wealth of results about ennreal, including a proof that multiplication is measurable. This completes the story of ennreal measurable functions being a commutative semiring. -/ ------------- A measurable linear order ------------------------------------------------------------ /- Similar to topological semirings, a measurable linear order adds measurability onto a linear order. -/ class measurable_linear_order (α:Type*) [M:measurable_space α] extends linear_order α := (is_measurable_le:is_measurable {p:α × α|p.fst ≤ p.snd}) (is_measurable_eq:is_measurable {p:α × α|p.fst = p.snd}) instance measurable_linear_order_to_has_measurable_eq (α:Type*) [M:measurable_space α] [L:measurable_linear_order α]:has_measurable_equality M := { is_measurable_eq := L.is_measurable_eq, } def measurable_linear_order_t2_sc {α:Type*} [T:topological_space α] [SC:topological_space.second_countable_topology α] [P:linear_order α] [OT:order_topology α] [T2:t2_space α]:@measurable_linear_order α (borel α) := { is_measurable_le:=is_measurable_of_le, is_measurable_eq:=is_measurable_of_eq, } noncomputable instance measurable_linear_order_nnreal:measurable_linear_order nnreal := measurable_linear_order_t2_sc noncomputable instance measurable_linear_order_real:measurable_linear_order real := measurable_linear_order_t2_sc noncomputable instance measurable_linear_order_ennreal:measurable_linear_order ennreal := measurable_linear_order_t2_sc lemma lt_iff_le_not_eq {α:Type*} [linear_order α] (a b:α):a < b ↔ a ≤ b ∧ (a ≠ b) := begin apply iff.trans, apply linear_order.lt_iff_le_not_le, split; intro A1, { split, apply A1.left, intro A2, apply A1.right, rw A2, }, { split, apply A1.left, intro A2, apply A1.right, apply linear_order.le_antisymm, apply A1.left, apply A2, } end lemma measurable_linear_order.is_measurable_lt (α:Type*) [M:measurable_space α] [c:measurable_linear_order α]:measurable_space.is_measurable' (@prod.measurable_space α α M M) {p:α × α|p.fst < p.snd} := begin have A1:{p:α × α|p.fst < p.snd} = {p:α × α|p.fst ≤ p.snd} \ {p:α × α|p.fst = p.snd}, { ext, simp, apply lt_iff_le_not_eq, }, rw A1, apply is_measurable.diff, { apply measurable_linear_order.is_measurable_le, }, { apply measurable_linear_order.is_measurable_eq } end lemma measurable_linear_order.is_measurable_le' (α:Type*) [M:measurable_space α] [MLO:measurable_linear_order α]:is_measurable {p:α × α|p.snd ≤ p.fst} := begin have A1:{p:α × α|p.snd ≤ p.fst} = {p:α × α|p.fst < p.snd}ᶜ, { ext p, split;intros A1A;simp;simp at A1A;apply A1A, }, rw A1, apply is_measurable.compl, apply measurable_linear_order.is_measurable_lt, end --------------------------------------------------------------------------------------------------- section is_sub_semiring universes u v --def semiring.to_add_monoid {α:Type u} (semiring α):add_monoid α := def SC_sum_measurable_add_monoid {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:add_monoid β} {TA:has_continuous_add β}: add_monoid (measurable_fun MΩ (borel β)) := @subtype.add_monoid (Ω → β) _ (@measurable Ω β MΩ (borel β)) (@SC_sum_measurable_is_add_submonoid Ω MΩ β T SC CSR TA) def SC_sum_measurable_add_comm_monoid {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:add_comm_monoid β} {TA:has_continuous_add β}: add_comm_monoid (measurable_fun MΩ (borel β)) := @subtype.add_comm_monoid (Ω → β) _ (@measurable Ω β MΩ (borel β)) (@SC_sum_measurable_is_add_submonoid Ω MΩ β T SC (add_comm_monoid.to_add_monoid β) TA) def SC_sum_measurable_is_add_submonoid_from_semiring {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:semiring β} {TA:topological_semiring β}: is_add_submonoid (@measurable Ω β MΩ (borel β)) := (@SC_sum_measurable_is_add_submonoid Ω MΩ β T SC (add_comm_monoid.to_add_monoid β) (topological_semiring.to_has_continuous_add)) def SC_sum_measurable_is_add_subgroup_from_ring {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:ring β} {TA:topological_ring β}: is_add_subgroup (@measurable Ω β MΩ (borel β)) := (@SC_sum_measurable_is_add_subgroup Ω MΩ β T SC (add_comm_group.to_add_group β) (topological_ring.to_topological_add_group β)) def SC_mul_measurable_is_submonoid_from_semiring {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:semiring β} {TA:topological_semiring β}: is_submonoid (@measurable Ω β MΩ (borel β)) := (@SC_mul_measurable_is_submonoid Ω MΩ β T SC (monoid_with_zero.to_monoid β) (topological_semiring.to_has_continuous_mul)) def SC_measurable_semiring_is_sub_semiring {Ω:Type u} [MΩ:measurable_space Ω] {β:Type v} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:semiring β} {TA:topological_semiring β}: is_sub_semiring (@measurable Ω β MΩ (borel β)) := { ..(@SC_sum_measurable_is_add_submonoid_from_semiring Ω MΩ β T SC _ TA), ..(@SC_mul_measurable_is_submonoid_from_semiring Ω MΩ β T SC _ TA), } def SC_measurable_ring_is_subring {Ω:Type u} [MΩ:measurable_space Ω] {β:Type v} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:ring β} {TA:topological_ring β}: is_subring (@measurable Ω β MΩ (borel β)) := { ..(@SC_sum_measurable_is_add_subgroup_from_ring Ω MΩ β T SC _ TA), ..(@SC_mul_measurable_is_submonoid_from_semiring Ω MΩ β T SC _ (topological_ring.to_topological_semiring β)), } def SC_measurable_semiring {Ω:Type u} [MΩ:measurable_space Ω] {β:Type v} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:semiring β} {TA:topological_semiring β}: semiring (measurable_fun MΩ (borel β)):= @subtype.semiring (Ω → β) _ (@measurable Ω β MΩ (borel β)) (@SC_measurable_semiring_is_sub_semiring Ω MΩ β T SC CSR TA) def SC_measurable_comm_semiring {Ω:Type u} [MΩ:measurable_space Ω] {β:Type v} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:comm_semiring β} {TA:topological_semiring β}: comm_semiring (measurable_fun MΩ (borel β)):= @subtype.comm_semiring (Ω → β) _ (@measurable Ω β MΩ (borel β)) (@SC_measurable_semiring_is_sub_semiring Ω MΩ β T SC (comm_semiring.to_semiring β) TA) def SC_measurable_comm_ring {Ω:Type u} [MΩ:measurable_space Ω] {β:Type v} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:comm_ring β} {TA:topological_ring β}: comm_ring (measurable_fun MΩ (borel β)):= @subtype.comm_ring (Ω → β) _ (@measurable Ω β MΩ (borel β)) (@SC_measurable_ring_is_subring Ω MΩ β T SC (comm_ring.to_ring β) TA) end is_sub_semiring noncomputable instance nnreal_measurable_fun_comm_semiring {Ω:Type*} [MΩ:measurable_space Ω]: comm_semiring (measurable_fun MΩ (borel nnreal)):= @SC_measurable_comm_semiring Ω MΩ nnreal nnreal.topological_space nnreal.topological_space.second_countable_topology nnreal.comm_semiring nnreal.topological_semiring noncomputable def real.topological_space:topological_space ℝ := infer_instance noncomputable instance real_measurable_fun_comm_ring {Ω:Type*} [MΩ:measurable_space Ω]: comm_ring (measurable_fun MΩ (borel real)):= @SC_measurable_comm_ring Ω MΩ real real.topological_space real.topological_space.second_countable_topology real.comm_ring real.topological_ring lemma nnreal_measurable_fun_zero_val_def {Ω:Type*} [MΩ:measurable_space Ω]: (0:MΩ →ₘ (borel nnreal)).val = 0 := rfl lemma real_measurable_fun_zero_val_def {Ω:Type*} [MΩ:measurable_space Ω]: (0:MΩ →ₘ (borel real)).val = 0 := rfl lemma nnreal_measurable_fun_add_val_def {Ω:Type*} [MΩ:measurable_space Ω] {a b:MΩ →ₘ (borel nnreal)}: (a + b).val = (a.val + b.val) := rfl lemma real_measurable_fun_add_val_def {Ω:Type*} [MΩ:measurable_space Ω] {a b:MΩ →ₘ (borel real)}: (a + b).val = (a.val + b.val) := rfl lemma nnreal_measurable_fun_one_val_def {Ω:Type*} [MΩ:measurable_space Ω]: (1:MΩ →ₘ (borel nnreal)).val = 1 := rfl lemma real_measurable_fun_one_val_def {Ω:Type*} [MΩ:measurable_space Ω]: (1:MΩ →ₘ (borel real)).val = 1 := rfl lemma nnreal_measurable_fun_mul_val_def {Ω:Type*} [MΩ:measurable_space Ω] {a b:MΩ →ₘ (borel nnreal)}: (a * b).val = (a.val * b.val) := rfl lemma real_measurable_fun_mul_val_def {Ω:Type*} [MΩ:measurable_space Ω] {a b:MΩ →ₘ (borel real)}: (a * b).val = (a.val * b.val) := rfl noncomputable instance nnreal_random_variable_comm_semiring {Ω:Type*} {p:probability_space Ω}: comm_semiring (random_variable p (borel nnreal)):= nnreal_measurable_fun_comm_semiring noncomputable instance real_random_variable_comm_ring {Ω:Type*} {p:probability_space Ω}: comm_ring (random_variable p (borel real)):= real_measurable_fun_comm_ring lemma nnreal_random_variable_add_val_def {Ω:Type*} {P:probability_space Ω} {a b:P →ᵣ (borel nnreal)}: (a + b).val = (a.val + b.val) := rfl lemma real_random_variable_add_val_def {Ω:Type*} {P:probability_space Ω} {a b:P →ᵣ (borel real)}: (a + b).val = (a.val + b.val) := rfl lemma nnreal_random_variable_mul_val_def {Ω:Type*} {P:probability_space Ω} {a b:P →ᵣ (borel nnreal)}: (a * b).val = (a.val * b.val) := rfl lemma real_random_variable_mul_val_def {Ω:Type*} {P:probability_space Ω} {a b:P →ᵣ (borel nnreal)}: (a * b).val = (a.val * b.val) := rfl lemma real_random_variable_neg_val_def {Ω:Type*} {P:probability_space Ω} {a:P →ᵣ (borel real)}: (-a).val = -(a.val) := rfl --ennreal is not a topological semiring, because multiplication is not continuous, --but it is measurable. Therefore, we must prove it is a submonoid directly. def ennreal_measurable_is_submonoid {Ω:Type*} [MΩ:measurable_space Ω]: is_submonoid (@measurable Ω ennreal MΩ (borel ennreal)) := { one_mem :=@measurable_const ennreal Ω (borel ennreal) MΩ 1, mul_mem := begin intros x y A1 A2, apply measurable.ennreal_mul A1 A2, end } --Should be able to use SC_sum_measurable_is_add_submonoid, --but results in definitional inequalities in ennreal_measurable_is_sub_semiring. def ennreal_measurable_is_add_submonoid {Ω:Type*} [MΩ:measurable_space Ω]: is_add_submonoid (@measurable Ω ennreal MΩ (borel ennreal)) := { zero_mem :=@measurable_const ennreal Ω (borel ennreal) MΩ 0, add_mem := begin intros x y A1 A2, apply measurable.ennreal_add A1 A2, end } def ennreal_measurable_is_sub_semiring {Ω:Type*} [MΩ:measurable_space Ω]: is_sub_semiring (@measurable Ω ennreal MΩ (borel ennreal)) := { ..(@ennreal_measurable_is_add_submonoid Ω MΩ), ..(@ennreal_measurable_is_submonoid Ω MΩ), } noncomputable instance ennreal_measurable_fun_comm_semiring {Ω:Type*} [MΩ:measurable_space Ω]: comm_semiring (measurable_fun MΩ (borel ennreal)):= @subtype.comm_semiring (Ω → ennreal) _ (@measurable Ω ennreal MΩ (borel ennreal)) (@ennreal_measurable_is_sub_semiring Ω MΩ) noncomputable instance ennreal_random_variable_comm_semiring {Ω:Type*} {p:probability_space Ω}: comm_semiring (random_variable p (borel ennreal)):= ennreal_measurable_fun_comm_semiring lemma ennreal_measurable_fun_zero_val_def {Ω:Type*} [MΩ:measurable_space Ω]: (0:MΩ →ₘ (borel ennreal)).val = 0 := rfl lemma ennreal_measurable_fun_add_val_def {Ω:Type*} [MΩ:measurable_space Ω] {a b:MΩ →ₘ (borel ennreal)}: (a + b).val = (a.val + b.val) := rfl --A test to see if + works. lemma nnreal_commutes {Ω:Type*} {P:probability_space Ω} (A B:P →ᵣ (borel nnreal)):A + B = B + A := begin rw add_comm, end def measurable_set_le {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] :measurable_set (Mβ ×ₘ Mβ) := { val:={p:β × β|p.fst ≤ p.snd}, property:=L.is_measurable_le, } lemma measurable_set_le_val_def {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β]:(@measurable_set_le β Mβ L).val = {p:β × β|p.fst ≤ p.snd} := rfl lemma measurable_linear_order.is_measurable_lt' (α:Type*) [M:measurable_space α] [c:measurable_linear_order α]:measurable_space.is_measurable' (M ×ₘ M) {p:α × α|p.fst < p.snd} := begin apply measurable_linear_order.is_measurable_lt, end def measurable_set_lt {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] :measurable_set (Mβ ×ₘ Mβ) := { val:={p:β × β|p.fst < p.snd}, property:=@measurable_linear_order.is_measurable_lt _ _ L, } lemma event_eq_val_def {Ω : Type*} {P:probability_space Ω} {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] (X Y:P →ᵣ Mβ):(X =ᵣ Y).val = {a : Ω | X.val a = Y.val a} := begin rw rv_eq_val_def, end def event_lt {Ω : Type*} {P:probability_space Ω} {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] (X Y:P →ᵣ Mβ):event P := rv_event (X ×ᵣ Y) (measurable_set_lt) /- Now, Pr[X <ᵣ Y] is just what it looks like: the probability that X is less than Y. -/ infixr ` <ᵣ `:80 := event_lt def event_le {Ω : Type*} {P:probability_space Ω} {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] (X Y:P →ᵣ Mβ):event P := rv_event (X ×ᵣ Y) (measurable_set_le) infixr ` ≤ᵣ `:80 := event_le lemma event_le_def {Ω : Type*} {P:probability_space Ω} {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] (X Y:P →ᵣ Mβ):(X ≤ᵣ Y) = rv_event (X ×ᵣ Y) (measurable_set_le) := rfl lemma event_le_val_def {Ω : Type*} {P:probability_space Ω} {β : Type*} [Mβ:measurable_space β] [L:measurable_linear_order β] (X Y:P →ᵣ Mβ):(X ≤ᵣ Y).val = {ω : Ω | X.val ω ≤ Y.val ω} := begin rw event_le_def, rw rv_event_val_def, rw prod_random_variable_val_def, rw measurable_set_le_val_def, simp, end noncomputable instance coe_measurable_fun_of_nnreal {Ω : Type*} {P:measurable_space Ω} :has_coe nnreal (measurable_fun P (borel nnreal)) := { coe := const_measurable_fun } noncomputable instance coe_measurable_fun_of_real {Ω : Type*} {P:measurable_space Ω} :has_coe real (measurable_fun P (borel real)) := { coe := const_measurable_fun } noncomputable instance coe_random_variable_of_nnreal {Ω : Type*} {P:probability_space Ω} :has_coe nnreal (P →ᵣ borel nnreal) := { coe := const_random_variable } noncomputable instance coe_random_variable_of_real {Ω : Type*} {P:probability_space Ω} :has_coe real (P →ᵣ borel real) := { coe := const_random_variable } lemma coe_random_variable_of_real_def {Ω : Type*} {P:probability_space Ω} {x:ℝ}: (x:P →ᵣ (borel ℝ)) = const_random_variable x := rfl lemma coe_random_variable_of_real_val_def {Ω : Type*} {P:probability_space Ω} {x:ℝ}: (x:P →ᵣ (borel ℝ)).val = λ (ω:Ω), x := rfl noncomputable def to_nnreal_rv {Ω : Type*} {P:probability_space Ω} (x:nnreal):(P →ᵣ borel nnreal) := x lemma to_nnreal_rv_val_def {Ω : Type*} {P:probability_space Ω} (x:nnreal):(@to_nnreal_rv Ω P x).val = λ ω:Ω, x := rfl noncomputable instance coe_measurable_fun_of_ennreal {Ω : Type*} [MΩ:measurable_space Ω] :has_coe ennreal (measurable_fun MΩ (borel ennreal)) := { coe := const_measurable_fun } noncomputable instance coe_random_variable_of_ennreal {Ω : Type*} {P:probability_space Ω} :has_coe ennreal (P →ᵣ borel ennreal) := { coe := const_random_variable } noncomputable def to_ennreal_rv {Ω : Type*} {P:probability_space Ω} (x:ennreal):(P →ᵣ borel ennreal) := x def to_ennreal_rv_val_def {Ω : Type*} {P:probability_space Ω} (x:ennreal): (@to_ennreal_rv Ω P x).val = λ ω:Ω, x := begin rw to_ennreal_rv, refl, end noncomputable def expected_value_ennreal {α:Type*} {p:probability_space α} (X:p →ᵣ borel ennreal):ennreal := ∫⁻ (a : α), X.val a ∂ (p.volume) lemma nnreal_to_ennreal_measurable:measurable (λ x:nnreal, (x:ennreal)) := begin apply is_ennreal_measurable_intro_Iio, intro x, cases x, { simp, }, { simp, apply is_nnreal_is_measurable_intro_Iio, } end def measurable2 {α β γ:Type*} [measurable_space α] [measurable_space β] [measurable_space γ] (f:α → β → γ):Prop := measurable (λ p:α × β, f (p.fst) (p.snd)) lemma measurable2_def {α β γ:Type*} [measurable_space α] [measurable_space β] [measurable_space γ] (f:α → β → γ):measurable2 f = measurable (λ p:α × β, f (p.fst) (p.snd)) := rfl lemma measurable2_composition {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} [Mβ:measurable_space β] (f:Ω → β) (g:Ω → β) (h:β → β → β): (measurable f) → (measurable g) → (measurable2 h) → measurable (λ ω:Ω, h (f ω) (g ω)) := begin intros A1 A2 A3, have A4:measurable (λ ω:Ω, prod.mk (f ω) (g ω)), { apply measurable_fun_product_measurable;assumption, }, rw measurable2_def at A3, have A6:(λ ω:Ω, h (f ω) (g ω))=(λ p: (β × β), h (p.fst) (p.snd)) ∘ (λ ω:Ω, prod.mk (f ω) (g ω)), { simp, }, rw A6, apply compose_measurable_fun_measurable (λ p: (β × β), h (p.fst) (p.snd)) (λ ω:Ω, prod.mk (f ω) (g ω)) A3 A4, end lemma measurable2_max:measurable2 (@max ℝ _) := begin rw measurable2_def, apply measurable.if, apply @measurable_linear_order.is_measurable_le' ℝ, apply fst_measurable, apply snd_measurable, end lemma abs_eq_max (x:ℝ):abs x = max x (-x) := rfl lemma abs_eq_max_fn :(@abs ℝ _) = (λ x, max x (-x)) := begin ext, rw abs_eq_max, end lemma measurable_abs:measurable (@abs ℝ _) := begin rw abs_eq_max_fn, apply measurable2_composition (@id ℝ) (@has_neg.neg ℝ _) (@max ℝ _), { apply measurable_id, }, { apply continuous_measurable, apply @topological_ring.continuous_neg ℝ _ _, }, { apply measurable2_max, }, end lemma of_real_of_nonpos {a:ℝ}:a ≤ 0 → (nnreal.of_real a = 0) := begin intro A1, apply subtype.eq, simp, apply A1, end lemma nnreal_lt {a:ℝ} {b:nnreal}:(b ≠ 0) → (nnreal.of_real a < b ↔ a < b.val) := begin intro A1, split;intro A2, { have A3:0 ≤ a ∨ a < 0 := decidable.le_or_lt 0 a, cases A3, { rw ← nnreal.coe_lt_coe at A2, rw nnreal.coe_of_real _ A3 at A2, apply A2, }, { apply lt_of_lt_of_le, apply A3, apply b.2, }, }, { have A3:0 ≤ a ∨ a < 0 := decidable.le_or_lt 0 a, cases A3, { rw ← nnreal.coe_lt_coe, rw nnreal.coe_of_real _ A3, apply A2, }, { rw of_real_of_nonpos (le_of_lt A3), --apply lt_of_lt_of_le, --apply A3, --apply b.2, apply lt_of_le_of_ne, { apply bot_le, }, { symmetry, apply A1, }, }, }, end lemma nnreal_lt_set {b:nnreal}:(b ≠ 0) → {a:ℝ|nnreal.of_real a < b} = {a:ℝ|a < b.val} := begin intro A1, ext, simp, apply nnreal_lt A1, end lemma nnreal_lt_zero_set:{a : ℝ | nnreal.of_real a < 0} = ∅ := begin ext, simp, end lemma measurable_nnreal_of_real:measurable nnreal.of_real := begin apply is_nnreal_measurable_intro_Iio, intro x, simp, have A1:(x=0) ∨ (x≠ 0) := eq_or_ne, cases A1, { rw A1, rw nnreal_lt_zero_set, apply is_measurable.empty, }, { rw nnreal_lt_set A1, apply is_real_is_measurable_intro_Iio, }, end noncomputable def nnreal_of_real_fun:measurable_fun (borel real) (borel nnreal) := { val := nnreal.of_real, property := measurable_nnreal_of_real, } lemma nnreal_of_real_fun_val_def:nnreal_of_real_fun.val = nnreal.of_real := rfl noncomputable def real_abs_fun:measurable_fun (borel real) (borel real) := { val := (@abs ℝ _), property := measurable_abs, } lemma real_abs_fun_val_def:real_abs_fun.val = (@abs ℝ _) := rfl noncomputable def measurable_fun_nnreal_of_measurable_fun_real {α:Type*} {Mα:measurable_space α} (X:measurable_fun Mα (borel real)):measurable_fun Mα (borel nnreal) := compose_measurable_fun nnreal_of_real_fun X lemma measurable_fun_nnreal_of_measurable_fun_real_val_def {α:Type*} {Mα:measurable_space α} (X:measurable_fun Mα (borel real)): (measurable_fun_nnreal_of_measurable_fun_real X).val = (nnreal.of_real ∘ X.val) := begin unfold measurable_fun_nnreal_of_measurable_fun_real, rw compose_measurable_fun_val_def, rw nnreal_of_real_fun_val_def end def nnreal_to_ennreal_measurable_fun:measurable_fun (borel nnreal) (borel ennreal) := { val := (λ x:nnreal, (x:ennreal)), property := nnreal_to_ennreal_measurable, } noncomputable def nnreal_to_ennreal_random_variable {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel nnreal):p →ᵣ borel ennreal := nnreal_to_ennreal_measurable_fun ∘r X lemma nnreal_to_ennreal_random_variable_val_def {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel nnreal): (nnreal_to_ennreal_random_variable X).val = (λ (ω:Ω), ((X.val ω):ennreal)) := begin unfold nnreal_to_ennreal_random_variable, rw rv_compose_val_def, unfold nnreal_to_ennreal_measurable_fun, end noncomputable def expected_value_nnreal {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel nnreal):ennreal := @expected_value_ennreal Ω p (nnreal_to_ennreal_random_variable X) class has_expectation (Ω α: Type*) (P:probability_space Ω) (M:measurable_space α) := (expectation : (P →ᵣ M) → ennreal) notation `E[` X `]`:= has_expectation.expectation X noncomputable instance has_expectation_nnreal {Ω:Type*} {P:probability_space Ω}:has_expectation Ω nnreal P (borel nnreal) := { expectation := @expected_value_nnreal Ω P } noncomputable instance has_expectation_ennreal {Ω:Type*} {P:probability_space Ω}:has_expectation Ω ennreal P (borel ennreal) := { expectation := @expected_value_ennreal Ω P } /- I haven't wrapped my head around measure_space yet. -/ def to_measure_space {Ω:Type*} (p:probability_space Ω): measure_theory.measure_space Ω := probability_space.to_measure_space lemma expected_value_ennreal_def {Ω:Type*} {P:probability_space Ω} (X:P →ᵣ borel ennreal):E[X] = ∫⁻ (a : Ω), (X.val) a ∂ (P.volume) := rfl lemma expected_value_ennreal_def2 {Ω:Type*} {P:probability_space Ω} (X:P →ᵣ borel ennreal):E[X] = measure_theory.lintegral P.volume(X.val) := rfl lemma expected_value_nnreal_def {Ω:Type*} {P:probability_space Ω} (X:P →ᵣ borel nnreal):E[X] = @expected_value_ennreal Ω P (nnreal_to_ennreal_random_variable X) := rfl lemma expected_value_nnreal_def2 {Ω:Type*} {P:probability_space Ω} (X:P →ᵣ borel nnreal):E[X] = measure_theory.lintegral P.volume (λ (ω:Ω), ((X.val ω):ennreal)) := rfl lemma expected_value_nnreal_def3 {Ω:Type*} {P:probability_space Ω} (X:P →ᵣ borel nnreal):E[X] = E[(nnreal_to_ennreal_random_variable X)] := rfl lemma expected_value_nnreal_def4 {Ω:Type*} {P:probability_space Ω} (X:P →ᵣ borel nnreal):E[X] = @expected_value_nnreal Ω P X := rfl lemma expectation_add_ennreal {Ω:Type*} {p:probability_space Ω} (X Y:p →ᵣ borel ennreal):E[X + Y] = E[X] + E[Y] := begin repeat {rw expected_value_ennreal_def2}, rw ennreal_measurable_fun_add_val_def, have A1:@measure_theory.lintegral Ω _ p.volume (X.val + Y.val)= (@measure_theory.lintegral Ω _ p.volume (λ a, X.val a + Y.val a)), { refl, }, rw A1, rw @measure_theory.lintegral_add Ω (probability_space.to_measurable_space Ω) p.volume X.val Y.val, apply X.property, apply Y.property, end lemma decidable_subst (P Q:Prop):(P↔ Q) → decidable P → decidable Q := begin intros A1 A2, rw ← A1, apply A2, end lemma decidable_subst2 (P Q:Prop):(Q↔ P) → decidable P → decidable Q := begin intros A1 A2, rw A1, apply A2, end noncomputable def max_rv {α β:Type*} {P:probability_space α} {Mβ:measurable_space β} [L:measurable_linear_order β] [D:decidable_linear_order β] (X Y:random_variable P Mβ):random_variable P Mβ := if_random_variable (X ≤ᵣ Y) (classical.decidable_pred (X ≤ᵣ Y).val) Y X noncomputable def min_rv {α β:Type*} {P:probability_space α} {Mβ:measurable_space β} [L:measurable_linear_order β] [D:decidable_linear_order β] (X Y:random_variable P Mβ):random_variable P Mβ := if_random_variable (X ≤ᵣ Y) (classical.decidable_pred (X ≤ᵣ Y).val) X Y noncomputable def absolute_nnreal {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)):random_variable P (borel nnreal) := @measurable_fun_nnreal_of_measurable_fun_real Ω (probability_space.to_measurable_space Ω) (real_abs_fun ∘r X) lemma absolute_nnreal_val_def {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)): (absolute_nnreal X).val = nnreal.of_real ∘ (@abs ℝ _) ∘ X.val := begin unfold absolute_nnreal, rw measurable_fun_nnreal_of_measurable_fun_real_val_def, rw rv_compose_val_def, rw real_abs_fun_val_def, end noncomputable def pos_nnreal {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)):random_variable P (borel nnreal) := @measurable_fun_nnreal_of_measurable_fun_real Ω (probability_space.to_measurable_space Ω) X lemma pos_nnreal_val_def {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)): (pos_nnreal X).val = nnreal.of_real ∘ X.val := begin unfold pos_nnreal, rw measurable_fun_nnreal_of_measurable_fun_real_val_def, end noncomputable def neg_nnreal {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)):random_variable P (borel nnreal) := @measurable_fun_nnreal_of_measurable_fun_real Ω (probability_space.to_measurable_space Ω) (-X) lemma neg_nnreal_val_def {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)): (neg_nnreal X).val = nnreal.of_real ∘ (- X.val) := begin unfold neg_nnreal, rw measurable_fun_nnreal_of_measurable_fun_real_val_def, rw real_random_variable_neg_val_def, end noncomputable def absolute_expected_value_real {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)):ennreal := expected_value_nnreal (absolute_nnreal X) def expected_value_exists {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real):Prop := (absolute_expected_value_real X) < ⊤ /- Calculate the expected value of a real random variable. If the absolute expected value is infinite, the result is undefined. -/ noncomputable def expected_value_real_raw {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)):real := ennreal.to_real (expected_value_nnreal (pos_nnreal X)) - (ennreal.to_real (expected_value_nnreal (neg_nnreal X))) lemma absolute_nnreal_pos_nnreal_plus_neg_nnreal {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)): (absolute_nnreal X) = (pos_nnreal X) + (neg_nnreal X) := begin apply subtype.eq, rw absolute_nnreal_val_def, rw nnreal_measurable_fun_add_val_def, -- unfold absolute_nnreal pos_nnreal neg_nnreal, rw pos_nnreal_val_def, rw neg_nnreal_val_def, ext ω, simp, let x:ℝ := X.val ω, begin have A1:x = X.val ω:=rfl, rw ← random_variable_val_eq_coe, rw ← A1, have A2:x ≤ 0 ∨ (0 < x) := le_or_lt x 0, cases A2, { rw abs_of_nonpos, have A3:nnreal.of_real x = 0, { apply nnreal.of_real_of_nonpos A2, }, rw A3, simp, apply A2, }, { rw abs_of_pos A2, have A3:nnreal.of_real (-x) = 0, { apply nnreal.of_real_of_nonpos, apply le_of_lt, apply neg_lt_of_pos, apply A2, }, { rw A3, simp, }, }, end end noncomputable def expected_value_real {Ω:Type*} {P:probability_space Ω} (X:random_variable P (borel ℝ)):real := @ite (expected_value_exists X) (classical.prop_decidable (expected_value_exists X)) _ (expected_value_real_raw X) 0 /- Note that random variables do not necessarily have means or variances. In particular, the mean (or variance) may be infinite. TODO: make the calculation of the variance more explicit. Explicitly show that for any real or nnreal random variable, 0≤ (X ω - E[X]) * (X ω - E[x]) (on the extended real number line). -/ def has_mean {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel nnreal) (μ:nnreal):Prop := E[X] = μ noncomputable def finite_mean {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel nnreal):nnreal := ennreal.to_nnreal ( E[X] ) def has_variance {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel nnreal) {μ:nnreal} {H:has_mean X μ} {V:nnreal}:Prop := E[X * X] - μ * μ = V lemma indicator_measurable {Ω:Type*} [measurable_space Ω] (E:set Ω) [D:decidable_pred E]: (is_measurable E) → measurable (λ ω:Ω, if (ω ∈ E) then (1:nnreal) else (0:nnreal)) := begin intros A1, have A2:(λ ω:Ω, if (ω ∈ E) then (1:nnreal) else (0:nnreal)) = (λ ω:Ω, if (ω ∈ E) then ((λ x:Ω, (1:nnreal)) ω) else ((λ x:Ω, (0:nnreal)) ω)), { refl, }, rw A2, apply measurable.if, { exact A1, }, { apply const_measurable, }, { apply const_measurable, } end def indicatorh {Ω : Type*} [MΩ:measurable_space Ω] (E:set Ω) [D:decidable_pred E] (H:is_measurable E):measurable_fun MΩ (borel nnreal) := { val := (λ ω:Ω, if (ω ∈ E) then (1:nnreal) else (0:nnreal)), property := @indicator_measurable Ω MΩ E D H, } noncomputable def indicator {Ω : Type*} {MΩ:measurable_space Ω} (E:measurable_set MΩ):measurable_fun MΩ (borel nnreal) := @indicatorh Ω MΩ E.val (classical.decidable_pred E.val) E.property lemma indicator_val_def {Ω : Type*} {MΩ:measurable_space Ω} (E:measurable_set MΩ):(indicator E).val = (λ ω:Ω, @ite (ω ∈ E.val) (@classical.decidable_pred Ω E.val ω) nnreal (1:nnreal) (0:nnreal)) := begin refl, end noncomputable def indicator_rv {Ω : Type*} {P:probability_space Ω} (E:event P):random_variable P (borel nnreal) := indicator E def finset_sum_measurable2 {Ω β:Type*} {MΩ:measurable_space Ω} {γ:Type*} {T:topological_space γ} {SC:topological_space.second_countable_topology γ} {CSR:add_comm_monoid γ} {TA:has_continuous_add γ} (S:finset β) (X:β → (measurable_fun MΩ (borel γ))):@measurable _ _ _ (borel γ) (λ ω:Ω, S.sum (λ b:β, ((X b).val ω))) := begin apply finset_sum_measurable_classical, { apply SC, }, { apply TA, }, { intro b, apply (X b).property, } end def finset_sum_measurable_fun {Ω β:Type*} {MΩ:measurable_space Ω} {γ:Type*} [T:topological_space γ] [SC:topological_space.second_countable_topology γ] [CSR:add_comm_monoid γ] [TA:has_continuous_add γ] (S:finset β) (X:β → (measurable_fun MΩ (borel γ))):measurable_fun MΩ (borel γ) := { val := (λ ω:Ω, S.sum (λ b:β, ((X b).val ω))), property := @finset_sum_measurable2 Ω β MΩ γ T SC CSR TA S X, } lemma finset_sum_measurable_fun_val_def {Ω β:Type*} {MΩ:measurable_space Ω} {γ:Type*} [T:topological_space γ] [SC:topological_space.second_countable_topology γ] [CSR:add_comm_monoid γ] [TA:has_continuous_add γ] (S:finset β) (X:β → (measurable_fun MΩ (borel γ))): (finset_sum_measurable_fun S X).val = (λ ω:Ω, S.sum (λ b:β, ((X b).val ω))) := begin unfold finset_sum_measurable_fun, end noncomputable def count_finset {Ω β:Type*} {MΩ:measurable_space Ω} (S:finset β) (X:β → measurable_set MΩ):MΩ →ₘ borel nnreal := finset_sum_measurable_fun S (λ b:β, indicator (X b)) lemma count_finset_val_def {Ω β:Type*} {MΩ:measurable_space Ω} (S:finset β) (X:β → measurable_set MΩ):(count_finset S X).val = λ ω:Ω, S.sum (λ (b : β), @ite (ω ∈ (X b).val) (@classical.decidable_pred Ω (X b).val ω) nnreal 1 0) := begin unfold count_finset, rw finset_sum_measurable_fun_val_def, ext ω, have A1:(λ (b : β), (indicator (X b)).val ω) = (λ b, @ite (ω ∈ (X b).val) (@classical.decidable_pred Ω (X b).val ω) nnreal 1 0), { ext, rw indicator_val_def, }, rw A1, end noncomputable def count_finset_rv {Ω β:Type*} {P:probability_space Ω} (S:finset β) (X:β → event P):P →ᵣ borel nnreal := count_finset S X noncomputable def count {Ω β:Type*} {MΩ:measurable_space Ω} [F:fintype β] (X:β → measurable_set MΩ):MΩ →ₘ borel nnreal := count_finset F.elems X --Before going on, we need linearity of expectation. --We have to either prove that the ennreal random variables are a commutative semiring, or --just a commutative additive monoid. ---------- Lemmas that need a home ----------------------------------------------------------------- lemma supr_eq_max {α β:Type*} [complete_lattice α] {x:β} {f:β → α}: (∀ y:β, f y ≤ f x)→ f x = supr f := begin intro A1, apply le_antisymm, { apply complete_lattice.le_Sup, simp, }, { apply complete_lattice.Sup_le, intros b A2, simp at A2, cases A2 with y A3, rw ← A3, apply A1, } end lemma measure_theory_volume_def {Ω:Type*} {P:probability_space Ω} {S:set Ω}:@measure_theory.measure_space.volume Ω (to_measure_space P) S = @measure_theory.measure_space.volume Ω (to_measure_space P) S := rfl lemma measure_theory_volume_def2 {Ω:Type*} {P:probability_space Ω} {S:set Ω}:@measure_theory.measure_space.volume Ω (to_measure_space P) S = P.volume.measure_of S := rfl lemma measure_theory_volume_def3 {Ω:Type*} {MΩ:measure_theory.measure_space Ω} {S:set Ω}:@measure_theory.measure_space.volume Ω MΩ S = @measure_theory.measure_space.volume Ω MΩ S := rfl lemma measure_theory_volume_def4 {Ω:Type*} {MΩ:measure_theory.measure_space Ω} {S:set Ω}:@measure_theory.measure_space.volume Ω MΩ S = measure_theory.outer_measure.measure_of (@measure_theory.measure_space.volume Ω MΩ).to_outer_measure S := rfl lemma univ_eq_empty_of_not_inhabited {Ω:Type*}:(¬(∃ x:Ω,true)) → (@set.univ Ω=∅) := begin intro A1, ext,split;intro A2, { exfalso, apply A1, apply exists.intro x, exact true.intro, }, { exfalso, apply A2, } end lemma simple_func_const_cast_def {Ω:Type*} {MΩ:measurable_space Ω} (x:ennreal): ⇑(@measure_theory.simple_func.const Ω ennreal MΩ x)=λ ω:Ω, x := rfl lemma simple_func_const_to_fun_def {Ω:Type*} {MΩ:measurable_space Ω} (x:ennreal): (@measure_theory.simple_func.const Ω ennreal MΩ x).to_fun=λ ω:Ω, x := rfl lemma simple_func_to_fun_eq_cast_def {Ω:Type*} {MΩ:measurable_space Ω} (s:@measure_theory.simple_func Ω MΩ ennreal):s.to_fun = s := rfl lemma outcome_space_inhabited {Ω:Type*} (P:probability_space Ω):(∃ x:Ω,true) := begin have A1:¬(∃ x:Ω,true) → false, { intro A1A, have A1B:(@set.univ Ω=∅), { apply univ_eq_empty_of_not_inhabited A1A, }, have A1C:P.volume.measure_of (@set.univ Ω)= P.volume.measure_of (@has_emptyc.emptyc (set Ω) _), { rw A1B, }, rw measure_theory.outer_measure.empty at A1C, rw probability_space.univ_one at A1C, simp at A1C, exact A1C, }, apply classical.by_contradiction A1, end lemma outcome_space_nonempty {Ω:Type*} (P:probability_space Ω):nonempty Ω := begin have A1:(∃ x:Ω, true) := outcome_space_inhabited P, cases A1 with x A2, apply nonempty.intro x, end lemma integral_simple_func_const {Ω:Type*} {P:probability_space Ω} (x:ennreal): @measure_theory.simple_func.lintegral Ω (P.to_measurable_space) (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) (P.to_measure_space.volume) = x := begin unfold measure_theory.simple_func.lintegral, have A1:(λ (x_1 : ennreal), x_1 * @measure_theory.measure_space.volume Ω (to_measure_space P) (⇑(measure_theory.simple_func.const Ω x) ⁻¹' {x_1})) = λ x_1:ennreal, if (x_1 = x) then x else 0, { ext x_1, rw measure_theory_volume_def2, rw simple_func_const_cast_def, have A1A:decidable (x_1 = x), { apply classical.decidable_eq ennreal x_1 x, }, cases A1A, { rw if_neg A1A, have A1C:((λ (ω : Ω), x) ⁻¹' {x_1}) =∅, { ext ω,split;intros A1CA, { simp at A1CA, exfalso, apply A1A, rw A1CA, }, { exfalso, apply A1CA, } }, rw A1C, rw measure_theory.outer_measure.empty, simp, }, { rw if_pos A1A, rw A1A, have A1C:((λ (ω : Ω), x) ⁻¹' {x}) =set.univ, { ext ω,split;intros A1CA;simp, }, rw A1C, rw probability_space.univ_one, simp, }, }, rw A1, have A3:(@measure_theory.simple_func.range Ω ennreal (@measure_theory.measure_space.to_measurable_space Ω (@to_measure_space Ω P)) (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x)) = {x}, { have A3X:nonempty Ω := outcome_space_nonempty P, apply @measure_theory.simple_func.range_const ennreal Ω (probability_space.to_measurable_space Ω) A3X x, }, rw A3, simp, end lemma ge_refl {α : Type*} [preorder α] (a : α): a ≥ a := begin simp, end lemma simple_func_le_def {Ω:Type*} {MΩ:measurable_space Ω} {β:Type*} [preorder β] (a b:(@measure_theory.simple_func Ω MΩ β)): (a ≤ b) ↔ a.to_fun ≤ b.to_fun := begin refl, end lemma integral_simple_func_to_fun {Ω:Type*} {MΩ:measure_theory.measure_space Ω} (s:@measure_theory.simple_func Ω MΩ.to_measurable_space ennreal): @measure_theory.lintegral Ω MΩ.to_measurable_space MΩ.volume (@measure_theory.simple_func.to_fun Ω MΩ.to_measurable_space ennreal s) = s.lintegral MΩ.volume := begin rw simple_func_to_fun_eq_cast_def, rw measure_theory.simple_func.lintegral_eq_lintegral, end lemma to_ennreal_rv_val_eq_simple_func {Ω:Type*} {P:probability_space Ω} {x:ennreal}:(@to_ennreal_rv Ω P x).val = (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x).to_fun := begin rw to_ennreal_rv_val_def, rw simple_func_const_to_fun_def, end lemma ennreal_expectation_const {Ω:Type*} {P:probability_space Ω} {x:ennreal}: E[(@to_ennreal_rv Ω P x)] = (x:ennreal) := begin rw expected_value_ennreal_def2, rw to_ennreal_rv_val_eq_simple_func, rw integral_simple_func_to_fun, rw integral_simple_func_const, end lemma ennreal_expectation_zero {Ω:Type*} {P:probability_space Ω}: E[(0:P→ᵣ (borel ennreal))] = (0:ennreal) := begin --apply ennreal_expectation_const, rw expected_value_ennreal_def, have A1:(0:P→ᵣ (borel ennreal)).val=λ ω:Ω, 0, { apply @ennreal_measurable_fun_zero_val_def Ω (probability_space.to_measurable_space Ω), }, rw A1, rw measure_theory.lintegral_zero, end lemma nnreal_zero_eq_ennreal_zero {Ω:Type*} {P:probability_space Ω}: (@nnreal_to_ennreal_random_variable Ω P (0:P→ᵣ (borel nnreal))) = (0:P→ᵣ (borel ennreal)) := begin apply subtype.eq, rw nnreal_to_ennreal_random_variable_val_def, refl, end lemma expectation_zero {Ω:Type*} {P:probability_space Ω}: E[(0:P→ᵣ (borel nnreal))] = (0:ennreal) := begin rw expected_value_nnreal_def3, rw nnreal_zero_eq_ennreal_zero, apply ennreal_expectation_zero, end lemma to_nnreal_rv_eq_to_ennreal_rv {Ω:Type*} {P:probability_space Ω} {x:nnreal}: (@nnreal_to_ennreal_random_variable Ω P (to_nnreal_rv x)) = (to_ennreal_rv (x:ennreal)) := begin apply subtype.eq, rw nnreal_to_ennreal_random_variable_val_def, refl, end lemma nnreal_expectation_const {Ω:Type*} {P:probability_space Ω} (x:nnreal): E[(@to_nnreal_rv Ω P x)] = (x:ennreal) := begin rw expected_value_nnreal_def3, rw to_nnreal_rv_eq_to_ennreal_rv, rw ennreal_expectation_const, end /- lemma ennreal_expectation_prod {Ω:Type*} {P:probability_space Ω} (X Y:P →ᵣ (borel ennreal)):E[X * Y] = E[X] * E[Y] -/ lemma finset_sum_measurable_fun_zero {Ω β:Type*} {P:probability_space Ω} (X:β → P →ᵣ (borel nnreal)): (finset_sum_measurable_fun ∅ (λ (b : β), (X b))) = (0:P→ᵣ (borel nnreal)) := begin unfold finset_sum_measurable_fun, simp, refl, end lemma finset_sum_measurable_fun_insert {Ω β:Type*} [decidable_eq β] {P:probability_space Ω} {a:β} {S:finset β} (X:β → P →ᵣ (borel nnreal)):(a∉ S) → (finset_sum_measurable_fun (insert a S) (λ (b : β), (X b))) = (X a) + (finset_sum_measurable_fun S (λ (b : β), (X b))) := begin intros A1, apply subtype.eq, rw finset_sum_measurable_fun_val_def, rw nnreal_measurable_fun_add_val_def, rw finset_sum_measurable_fun_val_def, ext ω, rw finset.sum_insert, refl, exact A1, end lemma lift_add_nnreal_random_variable {Ω:Type*} {p:probability_space Ω} (X Y:p →ᵣ borel nnreal): nnreal_to_ennreal_random_variable (X + Y) = (nnreal_to_ennreal_random_variable X) + (nnreal_to_ennreal_random_variable Y) := begin apply subtype.eq, rw ennreal_measurable_fun_add_val_def, rw nnreal_to_ennreal_random_variable_val_def, rw nnreal_to_ennreal_random_variable_val_def, rw nnreal_to_ennreal_random_variable_val_def, rw nnreal_measurable_fun_add_val_def, have A1:(λ (ω : Ω), (((X.val + Y.val) ω):ennreal))=(λ (ω : Ω), ((X.val ω):ennreal) + ((Y.val ω):ennreal)), { ext ω, simp, }, rw A1, refl, end lemma expectation_add_nnreal {Ω:Type*} {p:probability_space Ω} (X Y:p →ᵣ borel nnreal):E[X + Y] = E[X] + E[Y] := begin rw expected_value_nnreal_def, rw lift_add_nnreal_random_variable, apply expectation_add_ennreal, end lemma finset_sum_measurable_fun_linear {Ω β:Type*} {P:probability_space Ω} (S:finset β) [D:decidable_eq β] (X:β → P →ᵣ (borel nnreal)): E[(finset_sum_measurable_fun S (λ (b : β), (X b)))] = finset.sum S (λ (k : β), E[X k]) := begin apply finset.induction_on S, { rw finset_sum_measurable_fun_zero, simp, rw expectation_zero, }, { intros a s A1 A2, rw finset_sum_measurable_fun_insert, rw finset.sum_insert, rw expectation_add_nnreal, rw A2, exact A1, exact A1, } end noncomputable def ennreal.has_zero:has_zero ennreal := infer_instance lemma indicator_eq_simple_func {Ω:Type*} {P:probability_space Ω} {S:event P}: (@nnreal_to_ennreal_random_variable Ω P (@indicator Ω (probability_space.to_measurable_space Ω) S)).val = (@measure_theory.simple_func.restrict Ω ennreal (probability_space.to_measurable_space Ω) ennreal.has_zero (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) 1) S.val) := begin ext ω, rw nnreal_to_ennreal_random_variable_val_def, rw indicator_val_def, rw measure_theory.simple_func.restrict_apply, rw measure_theory.simple_func.const_apply, simp, apply S.property, end lemma restrict_univ {Ω:Type*} {MΩ:measurable_space Ω} (s:@measure_theory.simple_func Ω MΩ ennreal): (@measure_theory.simple_func.restrict Ω ennreal MΩ ennreal.has_zero s (@set.univ Ω))=s := begin ext ω, simp, end lemma simple_func_preimage_empty_of_notin_range {Ω:Type*} {MΩ:measurable_space Ω} {f:@measure_theory.simple_func Ω MΩ ennreal} {x:ennreal}:(x∉ f.range) → ⇑f ⁻¹' {x}=∅ := begin intro A1, unfold measure_theory.simple_func.range at A1, ext ω,split;intro A2, { exfalso, apply A1, rw ← simple_func_to_fun_eq_cast_def at A2, simp, apply exists.intro ω, simp at A2, exact A2, }, { exfalso, apply A2, } end lemma simple_func_integral_superset {Ω:Type*} {MΩ:measure_theory.measure_space Ω} {f:@measure_theory.simple_func Ω MΩ.to_measurable_space ennreal} {S:finset ennreal}:f.range ⊆ S → f.lintegral MΩ.volume = S.sum (λ x, x * measure_theory.measure_space.volume (f ⁻¹' {x})) := begin intro A1, unfold measure_theory.simple_func.lintegral, apply finset.sum_subset A1, intros x A2 A3, have A4:⇑f ⁻¹' {x}=∅, { apply simple_func_preimage_empty_of_notin_range A3, }, rw A4, rw measure_theory_volume_def4, rw measure_theory.outer_measure.empty, simp, end lemma restrict_range_subseteq {Ω:Type*} {MΩ:measurable_space Ω} (s:@measure_theory.simple_func Ω MΩ ennreal) (S:measurable_set MΩ): (@measure_theory.simple_func.range Ω ennreal MΩ (@measure_theory.simple_func.restrict Ω ennreal MΩ ennreal.has_zero s (@subtype.val (set Ω) (@measurable_space.is_measurable' Ω MΩ) (S)))) ⊆ {0} ∪ (s.range) := begin simp, rw finset.subset_iff, intros x A1, simp, simp at A1, cases A1 with ω A2, rw ← measurable_set_val_eq_coe at A2, rw @measure_theory.simple_func.restrict_apply Ω ennreal MΩ ennreal.has_zero s S.val S.property at A2, cases classical.em (ω ∈ S.val) with A3 A3, { right, apply exists.intro ω, rw if_pos at A2, exact A2, exact A3, }, { left, rw if_neg at A2, rw A2, exact A3, } end lemma integral_simple_func_restrict_const {Ω:Type*} {P:probability_space Ω} {S:event P} (x:ennreal): (x≠ 0) → (@measure_theory.simple_func.lintegral Ω (probability_space.to_measurable_space Ω) (@measure_theory.simple_func.restrict Ω ennreal (probability_space.to_measurable_space Ω) ennreal.has_zero (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) S.val) P.volume) = x * (P.volume.measure_of (S.val)) := begin intro AX, have A1:(λ (x_1 : ennreal), x_1 * @measure_theory.measure_space.volume Ω (to_measure_space P) (⇑(@measure_theory.simple_func.restrict Ω ennreal (probability_space.to_measurable_space Ω) ennreal.has_zero (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) S.val) ⁻¹' {x_1})) = λ x_1:ennreal, if (x_1 = x) then x * (P.volume.measure_of S.val) else 0, { ext x_1, rw measure_theory_volume_def2, have A1X:decidable (x_1 = 0), { apply classical.decidable_eq ennreal x_1 0, }, cases A1X, { rw measure_theory.simple_func.restrict_preimage, have A1A:decidable (x_1 = x), { apply classical.decidable_eq ennreal x_1 x, }, cases A1A, { rw if_neg A1A, have A1C:⇑(@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) ⁻¹' {x_1} =∅, { ext ω,split;intros A1CA, { simp at A1CA, exfalso, apply A1A, rw A1CA, }, { exfalso, apply A1CA, } }, rw A1C, simp, }, { rw if_pos A1A, rw A1A, have A1C:⇑(@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) ⁻¹' {x} =set.univ, { ext ω,split;intros A1CA;simp, }, rw A1C, simp, }, apply S.property, simp, intro A1D, apply A1X, rw A1D, }, { rw A1X, simp, have A1E:¬ (0 = x), { intro A1E1, apply AX, rw A1E1, }, rw if_neg, simp, intro A1E1, apply AX, rw A1E1, }, }, have B1:(@measure_theory.simple_func.range Ω ennreal (@measure_theory.measure_space.to_measurable_space Ω (@to_measure_space Ω P)) (@measure_theory.simple_func.restrict Ω ennreal (probability_space.to_measurable_space Ω) ennreal.has_zero (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) (@subtype.val (set Ω) (@measurable_space.is_measurable' Ω (probability_space.to_measurable_space Ω)) (S)))) ⊆ {0,x}, { apply set.subset.trans, apply restrict_range_subseteq, have B1A:nonempty Ω := outcome_space_nonempty P, rw @measure_theory.simple_func.range_const ennreal Ω (probability_space.to_measurable_space Ω) B1A x, simp, }, rw @simple_func_integral_superset Ω (@to_measure_space Ω P) (@measure_theory.simple_func.restrict Ω ennreal (probability_space.to_measurable_space Ω) ennreal.has_zero (@measure_theory.simple_func.const Ω ennreal (probability_space.to_measurable_space Ω) x) (@subtype.val (set Ω) (@measurable_space.is_measurable' Ω (probability_space.to_measurable_space Ω)) (S))) {0,x} B1, rw A1, simp, end lemma indicator_expectation_set {Ω:Type*} {P:probability_space Ω} {S:event P}:E[(indicator S)] = (@event_prob Ω P S) := begin rw expected_value_nnreal_def3, rw expected_value_ennreal_def2, rw @indicator_eq_simple_func Ω P S, rw measure_theory.simple_func.lintegral_eq_lintegral, rw integral_simple_func_restrict_const, { simp, rw event_prob_def, rw ← event_val_eq_coe, refl, }, apply one_ne_zero, end lemma indicator_expectation_event {Ω:Type*} {P:probability_space Ω} {S:event P}:E[(indicator S)] = Pr[S] := begin rw indicator_expectation_set, end ---------- Unproven lemmas, all focusing on trying to get the PAC bound. --------------------------- lemma ennreal_generate_from:(borel ennreal) = measurable_space.generate_from {s | ∃a, s = {b | a < b} ∨ s = {b | b < a}} := begin apply borel_eq_generate_from_of_subbasis, refl, end lemma generate_measurable_iff_is_measurable {Ω:Type*} (B:set (set Ω)) (U:set Ω): measurable_space.generate_measurable B U ↔ @is_measurable Ω (measurable_space.generate_from B) U := begin unfold is_measurable, unfold measurable_space.generate_from, end lemma ennreal_is_measurable_of_generate_measurable (U:set ennreal): measurable_space.generate_measurable {s:set ennreal | ∃a, s = {b | a < b} ∨ s = {b | b < a}} U ↔ is_measurable U := begin have A1:is_measurable U = @is_measurable ennreal (borel ennreal) U := rfl, rw A1, rw ennreal_generate_from, rw generate_measurable_iff_is_measurable, end lemma Iio_empty:@set.Iio ennreal _ 0 = ∅ := begin unfold set.Iio, simp, end lemma Ioi_empty:@set.Ioi ennreal _ ⊤ = ∅ := begin unfold set.Ioi, simp, end lemma Iio_in_ennreal_subbasis {t:ennreal}: (set.Iio t) ∈ {s:set ennreal| ∃a, s = {b | a < b} ∨ s = {b | b < a}} := begin simp, apply exists.intro t, right, refl, end lemma Ioi_in_ennreal_subbasis {t:ennreal}: (set.Ioi t) ∈ {s:set ennreal| ∃a, s = {b | a < b} ∨ s = {b | b < a}} := begin simp, apply exists.intro t, left, refl, end lemma Iic_compl_Ioi {α : Type*} [linear_order α] {a:α}: (set.Iic a)=(set.Ioi a)ᶜ := begin unfold set.Iic, unfold set.Ioi, ext,split;intro A1;simp;simp at A1;apply A1, end lemma Ici_compl_Iio {α : Type*} [linear_order α] {a:α}: (set.Ici a)=(set.Iio a)ᶜ := begin unfold set.Ici, unfold set.Iio, ext,split;intro A1;simp;simp at A1;apply A1, end lemma ennreal_is_measurable_Iic {a:ennreal}:is_measurable (set.Iic a) := begin rw ← ennreal_is_measurable_of_generate_measurable, have A1:(set.Iic a)=(set.Ioi a)ᶜ := Iic_compl_Ioi, rw A1, apply measurable_space.generate_measurable.compl, apply measurable_space.generate_measurable.basic, apply Ioi_in_ennreal_subbasis, end lemma ennreal_is_measurable_Iio {a:ennreal}:is_measurable (set.Iio a) := begin rw ← ennreal_is_measurable_of_generate_measurable, apply measurable_space.generate_measurable.basic, apply Iio_in_ennreal_subbasis, end lemma ennreal_is_measurable_Ici {a:ennreal}:is_measurable (set.Ici a) := begin rw ← ennreal_is_measurable_of_generate_measurable, have A1:(set.Ici a)=(set.Iio a)ᶜ := Ici_compl_Iio, rw A1, apply measurable_space.generate_measurable.compl, apply measurable_space.generate_measurable.basic, apply Iio_in_ennreal_subbasis, end lemma ennreal_is_measurable_Ioi {a:ennreal}:is_measurable (set.Ioi a) := begin rw ← ennreal_is_measurable_of_generate_measurable, apply measurable_space.generate_measurable.basic, apply Ioi_in_ennreal_subbasis, end lemma ennreal_measurable_introh (f:ennreal → ennreal): (∀ (y:ennreal),is_measurable (f ⁻¹' (set.Iio y))) → (∀ (y:ennreal),is_measurable (f ⁻¹' (set.Ioi y))) → measurable f := begin intros A1 A2, apply generate_from_measurable, symmetry, apply ennreal_generate_from, intros B A3, cases A3 with s A4, cases A4, { rw A4, apply A2, }, { rw A4, apply A1, }, end lemma ennreal_measurable_intro (f:ennreal → ennreal): (∀ (y:ennreal),y≠ 0 → is_measurable (f ⁻¹' (set.Iio y))) → (∀ (y:ennreal),y≠ ⊤ → is_measurable (f ⁻¹' (set.Ioi y))) → measurable f := begin intros A1 A2, apply ennreal_measurable_introh, { intro y, have A3:(y = 0) ∨ (y ≠ 0) := classical.em (y=0), cases A3, { rw A3, rw Iio_empty, simp, }, { apply A1, apply A3, } }, { intro y, have A3:(y = ⊤) ∨ (y ≠ ⊤) := classical.em (y=⊤), cases A3, { rw A3, rw Ioi_empty, simp, }, { apply A2, apply A3, } }, end lemma classical.double_negation_elimination {P:Prop}:¬ ¬ P → P := begin intro A1, have A2:P ∨ ¬ P := classical.em P, cases A2, { exact A2, }, { exfalso, apply A1, exact A2, } end lemma subset_of_not_exists_in_diff {α:Type*} {S T:set α}:(¬ (∃ a:α, a∈ T \ S)) → (T⊆ S) := begin intro A1, rw set.subset_def, have A2:∀ a:α, ¬ (a∈ T \ S) := forall_not_of_not_exists A1, intros x A3, have A4:x∉ T \ S := A2 x, simp at A4, apply A4 A3, end lemma in_notin_or_notin_in_or_eq {α:Type*} {S T:set α}: (∃ a:α, a∈ S \ T) ∨ (∃ a:α, a∈ T \ S) ∨ S = T := begin have A1:(∃ a:α, a∈ S \ T) ∨ ¬ (∃ a:α, a∈ S \ T), { apply classical.em, }, have A2:(∃ a:α, a∈ T \ S) ∨ ¬ (∃ a:α, a∈ T \ S), { apply classical.em, }, cases A1, { left, apply A1, }, { cases A2, { right,left, apply A2, }, right,right, apply set.subset.antisymm, { apply subset_of_not_exists_in_diff A1, }, { apply subset_of_not_exists_in_diff A2, } }, end lemma in_notin_or_notin_in_of_ne {α:Type*} {S T:set α}:S≠ T → ((∃ a:α, a∈ S \ T) ∨ (∃ a:α, a∈ T \ S)) := begin intros A1, have A2:((∃ a:α, a∈ S \ T) ∨ (∃ a:α, a∈ T \ S) ∨ S = T ) := in_notin_or_notin_in_or_eq, cases A2, { left, apply A2, }, cases A2, { right, apply A2, }, { exfalso, apply A1, apply A2, } end --Classical. lemma exists_notin_of_ne_set_univ {α:Type*} {S:set α}:S ≠ set.univ → (∃ x, x∉ S) := begin intro A1, have A2:((∃ a:α, a∈ S \ set.univ) ∨ (∃ a:α, a∈ set.univ \ S)) :=in_notin_or_notin_in_of_ne A1, cases A2;cases A2 with a A3;simp at A3, { exfalso, apply A3, }, { apply exists.intro a, exact A3, } end lemma false_of_le_of_lt {α:Type*} [linear_order α] {x y:α}:(x < y) → (y ≤ x) → false := begin intros A1 A2, apply not_le_of_lt A1, apply A2, end lemma ennreal_monotone_inv (f:ennreal → ennreal) (x y:ennreal): monotone f → f x < f y → x < y := begin intros A1 A2, apply classical.by_contradiction, intro A3, have A4:f y ≤ f x, { apply A1, apply le_of_not_lt A3, }, apply false_of_le_of_lt A2 A4, end lemma ennreal_monotone_bound_le_Sup (f:ennreal → ennreal) (x' y:ennreal): monotone f → {x:ennreal|f x < y} ≠ set.univ → x'∈ {x:ennreal|f x < y} → x' ≤ Sup {x:ennreal|f x < y} := begin intros AX A1 A2, have A4:(bdd_above {x:ennreal|f x < y}), { unfold bdd_above, unfold upper_bounds, have A4A:(∃ z, z∉ {x:ennreal|f x < y}), { apply exists_notin_of_ne_set_univ, apply A1, }, cases A4A with z A4B, apply exists.intro z, simp, simp at A4B, intros a A4C, apply @le_of_lt ennreal _ a z, apply ennreal_monotone_inv, unfold monotone at AX, apply AX, apply lt_of_lt_of_le, apply A4C, apply A4B, }, apply le_cSup A4, exact A2, end lemma ennreal_monotone_bound_Inf_le (f:ennreal → ennreal) (x' y:ennreal): monotone f → {x:ennreal|y < f x} ≠ set.univ → x'∈ {x:ennreal|y < f x} → Inf {x:ennreal|y < f x} ≤ x' := begin intros AX A1 A2, have A4:(bdd_below {x:ennreal|y < f x}), { unfold bdd_below, unfold lower_bounds, have A4A:(∃ z, z∉ {x:ennreal|y < f x}), { apply exists_notin_of_ne_set_univ, apply A1, }, cases A4A with z A4B, apply exists.intro z, simp, simp at A4B, intros a A4C, apply @le_of_lt ennreal _ z a, apply ennreal_monotone_inv, unfold monotone at AX, apply AX, apply lt_of_le_of_lt, apply A4B, apply A4C, }, apply @cInf_le ennreal _ {x:ennreal|y < f x}, apply A4, exact A2, end /- Given an order topology (which is also ???), a monotone function f is borel measurable. First, find the image of f. Given [0,y), find all x such that f x < y. If this is all x or none of x, then we are done. Otherwise, since the ennreal are a conditionally complete lattice, there exists a supremum on such x, we'll call x'. If f x' < y, then [0,x'] is the measurable set. If f x' = y, then for any x < x', f x < y, otherwise x' would be the supremum. Thus, [0,x') would be the open set. A similar proof works for the preimage of (y,∞]. -/ lemma ennreal_monotone_measurable (f:ennreal → ennreal): monotone f → measurable f := begin intro A1, apply ennreal_measurable_intro;intros y A2, { let S := {x:ennreal|f x < y}, begin have B1:S = {x:ennreal|f x < y} := rfl, have C1:f ⁻¹' (set.Iio y) = S := rfl, rw C1, have B2:decidable (S=set.univ), { apply classical.prop_decidable, }, have B3:S.nonempty ∨ (S=∅), { rw or.comm, apply set.eq_empty_or_nonempty, }, have B4:decidable (y ≤ f (Sup S)), { apply classical.prop_decidable, }, cases B2, cases B3, { -- ¬S = set.univ, ¬S = ∅ ⊢ is_measurable (f ⁻¹' set.Iio y) cases B4, { have B4A:f (Sup S) < y, begin apply lt_of_not_ge, apply B4, end, have B4B:S = set.Iic (Sup S), { rw B1, ext z,simp;split;intros B4BA, { apply ennreal_monotone_bound_le_Sup, exact A1, apply B2, apply B4BA, }, { rw ← B1 at B4BA, have B4BB:f z ≤ f (Sup S), { apply A1, apply B4BA, }, apply lt_of_le_of_lt, apply B4BB, apply B4A, } }, rw B4B, apply ennreal_is_measurable_Iic, }, { have B4A:S = set.Iio (Sup S), { ext,split;intro B4AB, { simp, apply lt_of_le_of_ne, { apply ennreal_monotone_bound_le_Sup, exact A1, apply B2, apply B4AB, }, { intro B4AD, rw ← B4AD at B4, simp at B4AB, apply false_of_le_of_lt B4AB B4, }, }, { simp, simp at B4AB, apply classical.by_contradiction, intro D1, have D2:y≤ f x, { apply le_of_not_lt D1, }, have D3:Sup S ≤ x, { apply cSup_le B3, intros b D3A, simp at D3A, have D3B:b < x, { apply ennreal_monotone_inv, apply A1, apply lt_of_lt_of_le, apply D3A, apply D2, }, apply le_of_lt D3B, }, apply false_of_le_of_lt B4AB D3, } }, rw B4A, apply ennreal_is_measurable_Iio, } }, { -- S = ∅ ⊢ is_measurable (f ⁻¹' set.Iio y) rw B3, apply is_measurable.empty, }, { -- S = set.univ ⊢ is_measurable (f ⁻¹' set.Iio y) rw B2, apply is_measurable.univ, }, end }, { let S := {x:ennreal|y < f x}, begin have B1:S = {x:ennreal|y < f x} := rfl, have C1:f ⁻¹' (set.Ioi y) = S := rfl, rw C1, have B2:decidable (S=set.univ), { apply classical.prop_decidable, }, have B3:S.nonempty ∨ (S=∅), { rw or.comm, apply set.eq_empty_or_nonempty, }, have B4:decidable (f (Inf S)≤ y), { apply classical.prop_decidable, }, cases B2, cases B3, { -- ¬S = set.univ,¬S = ∅ ⊢ is_measurable (f ⁻¹' set.Iio y) cases B4, { have B4A:y < f (Inf S), begin apply lt_of_not_ge, apply B4, end, have B4B:S = set.Ici (Inf S), { rw B1, ext z,simp;split;intros B4BA, { apply ennreal_monotone_bound_Inf_le, exact A1, apply B2, apply B4BA, }, { rw ← B1 at B4BA, have B4BB:f (Inf S) ≤ f z, { apply A1, apply B4BA, }, apply lt_of_lt_of_le, apply B4A, apply B4BB, } }, rw B4B, apply ennreal_is_measurable_Ici, }, { have B4A:S = set.Ioi (Inf S), { ext,split;intro B4AB, { simp, apply lt_of_le_of_ne, { apply ennreal_monotone_bound_Inf_le, exact A1, apply B2, apply B4AB, }, { intro B4AD, rw B4AD at B4, simp at B4AB, apply false_of_le_of_lt B4AB B4, }, }, { simp, simp at B4AB, apply classical.by_contradiction, intro D1, have D2:f x ≤ y, { apply le_of_not_lt D1, }, have D3:x ≤ Inf S, { apply le_cInf B3, intros b D3A, simp at D3A, have D3B:x < b, { apply ennreal_monotone_inv, apply A1, apply lt_of_le_of_lt, apply D2, apply D3A, }, apply le_of_lt D3B, }, apply false_of_le_of_lt B4AB D3, } }, rw B4A, apply ennreal_is_measurable_Ioi, } }, { -- S = ∅ ⊢ is_measurable (f ⁻¹' set.Iio y) rw B3, apply is_measurable.empty, }, { -- S = set.univ ⊢ is_measurable (f ⁻¹' set.Iio y) rw B2, apply is_measurable.univ, }, end } end lemma ennreal_scalar_mul_monotone (k:ennreal):monotone (λ x, k * x) := begin apply ennreal.mul_left_mono, end /- WAIT: alternative proof. Scalar multiplication is monotone. Given an order topology (which is also ???), a monotone function f is borel measurable. First, find the image of f. Given [0,y), find all x such that f x < y. If this is all x or none of x, then we are done. Otherwise, since the ennreal are a conditionally complete lattice, there exists a supremum on such x, we'll call x'. If f x' < y, then [0,x'] is the measurable set. If f x' = y, then for any x < x', f x < y, otherwise x' would be the supremum. Thus, [0,x') would be the open set. A similar proof works for the preimage of (y,∞]. This is the simplest way to prove that scalar multiplication is measurable. Basically, we can consider the preimage of sets of the form (x,∞] and [0,x), and prove that they are measurable. The preimage of [0,0) and (∞,∞] is ∅. 1. If k = 0, then the preimage of [0,x) is set.univ. The preimage of (x,∞] is ∅. 2. If k = ∞, then the preimage of [0,x) is {0}. The preimage of (x,∞] is (0,∞]. 3. Otherwise, the preimage of [0,x) is [0,x/k). The preimage of (x,∞] is (x/k,∞]. -/ lemma ennreal_scalar_mul_measurable (k:ennreal):measurable (λ x, k * x) := begin apply ennreal_monotone_measurable, apply ennreal.mul_left_mono, end --TODO: this represents a semi-module. noncomputable def ennreal_scalar_measurable_fun (k:ennreal):(borel ennreal) →ₘ (borel ennreal) := { val := λ x, k * x, property := ennreal_scalar_mul_measurable k, } noncomputable def scalar_mul_measurable_fun {Ω:Type*} {MΩ:measurable_space Ω} (k:ennreal) (X:MΩ →ₘ (borel ennreal)):(MΩ →ₘ (borel ennreal)) := (ennreal_scalar_measurable_fun k) ∘m X noncomputable def scalar_mul_rv {Ω:Type*} {P:probability_space Ω} (k:ennreal) (X:P →ᵣ (borel ennreal)):(P →ᵣ (borel ennreal)) := (ennreal_scalar_measurable_fun k) ∘r X def scalar_mul_rv_val_def {Ω:Type*} {P:probability_space Ω} (k:ennreal) (X:P →ᵣ (borel ennreal)): (scalar_mul_rv k X).val = λ ω:Ω, k * (X.val ω) := rfl lemma nnreal_scalar_mul_to_ennreal {Ω:Type*} (p:probability_space Ω) (k:nnreal) (X:random_variable p (borel nnreal)): nnreal_to_ennreal_random_variable ((to_nnreal_rv (k)) * X) = scalar_mul_rv (k:ennreal) (nnreal_to_ennreal_random_variable X) := begin apply subtype.eq, rw scalar_mul_rv_val_def, rw nnreal_to_ennreal_random_variable_val_def, rw nnreal_to_ennreal_random_variable_val_def, rw nnreal_random_variable_mul_val_def, rw to_nnreal_rv_val_def, simp, end lemma ennreal_scalar_expected_value {Ω:Type*} (p:probability_space Ω) (k:ennreal) (X:random_variable p (borel ennreal)): E[scalar_mul_rv k X] = k * E[X] := begin rw expected_value_ennreal_def, rw scalar_mul_rv_val_def, rw measure_theory.lintegral_const_mul, rw expected_value_ennreal_def, apply X.property end -----Our TWO TARGET LEMMAS-------------------------------------------------------------------------- /- Okay, here is the plan for this one, because solving this one the "right" way will take forever. 1. First of all, we define a scalar multiplier on ennreal measurable functions and ennreal random variables. 2. Then, we show how the cast to ennreal results in such a random variable. 3. Then, we show how such the scalar multiplier yields a scalar multiplier on the expectation using measure_theory.lintegral_const_mul -/ lemma scalar_expected_value {Ω:Type*} (p:probability_space Ω) (X:random_variable p (borel nnreal)) (k:nnreal):E[X * (to_nnreal_rv (k))] = E[X] * (k:ennreal) := begin rw mul_comm, rw mul_comm _ (k:ennreal), rw expected_value_nnreal_def, rw nnreal_scalar_mul_to_ennreal, apply ennreal_scalar_expected_value, end lemma linear_count_finset_rv {Ω β:Type*} {P:probability_space Ω} (S:finset β) (X:β → event P):E[count_finset_rv S X] = S.sum (λ k, (Pr[X k]:ennreal)) := begin unfold count_finset_rv, unfold count_finset, have A1:decidable_eq β := classical.decidable_eq β, rw @finset_sum_measurable_fun_linear Ω β P S A1, have A2:(λ (k : β), E[indicator (X k)])=(λ (k : β), ↑Pr[X k]), { ext k, rw indicator_expectation_event, }, rw A2, end lemma pos_nnreal_and_neg_nnreal_of_expected_value_exists {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real):(expected_value_exists X) → E[pos_nnreal X] < ⊤ ∧ E[neg_nnreal X] < ⊤:= begin unfold expected_value_exists, unfold absolute_expected_value_real, rw absolute_nnreal_pos_nnreal_plus_neg_nnreal, rw ← expected_value_nnreal_def4, rw expectation_add_nnreal, intro A1, rw with_top.add_lt_top at A1, apply A1, end lemma pos_nnreal_of_expected_value_exists {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real):(expected_value_exists X) → E[pos_nnreal X] < ⊤ := begin intro A1, have A2:E[pos_nnreal X] < ⊤ ∧ E[neg_nnreal X] < ⊤, { apply pos_nnreal_and_neg_nnreal_of_expected_value_exists, apply A1, }, apply A2.left, end lemma neg_nnreal_of_expected_value_exists {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real):(expected_value_exists X) → E[neg_nnreal X] < ⊤ := begin intro A1, have A2:E[pos_nnreal X] < ⊤ ∧ E[neg_nnreal X] < ⊤, { apply pos_nnreal_and_neg_nnreal_of_expected_value_exists, apply A1, }, apply A2.right, end noncomputable def real_CDF {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real) (x:ℝ):nnreal := Pr[X ≤ᵣ x] -------------------------------Find a home for these theorems.-------------------------------- lemma pr_empty_zero {Ω α:Type*} {p:probability_space Ω} [M:measurable_space α] {X:p →ᵣ M} {E:@measurable_set α M}:E.val = ∅ → (X ∈ᵣ E ) = @event_empty Ω p := begin intro A1, apply event.eq, rw rv_event_val_def, ext ω, rw A1, split;intros A2, { simp at A2, exfalso, apply A2, }, { exfalso, apply A2, } end --Unused, except below. lemma pr_empty_zero2 {Ω α:Type*} {p:probability_space Ω} [M:measurable_space α] {E:event p}:E = @event_empty Ω p → Pr[E] = 0 := begin intro A1, rw A1, rw Pr_event_empty, end --Unused. lemma pr_empty_zero3 {Ω α:Type*} {p:probability_space Ω} [M:measurable_space α] {X:p →ᵣ M} {E:@measurable_set α M}:E.val = ∅ → Pr[X ∈ᵣ E ] = 0 := begin intro A1, apply @pr_empty_zero2 Ω α p M, apply pr_empty_zero, apply A1, end lemma set.disjoint_preimage {Ω α:Type*} {X:Ω → α} {A B:set α} : (A ∩ B ⊆ ∅ ) → ((set.preimage X (A)) ∩ (set.preimage X (B)) ⊆ ∅ ) := begin intros A1, rw set.subset_def, intros ω A2, exfalso, simp at A2, rw set.subset_def at A1, have A3 := A1 (X ω), apply A3, simp, apply A2, end lemma set.pairwise_disjoint_preimage {Ω α β:Type*} [decidable_eq β] {X:Ω → α} {f:β → set α} : (∀ (i j : β), i ≠ j → f i ∩ f j ⊆ ∅ ) → (∀ (i j : β), i ≠ j → (set.preimage X (f i)) ∩ (set.preimage X (f j)) ⊆ ∅ ) := begin intros A1 i j A2, apply set.disjoint_preimage (A1 i j A2), end lemma measure_Union2 {Ω α:Type*} {p:probability_space Ω} {M:measurable_space α} {X:Ω → α} {f:ℕ → set α} : (measurable X) → (∀ (i j : ℕ), i ≠ j → f i ∩ f j ⊆ ∅ ) → (∀ n, is_measurable (f n)) → p.volume.measure_of (X ⁻¹' ⋃ (i : ℕ), f i) =∑' n:ℕ, p.volume.measure_of (X ⁻¹' f n) := begin intros A1 A2 A3, rw set.preimage_Union, apply @measure_theory.measure_Union Ω _ measure_theory.measure_space.volume ℕ _ (λ n:ℕ, (set.preimage X (f n))), apply set.pairwise_disjoint_preimage A2, intro i, apply measurable.preimage A1 (A3 i), end lemma induction_on_inter2 {α:Type*} {M:measurable_space α} {S:set (set α)} {P:measurable_set M → Prop}: (M = measurable_space.generate_from S) → (∀ t₁ t₂:(set α), t₁ ∈ S → t₂ ∈ S → set.nonempty (t₁ ∩ t₂) → t₁ ∩ t₂ ∈ S) → (P ∅) → (∀ E:measurable_set M, P E → P (Eᶜ)) → (∀ (f : ℕ → measurable_set M), (∀ (i j : ℕ), i ≠ j → (measurable_inter (f i) (f j)).val ⊆ ∅) → (∀ (i : ℕ), P (f i)) → P (measurable_Union f)) → (∀ E:measurable_set M, E.val ∈ S → P E ) → (∀ E:measurable_set M, P E) := begin intros A1 A2 B1 B2 B3 A3, let P2 := λ T:set α, ∃ H:is_measurable T, P ⟨T, H⟩, begin have A4:P2 = λ T:set α, ∃ H:is_measurable T, P ⟨T, H⟩ := rfl, have A5:(∀ T:set α, is_measurable T → P2 T), { apply measurable_space.induction_on_inter, apply A1, apply A2, { rw A4, apply exists.intro is_measurable.empty, apply B1, }, { intros T A5A, rw A4, have A5B:is_measurable T, { rw A1, apply measurable_space.generate_measurable.basic, apply A5A, }, apply exists.intro A5B, apply A3, simp, apply A5A, }, { intros T A5C, rw A4, intro A5D, cases A5D with A5E A5F, have A5G:= (is_measurable.compl A5E), apply exists.intro A5G, have A5H:(measurable_set.mk A5G)=(measurable_set.mk A5E)ᶜ, { unfold measurable_set.mk, apply subtype.eq, rw measurable_set_neg_def, }, unfold measurable_set.mk at A5H, rw A5H, apply B2, apply A5F, }, { intros f A5J A5K A5L, have A5M:is_measurable (⋃ (i:ℕ), f i), { apply is_measurable.Union, intro b, apply A5K, }, rw A4, apply exists.intro A5M, let g := λ (i:ℕ), @measurable_set.mk α M (f i) (A5K i), let V := measurable_Union g, begin have A5N:g = λ (i:ℕ), @measurable_set.mk α M (f i) (A5K i) := rfl, have A5O:V = measurable_Union g := rfl, have A5P:@measurable_set.mk α M (⋃ (i:ℕ), f i) A5M = V, { apply subtype.eq, rw A5O, unfold measurable_set.mk, simp, rw ← measurable_set_val_eq_coe, rw measurable_Union_val_def, ext ω,split;intro A5PA;simp at A5PA;cases A5PA with i A5PA;simp; apply exists.intro i;have A5PB:f i = (g i).val := rfl, { rw ← measurable_set_val_eq_coe, rw ← A5PB, apply A5PA, }, { rw A5PB, apply A5PA, }, }, unfold measurable_set.mk at A5P, rw A5P, rw A5O, apply B3, { intros i j A5Q, rw measurable_inter_val_def, have A5R:(g i).val = f i := rfl, have A5S:(g j).val = f j := rfl, rw A5R, rw A5S, apply A5J, apply A5Q, }, { intro i, have A5T:=A5L i, rw A4 at A5T, cases A5T with A5U A5V, have A5W:g i = ⟨f i, A5U⟩ := rfl, rw A5W, apply A5V, }, end }, }, intro E, cases E, have A6 := A5 E_val E_property, rw A4 at A6, cases A6 with A7 A8, have A9:(⟨E_val, E_property⟩:measurable_set M) = (⟨E_val, A7⟩:measurable_set M), { apply subtype.eq, refl, }, rw A9, apply A8, end end lemma nnreal.sum_subst {β:Type*} [encodable β] {f g:β → nnreal}:(f = g) → (∑' (b:β), f b) = (∑' (b:β), g b) := begin intro A1, rw A1, end lemma random_variable_identical_generate_from {Ω α:Type*} {p:probability_space Ω} {M:measurable_space α} {S:set (set α)} {X Y:p →ᵣ M}: (M = measurable_space.generate_from S) → (∀ (t₁ t₂ : set α), t₁ ∈ S → t₂ ∈ S → set.nonempty (t₁ ∩ t₂) → t₁ ∩ t₂ ∈ S) → (∀ E:measurable_set M, E.val ∈ S → Pr[X ∈ᵣ E] = Pr[Y ∈ᵣ E]) → (∀ E:measurable_set M, Pr[X ∈ᵣ E] = Pr[Y ∈ᵣ E]) := begin intros A1 A2, apply induction_on_inter2, { apply A1, }, { apply A2, }, { repeat {rw rv_event_empty}, }, { intros E A1, repeat {rw rv_event_compl}, repeat {rw neg_eq_not}, repeat {rw ← Pr_one_minus_eq_not}, rw A1, }, { intros f A3 A4, repeat {rw rv_event_measurable_Union}, repeat {rw measurable_Union_eq_any}, repeat {rw Pr_eany_sum}, rw nnreal.sum_subst, --rw @sum_subst ℕ _ (λ b:ℕ, Pr[X ∈ᵣ f b]), --sorry { ext i, rw A4 i, }, apply set.pairwise_disjoint_preimage, { intros i j A5, have A6 := A3 i j A5, rw measurable_inter_val_def at A6, apply A6, }, apply set.pairwise_disjoint_preimage, { intros i j A5, have A6 := A3 i j A5, rw measurable_inter_val_def at A6, apply A6, }, }, end lemma random_variable_identical_generate_from2 {Ω α:Type*} {p:probability_space Ω} {M:measurable_space α} {S:set (set α)} {X Y:p →ᵣ M}: (M = measurable_space.generate_from S) → (∀ (t₁ t₂ : set α), t₁ ∈ S → t₂ ∈ S → set.nonempty (t₁ ∩ t₂) → t₁ ∩ t₂ ∈ S) → (∀ E:measurable_set M, E.val ∈ S → Pr[X ∈ᵣ E] = Pr[Y ∈ᵣ E]) → @random_variable_identical Ω p α M X Y := begin intros AX A1 A2, unfold random_variable_identical, apply @random_variable_identical_generate_from Ω α p M S X Y AX A1 A2, end lemma generate_measurable_finite_union {α:Type*} {s:set (set α)} {f:ℕ → set α} {n:ℕ}: (∀ n:ℕ, (measurable_space.generate_measurable s (f n))) → measurable_space.generate_measurable s (set.sUnion (set.image f {i:ℕ|i < n})) := begin let g:= λ i:ℕ, if (i < n) then (f i) else ∅, begin intro A1, have A2:g = λ i:ℕ, if (i < n) then (f i) else ∅ := rfl, have A3:(⋃ j:ℕ, g j) = (set.sUnion (set.image f {i:ℕ|i < n})), { ext ω,split;intro A4, { simp at A4, cases A4 with i A4, rw A2 at A4, simp at A4, have A4A:i < n, { apply decidable.by_contradiction, intro A4A1, rw if_neg at A4, apply A4, apply A4A1, }, rw if_pos at A4, simp, apply exists.intro i, split, { apply A4A, }, { apply A4, }, apply A4A, }, { simp at A4, cases A4 with i A4, simp, apply exists.intro i, rw A2, simp, rw if_pos, apply A4.right, apply A4.left, }, }, rw ← A3, apply measurable_space.generate_measurable.union, intro i, rw A2, simp, have A5:(i < n) ∨ ¬(i < n) := decidable.em (i < n), cases A5, { rw if_pos A5, apply A1, }, { rw if_neg A5, apply measurable_space.generate_measurable.empty, }, end end lemma set_range_Iic_closed {t₁ t₂ : set ℝ}: t₁ ∈ set.range (@set.Iic ℝ _)→ t₂ ∈ set.range (@set.Iic ℝ _) → set.nonempty (t₁ ∩ t₂) → t₁ ∩ t₂ ∈ set.range (@set.Iic ℝ _):= begin intros A1 A2 A3, simp at A1, cases A1 with y1 A1, simp at A2, cases A2 with y2 A2, subst t₁, subst t₂, rw set.Iic_inter_Iic, simp, end lemma set_Iic_eq_CDF {Ω:Type*} {p:probability_space Ω} {X:p →ᵣ borel real} {y:ℝ} {E:measurable_set (borel ℝ)}:E.val = set.Iic y → (Pr[X ∈ᵣ E] = (real_CDF X y)) := begin intro A1, unfold real_CDF, rw ← ennreal.coe_eq_coe, repeat { rw event_prob_def }, rw event_le_val_def, rw coe_random_variable_of_real_val_def, rw rv_event_val_def, rw A1, unfold set.Iic, simp, end --set_option pp.implicit true lemma real.is_measurable_Iic (x:ℝ):is_measurable (set.Iic x) := begin rw real_measurable_space_def, apply is_measurable_Iic, end lemma real.is_measurable_Ioc (x y:ℝ):is_measurable (set.Ioc x y) := begin rw real_measurable_space_def, apply is_measurable_Ioc, end lemma real_CDF_identical {Ω:Type*} {p:probability_space Ω} {X Y:p →ᵣ borel real}: ((real_CDF X) = (real_CDF Y)) → random_variable_identical X Y := begin intro A1, have A2:borel ℝ = measurable_space.generate_from (set.range set.Iic), { apply borel_eq_generate_Iic, }, apply random_variable_identical_generate_from2 A2, apply set_range_Iic_closed, intros E A3, simp at A3, cases A3 with y A3, have A4:E.val = set.Iic y, { rw A3, rw measurable_set_val_eq_coe, }, repeat {rw set_Iic_eq_CDF A4}, rw A1, end noncomputable def real_joint_CDF {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real) (Y:p →ᵣ borel real) (x y:ℝ):nnreal := Pr[(X ≤ᵣ x) ∧ₑ (Y ≤ᵣ y)] def measurable_set.Iic (x:ℝ):measurable_set (borel ℝ) := { val := set.Iic x, property := real.is_measurable_Iic x, } def measurable_set.Ioc (x y:ℝ):measurable_set (borel ℝ) := { val := set.Ioc x y, property := real.is_measurable_Ioc x y, } lemma measurable_set.Iic_val_def {x:ℝ}: (measurable_set.Iic x).val = set.Iic x := rfl lemma measurable_set.Ioc_val_def {x y:ℝ}: (measurable_set.Ioc x y).val = set.Ioc x y := rfl noncomputable def real_joint_set (x y:ℝ): measurable_set ((borel real) ×ₘ (borel real)) := prod_measurable_set (measurable_set.Iic x) (measurable_set.Iic y) lemma mem_real_measurable_set_Iic_def {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real) (x:ℝ):X ∈ᵣ (measurable_set.Iic x) = X ≤ᵣ x := begin apply event.eq, rw rv_event_val_def, rw measurable_set.Iic_val_def, rw event_le_val_def, unfold set.Iic, simp, rw ← random_variable_val_eq_coe, rw ← random_variable_val_eq_coe, rw coe_random_variable_of_real_val_def, end lemma real_joint_CDF_alt {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel real) (Y:p →ᵣ borel real) (x y:ℝ): real_joint_CDF X Y x y = Pr[(X ×ᵣ Y) ∈ᵣ real_joint_set x y] := begin unfold real_joint_set, rw mem_prod_random_variable_prod_measurable_set, unfold real_joint_CDF, repeat {rw mem_real_measurable_set_Iic_def}, end lemma prod_set_Iic_eq_CDF {Ω:Type*} {p:probability_space Ω} {X:p →ᵣ borel real} {x:ℝ} {Y:p →ᵣ borel real} {y:ℝ} {E:measurable_set (borel ℝ ×ₘ borel ℝ)}: E.val = set.prod (set.Iic x) (set.Iic y) → (Pr[(X ×ᵣ Y) ∈ᵣ E] = (real_joint_CDF X Y x y)) := begin intro A1, rw real_joint_CDF_alt, rw ← ennreal.coe_eq_coe, unfold real_joint_set, repeat { rw event_prob_def, rw rv_event_val_def }, rw A1, rw prod_measurable_set_val_def, repeat {rw measurable_set.Iic_val_def}, end lemma real.Iic_covers:set.sUnion (set.range (λ n:ℕ,set.Iic (n:ℝ))) = set.univ := begin ext x,split;intro A1, { apply set.mem_univ, }, { simp, have A2 := exists_nat_gt x, cases A2 with i A2, apply exists.intro i, apply le_of_lt, apply A2, }, end lemma set.mem_range_elim {α β:Type*} {f:α → β} {b:β}: b∈ set.range f → ∃ a:α, f a = b := begin intro A1, simp at A1, apply A1, end lemma prod_borel_R_eq_Iic: (borel ℝ) ×ₘ (borel ℝ) = measurable_space.generate_from {S|∃ x y:ℝ, S = set.prod (set.Iic x) (set.Iic y)} := begin repeat {rw borel_eq_generate_Iic}, unfold prod_space, have A1:set.countable (set.range (λ n:ℕ,set.Iic (n:ℝ))), { apply set.countable_range, }, have A2:(set.range (λ n:ℕ,set.Iic (n:ℝ))) ⊆ set.range set.Iic, { rw set.subset_def, intros S A2A, simp at A2A, simp, cases A2A with y A2A, apply exists.intro (y:ℝ), apply A2A, }, have A3:set.sUnion (set.range (λ n:ℕ,set.Iic (n:ℝ))) = set.univ := real.Iic_covers, rw @prod_measurable_space_def2 _ _ _ _ (set.range (λ n:ℕ,set.Iic (n:ℝ))) (set.range (λ n:ℕ,set.Iic (n:ℝ))) A1 A1 A2 A2 A3 A3, have A4: {U : set (ℝ × ℝ) | ∃ (A ∈ set.range (@set.Iic ℝ _)), ∃ (B ∈ set.range (@set.Iic ℝ _)), U = set.prod A B} = {S : set (ℝ × ℝ) | ∃ (x y : ℝ), S = set.prod (@set.Iic ℝ _ x) (@set.Iic ℝ _ y)}, { ext p;split;intro A4A;simp, { cases A4A with A A4A, cases A4A with A4A A4B, cases A4B with B A4B, cases A4B with A4B A4C, subst p, --cases A4A with x A4A, --unfold set.range at A4A, have A4D := @set.mem_range_elim (ℝ) (set ℝ) (set.Iic) A A4A, cases A4D with x A4D, apply exists.intro x, have A4E := @set.mem_range_elim (ℝ) (set ℝ) (set.Iic) B A4B, cases A4E with y A4E, apply exists.intro y, rw A4D, rw A4E, }, { simp at A4A, apply A4A, }, }, rw A4, end lemma prod_set_range_Iic_closed {t₁ t₂ : set (ℝ × ℝ)}: t₁ ∈ {S : set (ℝ × ℝ) | ∃ (x y : ℝ), S = set.prod (set.Iic x) (set.Iic y)} → t₂ ∈ {S : set (ℝ × ℝ) | ∃ (x y : ℝ), S = set.prod (set.Iic x) (set.Iic y)} → set.nonempty (t₁ ∩ t₂) → t₁ ∩ t₂ ∈ {S : set (ℝ × ℝ) | ∃ (x y : ℝ), S = set.prod (set.Iic x) (set.Iic y)} := begin intros A1 A2 A3, cases A1 with x1 A1, cases A1 with y1 A1, subst t₁, cases A2 with x2 A2, cases A2 with y2 A2, subst t₂, rw set.prod_inter_prod, repeat {rw set.Iic_inter_Iic}, simp, apply exists.intro (x1 ⊓ x2), apply exists.intro (y1 ⊓ y2), refl, end lemma real_joint_CDF_identical {Ω:Type*} {p:probability_space Ω} {X1 X2 Y1 Y2:p →ᵣ borel real}: ((real_joint_CDF X1 X2) = (real_joint_CDF Y1 Y2)) → random_variable_identical (X1 ×ᵣ X2) (Y1 ×ᵣ Y2) := begin intro A1, have A2:= prod_borel_R_eq_Iic, apply random_variable_identical_generate_from2 A2, apply prod_set_range_Iic_closed, intros E A3, simp at A3, cases A3 with x A3, cases A3 with y A3, repeat {rw prod_set_Iic_eq_CDF A3}, rw A1, end lemma is_measurable.countable {S:set ℝ}:set.countable S → is_measurable S := begin intro A1, have A2:S = (set.sUnion (set.image singleton S)), { simp, }, rw A2, apply is_measurable.sUnion, apply set.countable.image, apply A1, intro t, intro A3, simp at A3, cases A3 with x A3, cases A3 with A3 A4, subst t, apply is_measurable_singleton, end def measurable_set.of_countable (S:set ℝ) (H:set.countable S):measurable_set (borel ℝ) := { val := S, property := is_measurable.countable H, } def is_countable_support {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel ℝ) (S:set ℝ):Prop := ∃ (H:set.countable S), Pr[X ∈ᵣ (measurable_set.of_countable S H)] = 1 def is_discrete_random_variable {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel ℝ):Prop := ∃ (S:set ℝ), is_countable_support X S def is_probability_mass_function {Ω:Type*} {p:probability_space Ω} (X:p →ᵣ borel ℝ) {S:set ℝ} (f:{x // x ∈ S} → nnreal):Prop := (set.countable S) ∧ (∀ E:measurable_set (borel ℝ), has_sum f (Pr[X∈ᵣ E])) def is_absolutely_continuous_wrt {Ω:Type*} {M:measurable_space Ω} (μ ν:measure_theory.measure Ω):Prop := ∀ A:set Ω, is_measurable A → (ν A = 0) → (μ A = 0) def measure_zero_of_is_absolutely_continuous_wrt {Ω:Type*} {M:measurable_space Ω} (μ ν:measure_theory.measure Ω) (A:set Ω): is_absolutely_continuous_wrt μ ν → is_measurable A → (ν A = 0) → (μ A = 0) := begin intros A1 A2 A3, unfold is_absolutely_continuous_wrt at A1, apply A1 A A2 A3, end
bff31bcd47874d05ac51382216bc925d365e8a18
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world9/level1.lean
106c968c9f2a6dbe606c11831f58c0a493ad2686
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,515
lean
import game.world8.level13 -- hide import game.world3.level9 namespace mynat -- hide /- # Advanced Multiplication World ## Level 1: `mul_pos` Welcome to Advanced Multiplication World! Before attempting this world you should have completed seven other worlds, including Multiplication World and Advanced Addition World. There are four levels in this world. Recall that if `b : mynat` is a hypothesis and you do `cases b with n`, your one goal will split into two goals, namely the cases `b = 0` and `b = succ(n)`. So `cases` here is like a weaker version of induction (you don't get the inductive hypothesis). ## Tricks 1) if your goal is `⊢ X ≠ Y` then `intro h` will give you `h : X = Y` and a goal of `⊢ false`. This is because `X ≠ Y` *means* `(X = Y) → false`. Conversely if your goal is `false` and you have `h : X ≠ Y` as a hypothesis then `apply h` will turn the goal into `X = Y`. 2) if `hab : succ (3 * x + 2 * y + 1) = 0` is a hypothesis and your goal is `⊢ false`, then `exact succ_ne_zero _ hab` will solve the goal, because Lean will figure out that `_` is supposed to be `3 * x + 2 * y + 1`. -/ /- Theorem The product of two non-zero natural numbers is non-zero. -/ theorem mul_pos (a b : mynat) : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := begin [nat_num_game] intros ha hb, intro hab, cases b with b, apply hb, refl, rw mul_succ at hab, apply ha, cases a with a, refl, rw add_succ at hab, exfalso, exact succ_ne_zero _ hab, end end mynat -- hide
66ca2e83dd61ffcbbf6c5d4241231b8d213458de
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/algebra/functions.lean
c545d4bb9db0efdccdbc2ce7e7f486ff96942c52
[ "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
17,326
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.ordered_field universe u definition min {α : Type u} [decidable_linear_order α] (a b : α) : α := if a ≤ b then a else b definition max {α : Type u} [decidable_linear_order α] (a b : α) : α := if a ≤ b then b else a definition abs {α : Type u} [decidable_linear_ordered_comm_group α] (a : α) : α := max a (-a) section open decidable tactic variables {α : Type u} [decidable_linear_order α] private meta def min_tac_step : tactic unit := solve1 $ intros >> `[unfold min max] >> try `[simp [*, if_pos, if_neg]] >> try `[apply le_refl] >> try `[apply le_of_not_le, assumption] meta def tactic.interactive.min_tac (a b : interactive.parse lean.parser.pexpr) : tactic unit := interactive.by_cases (none, ``(%%a ≤ %%b)); min_tac_step lemma min_le_left (a b : α) : min a b ≤ a := by min_tac a b lemma min_le_right (a b : α) : min a b ≤ b := by min_tac a b lemma le_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b := by min_tac a b lemma le_max_left (a b : α) : a ≤ max a b := by min_tac a b lemma le_max_right (a b : α) : b ≤ max a b := by min_tac a b lemma max_le {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c := by min_tac a b lemma eq_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = min a b := le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b)) lemma min_comm (a b : α) : min a b = min b a := eq_min (min_le_right a b) (min_le_left a b) (λ c h₁ h₂, le_min h₂ h₁) lemma min_assoc (a b c : α) : min (min a b) c = min a (min b c) := begin apply eq_min, { apply le_trans, apply min_le_left, apply min_le_left }, { apply le_min, apply le_trans, apply min_le_left, apply min_le_right, apply min_le_right }, { intros d h₁ h₂, apply le_min, apply le_min h₁, apply le_trans h₂, apply min_le_left, apply le_trans h₂, apply min_le_right } end lemma min_left_comm : ∀ (a b c : α), min a (min b c) = min b (min a c) := left_comm (@min α _) (@min_comm α _) (@min_assoc α _) @[simp] lemma min_self (a : α) : min a a = a := by min_tac a a @[ematch] lemma min_eq_left {a b : α} (h : a ≤ b) : min a b = a := begin apply eq.symm, apply eq_min (le_refl _) h, intros, assumption end @[ematch] lemma min_eq_right {a b : α} (h : b ≤ a) : min a b = b := eq.subst (min_comm b a) (min_eq_left h) lemma eq_max {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b := le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂) lemma max_comm (a b : α) : max a b = max b a := eq_max (le_max_right a b) (le_max_left a b) (λ c h₁ h₂, max_le h₂ h₁) lemma max_assoc (a b c : α) : max (max a b) c = max a (max b c) := begin apply eq_max, { apply le_trans, apply le_max_left a b, apply le_max_left }, { apply max_le, apply le_trans, apply le_max_right a b, apply le_max_left, apply le_max_right }, { intros d h₁ h₂, apply max_le, apply max_le h₁, apply le_trans (le_max_left _ _) h₂, apply le_trans (le_max_right _ _) h₂} end lemma max_left_comm : ∀ (a b c : α), max a (max b c) = max b (max a c) := left_comm (@max α _) (@max_comm α _) (@max_assoc α _) @[simp] lemma max_self (a : α) : max a a = a := by min_tac a a lemma max_eq_left {a b : α} (h : b ≤ a) : max a b = a := begin apply eq.symm, apply eq_max (le_refl _) h, intros, assumption end lemma max_eq_right {a b : α} (h : a ≤ b) : max a b = b := eq.subst (max_comm b a) (max_eq_left h) /- these rely on lt_of_lt -/ lemma min_eq_left_of_lt {a b : α} (h : a < b) : min a b = a := min_eq_left (le_of_lt h) lemma min_eq_right_of_lt {a b : α} (h : b < a) : min a b = b := min_eq_right (le_of_lt h) lemma max_eq_left_of_lt {a b : α} (h : b < a) : max a b = a := max_eq_left (le_of_lt h) lemma max_eq_right_of_lt {a b : α} (h : a < b) : max a b = b := max_eq_right (le_of_lt h) /- these use the fact that it is a linear ordering -/ lemma lt_min {a b c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c := or.elim (le_or_gt b c) (assume h : b ≤ c, by min_tac b c) (assume h : b > c, by min_tac b c) lemma max_lt {a b c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c := or.elim (le_or_gt a b) (assume h : a ≤ b, by min_tac a b) (assume h : a > b, by min_tac a b) end section variables {α : Type u} [decidable_linear_ordered_cancel_comm_monoid α] lemma min_add_add_left (a b c : α) : min (a + b) (a + c) = a + min b c := eq.symm (eq_min (show a + min b c ≤ a + b, from add_le_add_left (min_le_left _ _) _) (show a + min b c ≤ a + c, from add_le_add_left (min_le_right _ _) _) (assume d, assume : d ≤ a + b, assume : d ≤ a + c, decidable.by_cases (assume : b ≤ c, by rwa [min_eq_left this]) (assume : ¬ b ≤ c, by rwa [min_eq_right (le_of_lt (lt_of_not_ge this))]))) lemma min_add_add_right (a b c : α) : min (a + c) (b + c) = min a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply min_add_add_left end lemma max_add_add_left (a b c : α) : max (a + b) (a + c) = a + max b c := eq.symm (eq_max (add_le_add_left (le_max_left _ _) _) (add_le_add_left (le_max_right _ _) _) (assume d, assume : a + b ≤ d, assume : a + c ≤ d, decidable.by_cases (assume : b ≤ c, by rwa [max_eq_right this]) (assume : ¬ b ≤ c, by rwa [max_eq_left (le_of_lt (lt_of_not_ge this))]))) lemma max_add_add_right (a b c : α) : max (a + c) (b + c) = max a b + c := begin rw [add_comm a c, add_comm b c, add_comm _ c], apply max_add_add_left end end section variables {α : Type u} [decidable_linear_ordered_comm_group α] lemma max_neg_neg (a b : α) : max (-a) (-b) = - min a b := eq.symm (eq_max (show -a ≤ -(min a b), from neg_le_neg $ min_le_left a b) (show -b ≤ -(min a b), from neg_le_neg $ min_le_right a b) (assume d, assume H₁ : -a ≤ d, assume H₂ : -b ≤ d, have H : -d ≤ min a b, from le_min (neg_le_of_neg_le H₁) (neg_le_of_neg_le H₂), show -(min a b) ≤ d, from neg_le_of_neg_le H)) lemma min_eq_neg_max_neg_neg (a b : α) : min a b = - max (-a) (-b) := by rw [max_neg_neg, neg_neg] lemma min_neg_neg (a b : α) : min (-a) (-b) = - max a b := by rw [min_eq_neg_max_neg_neg, neg_neg, neg_neg] lemma max_eq_neg_min_neg_neg (a b : α) : max a b = - min (-a) (-b) := by rw [min_neg_neg, neg_neg] end section decidable_linear_ordered_comm_group variables {α : Type u} [decidable_linear_ordered_comm_group α] lemma abs_of_nonneg {a : α} (h : a ≥ 0) : abs a = a := have h' : -a ≤ a, from le_trans (neg_nonpos_of_nonneg h) h, max_eq_left h' lemma abs_of_pos {a : α} (h : a > 0) : abs a = a := abs_of_nonneg (le_of_lt h) lemma abs_of_nonpos {a : α} (h : a ≤ 0) : abs a = -a := have h' : a ≤ -a, from le_trans h (neg_nonneg_of_nonpos h), max_eq_right h' lemma abs_of_neg {a : α} (h : a < 0) : abs a = -a := abs_of_nonpos (le_of_lt h) lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg (le_refl _) lemma abs_neg (a : α) : abs (-a) = abs a := begin unfold abs, rw [max_comm, neg_neg] end lemma abs_pos_of_pos {a : α} (h : a > 0) : abs a > 0 := by rwa (abs_of_pos h) lemma abs_pos_of_neg {a : α} (h : a < 0) : abs a > 0 := abs_neg a ▸ abs_pos_of_pos (neg_pos_of_neg h) lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) := by rw [← neg_sub, abs_neg] lemma ne_zero_of_abs_ne_zero {a : α} (h : abs a ≠ 0) : a ≠ 0 := assume ha, h (eq.symm ha ▸ abs_zero) /- these assume a linear order -/ lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 := match lt_trichotomy a 0 with | or.inl h₁ := have a > 0, from h ▸ neg_pos_of_neg h₁, absurd h₁ (lt_asymm this) | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 0, from h ▸ neg_neg_of_pos h₁, absurd h₁ (lt_asymm this) end lemma abs_nonneg (a : α) : abs a ≥ 0 := or.elim (le_total 0 a) (assume h : 0 ≤ a, by rwa (abs_of_nonneg h)) (assume h : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos h ... = abs a : eq.symm (abs_of_nonpos h)) lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a lemma le_abs_self (a : α) : a ≤ abs a := or.elim (le_total 0 a) (assume h : 0 ≤ a, begin rw [abs_of_nonneg h] end) (assume h : a ≤ 0, le_trans h $ abs_nonneg a) lemma neg_le_abs_self (a : α) : -a ≤ abs a := abs_neg a ▸ le_abs_self (-a) lemma eq_zero_of_abs_eq_zero {a : α} (h : abs a = 0) : a = 0 := have h₁ : a ≤ 0, from h ▸ le_abs_self a, have h₂ : -a ≤ 0, from h ▸ abs_neg a ▸ le_abs_self (-a), le_antisymm h₁ (nonneg_of_neg_nonpos h₂) lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := have a - b = 0, from eq_zero_of_abs_eq_zero h, show a = b, from eq_of_sub_eq_zero this lemma abs_pos_of_ne_zero {a : α} (h : a ≠ 0) : abs a > 0 := or.elim (lt_or_gt_of_ne h) abs_pos_of_neg abs_pos_of_pos lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := or.elim (le_total 0 a) (assume h : 0 ≤ a, eq.symm (abs_of_nonneg h) ▸ h1) (assume h : a ≤ 0, eq.symm (abs_of_nonpos h) ▸ h2) lemma abs_le_of_le_of_neg_le {a b : α} (h1 : a ≤ b) (h2 : -a ≤ b) : abs a ≤ b := abs_by_cases (λ x : α, x ≤ b) h1 h2 lemma abs_lt_of_lt_of_neg_lt {a b : α} (h1 : a < b) (h2 : -a < b) : abs a < b := abs_by_cases (λ x : α, x < b) h1 h2 private lemma aux1 {a b : α} (h1 : a + b ≥ 0) (h2 : a ≥ 0) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume h3 : b ≥ 0, calc abs (a + b) ≤ abs (a + b) : by apply le_refl ... = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... = abs a + abs b : by rw (abs_of_nonneg h3)) (assume h3 : ¬ b ≥ 0, have h4 : b ≤ 0, from le_of_lt (lt_of_not_ge h3), calc abs (a + b) = a + b : by rw (abs_of_nonneg h1) ... = abs a + b : by rw (abs_of_nonneg h2) ... ≤ abs a + 0 : add_le_add_left h4 _ ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos h4) _ ... = abs a + abs b : by rw (abs_of_nonpos h4)) private lemma aux2 {a b : α} (h1 : a + b ≥ 0) : abs (a + b) ≤ abs a + abs b := or.elim (le_total b 0) (assume h2 : b ≤ 0, have h3 : ¬ a < 0, from assume h4 : a < 0, have h5 : a + b < 0, begin have aux := add_lt_add_of_lt_of_le h4 h2, rwa [add_zero] at aux end, not_lt_of_ge h1 h5, aux1 h1 (le_of_not_gt h3)) (assume h2 : 0 ≤ b, begin have h3 : abs (b + a) ≤ abs b + abs a, begin rw add_comm at h1, exact aux1 h1 h2 end, rw [add_comm, add_comm (abs a)], exact h3 end) lemma abs_add_le_abs_add_abs (a b : α) : abs (a + b) ≤ abs a + abs b := or.elim (le_total 0 (a + b)) (assume h2 : 0 ≤ a + b, aux2 h2) (assume h2 : a + b ≤ 0, have h3 : -a + -b = -(a + b), by rw neg_add, have h4 : -(a + b) ≥ 0, from neg_nonneg_of_nonpos h2, have h5 : -a + -b ≥ 0, begin rw [← h3] at h4, exact h4 end, calc abs (a + b) = abs (-a + -b) : by rw [← abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 h5 ... = abs a + abs b : by rw [abs_neg, abs_neg]) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := have h1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rw sub_add_cancel ... = abs (a - b + b) : by rw sub_add_cancel ... ≤ abs (a - b) + abs b : by apply abs_add_le_abs_add_abs, le_of_add_le_add_right h1 lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left] ... ≤ abs (a - b) + abs (b - c) : by apply abs_add_le_abs_add_abs lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := begin apply le_trans, apply abs_add_le_abs_add_abs, apply le_trans, apply add_le_add_right, apply abs_add_le_abs_add_abs, apply le_refl end lemma dist_bdd_within_interval {a b lb ub : α} (h : lb < ub) (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := begin cases (decidable.em (b ≤ a)) with hba hba, rw (abs_of_nonneg (sub_nonneg_of_le hba)), apply sub_le_sub, apply hau, apply hbl, rw [abs_of_neg (sub_neg_of_lt (lt_of_not_ge hba)), neg_sub], apply sub_le_sub, apply hbu, apply hal end end decidable_linear_ordered_comm_group section decidable_linear_ordered_comm_ring variables {α : Type u} [decidable_linear_ordered_comm_ring α] lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := or.elim (le_total 0 a) (assume h1 : 0 ≤ a, or.elim (le_total 0 b) (assume h2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg h1 h2) ... = abs a * b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos h1 h2) ... = a * -b : by rw neg_mul_eq_mul_neg ... = abs a * -b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) (assume h1 : a ≤ 0, or.elim (le_total 0 b) (assume h2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg h1 h2) ... = -a * b : by rw neg_mul_eq_neg_mul ... = abs a * b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos h1 h2) ... = -a * -b : by rw neg_mul_neg ... = abs a * -b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma sub_le_of_abs_sub_le_left {a b c : α} (h : abs (a - b) ≤ c) : b - c ≤ a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... ≥ b - c : sub_le_self _ (le_trans (abs_nonneg _) h)) else have habs : b - a ≤ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b ≤ c + a, from le_add_of_sub_right_le habs, sub_left_le_of_le_add habs' lemma sub_le_of_abs_sub_le_right {a b c : α} (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub a b ▸ h) lemma sub_lt_of_abs_sub_lt_left {a b c : α} (h : abs (a - b) < c) : b - c < a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... > b - c : sub_lt_self _ (lt_of_le_of_lt (abs_nonneg _) h)) else have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b < c + a, from lt_add_of_sub_right_lt habs, sub_left_lt_of_lt_add habs' lemma sub_lt_of_abs_sub_lt_right {a b c : α} (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h) lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm] end lemma eq_zero_of_mul_self_add_mul_self_eq_zero {x y : α} (h : x * x + y * y = 0) : x = 0 := have x * x ≤ (0 : α), from calc x * x ≤ x * x + y * y : le_add_of_nonneg_right (mul_self_nonneg y) ... = 0 : h, eq_zero_of_mul_self_eq_zero (le_antisymm this (mul_self_nonneg x)) lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, apply abs_nonneg, iterate {rw abs_sub_square}, iterate {rw abs_mul_abs_self}, apply sub_le_sub_left, iterate {rw mul_assoc}, apply mul_le_mul_of_nonneg_left, rw [← abs_mul], apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end end decidable_linear_ordered_comm_ring section discrete_linear_ordered_field variables {α : Type u} [discrete_linear_ordered_field α] lemma abs_div (a b : α) : abs (a / b) = abs a / abs b := decidable.by_cases (assume h : b = 0, by rw [h, abs_zero, div_zero, div_zero, abs_zero]) (assume h : b ≠ 0, have h₁ : abs b ≠ 0, from assume h₂, h (eq_zero_of_abs_eq_zero h₂), eq_div_of_mul_eq _ _ h₁ (show abs (a / b) * abs b = abs a, by rw [← abs_mul, div_mul_cancel _ h])) lemma abs_one_div (a : α) : abs (1 / a) = 1 / abs a := by rw [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : α))] end discrete_linear_ordered_field
819a3beb476e7c7c03bcdbaf5756089abbd83eb4
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/coercions.lean
3a6d26e5ad7801919d215f91565397281fd6dfc7
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
2,258
lean
variables m n : ℕ variables i j : ℤ universe u universe v --#check i + j --#check i + m + j --#check i + m + n -- ↑ is \u --#check ↑m + i --#check coe m + i instance bool_to_Prop : has_coe bool Prop := ⟨λ b, b = tt⟩ --#reduce if tt then 3 else 5 --#reduce if ff then 3 else 5 open list def toSet {α : Type u} : list α → set α | [] := ∅ | (x :: xs) := toSet xs instance toSetCoe (α : Type u) : has_coe (list α) (set α) := ⟨toSet⟩ def s₁ : set ℕ := {1,2} def l₁ : list ℕ := [3,4] --#check s₁ ∪ l₁ --#reduce s₁ ∪ l₁ --#check s₁ ∪ [3,4] -- error --#check s₁ ∪ [(3:ℕ),4] -- ok --#check s₁ ∪ ([3,4]:list ℕ) -- ok --#check s₁ ∪ ↑ [3,4] -- ok instance coe_subtype2 {α : Type u} {p:α → Prop} : has_coe {x // p x} α := ⟨λ s,subtype.val s⟩ --has_coe_t is the transitive closure if has_coe namespace hidden instance lift_list {α : Type u} {β : Type v} [has_lift α β] : has_lift (list α) (list β) := ⟨ λ xs, list.map (@coe α β _) xs⟩ variables xs : list ℕ variables ys : list ℤ -- #check ↑ xs ++ ys end hidden structure Semigroup : Type (u+1) := (carrier : Type u) (mul : carrier -> carrier -> carrier) (mul_assoc : ∀ a b c : carrier, mul (mul a b) c = mul a (mul b c)) instance Semigroup_has_mul (S : Semigroup) : has_mul (S.carrier) := ⟨S.mul⟩ --#check Semigroup.carrier instance Semigroup_to_sort : has_coe_to_sort Semigroup := {S := _, coe := λ S, S.carrier} example (S : Semigroup) (a b c : S) : (a * b) * c = a * (b * c) := Semigroup.mul_assoc _ a b c structure morphism (S1 S2: Semigroup) := (mor : S1 → S2) (resp_mul: ∀ a b : S1, mor (a * b) = mor a * mor b) --#check @morphism.mor instance morphism_to_fun (S1 S2 : Semigroup) : has_coe_to_fun (morphism S1 S2) := {F := λ _, S1 → S2, coe := λ m, m.mor} lemma resp_mul {S1 S2 : Semigroup} (f : morphism S1 S2) (a b : S1) : f (a * b) = f a * f b := f.resp_mul a b lemma L1 (S1 S2 : Semigroup) (f : morphism S1 S2) (a : S1) : f (a * a * a) = f a * f a * f a := calc f (a * a * a) = f (a * a) * f a : by rw resp_mul ... = f a * f a * f a : by rw resp_mul --#check @L1 --set_option pp.coercions false --#check @L1
138dff3f0041c46c7f16b095307b9038abd42b0c
c777c32c8e484e195053731103c5e52af26a25d1
/archive/imo/imo2006_q5.lean
665882fd84f23805f5fe024c47b80089b9c41a1a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
9,432
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import data.polynomial.ring_division import dynamics.periodic_pts /-! # IMO 2006 Q5 Let $P(x)$ be a polynomial of degree $n>1$ with integer coefficients, and let $k$ be a positive integer. Consider the polynomial $Q(x) = P(P(\ldots P(P(x))\ldots))$, where $P$ occurs $k$ times. Prove that there are at most $n$ integers $t$ such that $Q(t)=t$. ## Sketch of solution The following solution is adapted from https://artofproblemsolving.com/wiki/index.php/2006_IMO_Problems/Problem_5. Let $P^k$ denote the polynomial $P$ composed with itself $k$ times. We rely on a key observation: if $P^k(t)=t$, then $P(P(t))=t$. We prove this by building the cyclic list $(P(t)-t,P^2(t)-P(t),\ldots)$, and showing that each entry divides the next, which by transitivity implies they all divide each other, and thus have the same absolute value. If the entries in this list are all pairwise equal, then we can show inductively that for positive $n$, $P^n(t)-t$ must always have the same sign as $P(t)-t$. Substituting $n=k$ gives us $P(t)=t$ and in particular $P(P(t))=t$. Otherwise, there must be two consecutive entries that are opposites of one another. This means $P^{n+2}(t)-P^{n+1}(t)=P^n(t)-P^{n+1}(t)$, which implies $P^{n+2}(t)=P^n(t)$ and $P(P(t))=t$. With this lemma, we can reduce the problem to the case $k=2$. If every root of $P(P(t))-t$ is also a root of $P(t)-t$, then we're done. Otherwise, there exist $a$ and $b$ with $a\ne b$ and $P(a)=b$, $P(b)=a$. For any root $t$ of $P(P(t))-t$, defining $u=P(t)$, we easily verify $a-t\mid b-u$, $b-u\mid a-t$, $a-u\mid b-t$, $b-t\mid a-u$, which imply $|a-t|=|b-u|$ and $|a-u|=|b-t|$. By casing on these equalities, we deduce $a+b=t+u$. This means that every root of $P(P(t))-t$ is a root of $P(t)+t-a-b$, and we're again done. -/ open function polynomial /-- If every entry in a cyclic list of integers divides the next, then they all have the same absolute value. -/ theorem int.nat_abs_eq_of_chain_dvd {l : cycle ℤ} {x y : ℤ} (hl : l.chain (∣)) (hx : x ∈ l) (hy : y ∈ l) : x.nat_abs = y.nat_abs := begin rw cycle.chain_iff_pairwise at hl, exact int.nat_abs_eq_of_dvd_dvd (hl x hx y hy) (hl y hy x hx) end theorem int.add_eq_add_of_nat_abs_eq_of_nat_abs_eq {a b c d : ℤ} (hne : a ≠ b) (h₁ : (c - a).nat_abs = (d - b).nat_abs) (h₂ : (c - b).nat_abs = (d - a).nat_abs) : a + b = c + d := begin cases int.nat_abs_eq_nat_abs_iff.1 h₁ with h₁ h₁, { cases int.nat_abs_eq_nat_abs_iff.1 h₂ with h₂ h₂, { exact (hne $ by linarith).elim }, { linarith } }, { linarith } end /-- The main lemma in the proof: if $P^k(t)=t$, then $P(P(t))=t$. -/ theorem polynomial.is_periodic_pt_eval_two {P : polynomial ℤ} {t : ℤ} (ht : t ∈ periodic_pts (λ x, P.eval x)) : is_periodic_pt (λ x, P.eval x) 2 t := begin -- The cycle [P(t) - t, P(P(t)) - P(t), ...] let C : cycle ℤ := (periodic_orbit (λ x, P.eval x) t).map (λ x, P.eval x - x), have HC : ∀ {n : ℕ}, (λ x, P.eval x)^[n + 1] t - ((λ x, P.eval x)^[n] t) ∈ C, { intro n, rw [cycle.mem_map, function.iterate_succ_apply'], exact ⟨_, iterate_mem_periodic_orbit ht n, rfl⟩ }, -- Elements in C are all divisible by one another. have Hdvd : C.chain (∣), { rw [cycle.chain_map, periodic_orbit_chain' _ ht], intro n, convert sub_dvd_eval_sub ((λ x, P.eval x)^[n + 1] t) ((λ x, P.eval x)^[n] t) P; rw function.iterate_succ_apply' }, -- Any two entries in C have the same absolute value. have Habs : ∀ m n : ℕ, ((λ x, P.eval x)^[m + 1] t - ((λ x, P.eval x)^[m] t)).nat_abs = ((λ x, P.eval x)^[n + 1] t - ((λ x, P.eval x)^[n] t)).nat_abs := λ m n, int.nat_abs_eq_of_chain_dvd Hdvd HC HC, -- We case on whether the elements on C are pairwise equal. by_cases HC' : C.chain (=), { -- Any two entries in C are equal. have Heq : ∀ m n : ℕ, (λ x, P.eval x)^[m + 1] t - ((λ x, P.eval x)^[m] t) = ((λ x, P.eval x)^[n + 1] t - ((λ x, P.eval x)^[n] t)) := λ m n, cycle.chain_iff_pairwise.1 HC' _ HC _ HC, -- The sign of P^n(t) - t is the same as P(t) - t for positive n. Proven by induction on n. have IH : ∀ n : ℕ, ((λ x, P.eval x)^[n + 1] t - t).sign = (P.eval t - t).sign, { intro n, induction n with n IH, { refl }, { apply eq.trans _ (int.sign_add_eq_of_sign_eq IH), have H := Heq n.succ 0, dsimp at H ⊢, rw [←H, sub_add_sub_cancel'] } }, -- This implies that the sign of P(t) - t is the same as the sign of P^k(t) - t, which is 0. -- Hence P(t) = t and P(P(t)) = P(t). rcases ht with ⟨(_ | k), hk, hk'⟩, { exact (irrefl 0 hk).elim }, { have H := IH k, rw [hk'.is_fixed_pt.eq, sub_self, int.sign_zero, eq_comm, int.sign_eq_zero_iff_zero, sub_eq_zero] at H, simp [is_periodic_pt, is_fixed_pt, H] } }, { -- We take two nonequal consecutive entries. rw [cycle.chain_map, periodic_orbit_chain' _ ht] at HC', push_neg at HC', cases HC' with n hn, -- They must have opposite sign, so that P^{k + 1}(t) - P^k(t) = P^{k + 2}(t) - P^{k + 1}(t). cases int.nat_abs_eq_nat_abs_iff.1 (Habs n n.succ) with hn' hn', { apply (hn _).elim, convert hn'; simp only [function.iterate_succ_apply'] }, -- We deduce P^{k + 2}(t) = P^k(t) and hence P(P(t)) = t. { rw [neg_sub, sub_right_inj] at hn', simp only [function.iterate_succ_apply'] at hn', exact @is_periodic_pt_of_mem_periodic_pts_of_is_periodic_pt_iterate _ _ t 2 n ht hn'.symm } } end theorem polynomial.iterate_comp_sub_X_ne {P : polynomial ℤ} (hP : 1 < P.nat_degree) {k : ℕ} (hk : 0 < k) : P.comp^[k] X - X ≠ 0 := by { rw sub_ne_zero, apply_fun nat_degree, simpa using (one_lt_pow hP hk.ne').ne' } /-- We solve the problem for the specific case k = 2 first. -/ theorem imo2006_q5' {P : polynomial ℤ} (hP : 1 < P.nat_degree) : (P.comp P - X).roots.to_finset.card ≤ P.nat_degree := begin -- Auxiliary lemmas on degrees. have hPX : (P - X).nat_degree = P.nat_degree, { rw nat_degree_sub_eq_left_of_nat_degree_lt, simpa using hP }, have hPX' : P - X ≠ 0, { intro h, rw [h, nat_degree_zero] at hPX, rw ←hPX at hP, exact (zero_le_one.not_lt hP).elim }, -- If every root of P(P(t)) - t is also a root of P(t) - t, then we're done. by_cases H : (P.comp P - X).roots.to_finset ⊆ (P - X).roots.to_finset, { exact (finset.card_le_of_subset H).trans ((multiset.to_finset_card_le _).trans ((card_roots' _).trans_eq hPX)) }, -- Otherwise, take a, b with P(a) = b, P(b) = a, a ≠ b. { rcases finset.not_subset.1 H with ⟨a, ha, hab⟩, replace ha := is_root_of_mem_roots (multiset.mem_to_finset.1 ha), simp [sub_eq_zero] at ha, simp [mem_roots hPX'] at hab, set b := P.eval a, rw sub_eq_zero at hab, -- More auxiliary lemmas on degrees. have hPab : (P + X - a - b).nat_degree = P.nat_degree, { rw [sub_sub, ←int.cast_add], have h₁ : (P + X).nat_degree = P.nat_degree, { rw nat_degree_add_eq_left_of_nat_degree_lt, simpa using hP }, rw nat_degree_sub_eq_left_of_nat_degree_lt; rwa h₁, rw nat_degree_int_cast, exact zero_lt_one.trans hP }, have hPab' : P + X - a - b ≠ 0, { intro h, rw [h, nat_degree_zero] at hPab, rw ←hPab at hP, exact (zero_le_one.not_lt hP).elim }, -- We claim that every root of P(P(t)) - t is a root of P(t) + t - a - b. This allows us to -- conclude the problem. suffices H' : (P.comp P - X).roots.to_finset ⊆ (P + X - a - b).roots.to_finset, { exact (finset.card_le_of_subset H').trans ((multiset.to_finset_card_le _).trans $ (card_roots' _).trans_eq hPab) }, { -- Let t be a root of P(P(t)) - t, define u = P(t). intros t ht, replace ht := is_root_of_mem_roots (multiset.mem_to_finset.1 ht), simp [sub_eq_zero] at ht, simp only [mem_roots hPab', sub_eq_iff_eq_add, multiset.mem_to_finset, is_root.def, eval_sub, eval_add, eval_X, eval_C, eval_int_cast, int.cast_id, zero_add], -- An auxiliary lemma proved earlier implies we only need to show |t - a| = |u - b| and -- |t - b| = |u - a|. We prove this by establishing that each side of either equation divides -- the other. apply (int.add_eq_add_of_nat_abs_eq_of_nat_abs_eq hab _ _).symm; apply int.nat_abs_eq_of_dvd_dvd; set u := P.eval t, { rw [←ha, ←ht], apply sub_dvd_eval_sub }, { apply sub_dvd_eval_sub }, { rw ←ht, apply sub_dvd_eval_sub }, { rw ←ha, apply sub_dvd_eval_sub } } } end /-- The general problem follows easily from the k = 2 case. -/ theorem imo2006_q5 {P : polynomial ℤ} (hP : 1 < P.nat_degree) {k : ℕ} (hk : 0 < k) : (P.comp^[k] X - X).roots.to_finset.card ≤ P.nat_degree := begin apply (finset.card_le_of_subset $ λ t ht, _).trans (imo2006_q5' hP), have hP' : P.comp P - X ≠ 0 := by simpa using polynomial.iterate_comp_sub_X_ne hP zero_lt_two, replace ht := is_root_of_mem_roots (multiset.mem_to_finset.1 ht), simp only [sub_eq_zero, is_root.def, eval_sub, iterate_comp_eval, eval_X] at ht, simpa [mem_roots hP', sub_eq_zero] using polynomial.is_periodic_pt_eval_two ⟨k, hk, ht⟩ end
a76b153e9dbfda43be62d2e0ab5fe2e8e6e8c5c1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Compiler/IR/Format.lean
e84828a6494398d364cf84c3ad259a0648c53b53
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
6,925
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.Compiler.IR.Basic namespace Lean namespace IR private def formatArg : Arg → Format | Arg.var id => format id | Arg.irrelevant => "◾" instance : ToFormat Arg := ⟨formatArg⟩ def formatArray {α : Type} [ToFormat α] (args : Array α) : Format := args.foldl (fun r a => r ++ " " ++ format a) Format.nil private def formatLitVal : LitVal → Format | LitVal.num v => format v | LitVal.str v => format (repr v) instance : ToFormat LitVal := ⟨formatLitVal⟩ private def formatCtorInfo : CtorInfo → Format | { name := name, cidx := cidx, usize := usize, ssize := ssize, .. } => do let mut r := f!"ctor_{cidx}" if usize > 0 || ssize > 0 then r := f!"{r}.{usize}.{ssize}" if name != Name.anonymous then r := f!"{r}[{name}]" r instance : ToFormat CtorInfo := ⟨formatCtorInfo⟩ private def formatExpr : Expr → Format | Expr.ctor i ys => format i ++ formatArray ys | Expr.reset n x => "reset[" ++ format n ++ "] " ++ format x | Expr.reuse x i u ys => "reuse" ++ (if u then "!" else "") ++ " " ++ format x ++ " in " ++ format i ++ formatArray ys | Expr.proj i x => "proj[" ++ format i ++ "] " ++ format x | Expr.uproj i x => "uproj[" ++ format i ++ "] " ++ format x | Expr.sproj n o x => "sproj[" ++ format n ++ ", " ++ format o ++ "] " ++ format x | Expr.fap c ys => format c ++ formatArray ys | Expr.pap c ys => "pap " ++ format c ++ formatArray ys | Expr.ap x ys => "app " ++ format x ++ formatArray ys | Expr.box _ x => "box " ++ format x | Expr.unbox x => "unbox " ++ format x | Expr.lit v => format v | Expr.isShared x => "isShared " ++ format x | Expr.isTaggedPtr x => "isTaggedPtr " ++ format x instance : ToFormat Expr := ⟨formatExpr⟩ instance : ToString Expr := ⟨fun e => Format.pretty (format e)⟩ private partial def formatIRType : IRType → Format | IRType.float => "float" | IRType.uint8 => "u8" | IRType.uint16 => "u16" | IRType.uint32 => "u32" | IRType.uint64 => "u64" | IRType.usize => "usize" | IRType.irrelevant => "◾" | IRType.object => "obj" | IRType.tobject => "tobj" | IRType.struct _ tys => "struct " ++ Format.bracket "{" (@Format.joinSep _ ⟨formatIRType⟩ tys.toList ", ") "}" | IRType.union _ tys => "union " ++ Format.bracket "{" (@Format.joinSep _ ⟨formatIRType⟩ tys.toList ", ") "}" instance : ToFormat IRType := ⟨formatIRType⟩ instance : ToString IRType := ⟨toString ∘ format⟩ private def formatParam : Param → Format | { x := name, borrow := b, ty := ty } => "(" ++ format name ++ " : " ++ (if b then "@& " else "") ++ format ty ++ ")" instance : ToFormat Param := ⟨formatParam⟩ def formatAlt (fmt : FnBody → Format) (indent : Nat) : Alt → Format | Alt.ctor i b => format i.name ++ " →" ++ Format.nest indent (Format.line ++ fmt b) | Alt.default b => "default →" ++ Format.nest indent (Format.line ++ fmt b) def formatParams (ps : Array Param) : Format := formatArray ps @[export lean_ir_format_fn_body_head] def formatFnBodyHead : FnBody → Format | FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e | FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " := ..." | FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y | FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y | FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx | FnBody.inc x n c _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.dec x n c _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x | FnBody.del x b => "del " ++ format x | FnBody.mdata d b => "mdata " ++ format d | FnBody.case tid x xType cs => "case " ++ format x ++ " of ..." | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" partial def formatFnBody (fnBody : FnBody) (indent : Nat := 2) : Format := let rec loop : FnBody → Format | FnBody.vdecl x ty e b => "let " ++ format x ++ " : " ++ format ty ++ " := " ++ format e ++ ";" ++ Format.line ++ loop b | FnBody.jdecl j xs v b => format j ++ formatParams xs ++ " :=" ++ Format.nest indent (Format.line ++ loop v) ++ ";" ++ Format.line ++ loop b | FnBody.set x i y b => "set " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.uset x i y b => "uset " ++ format x ++ "[" ++ format i ++ "] := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.sset x i o y ty b => "sset " ++ format x ++ "[" ++ format i ++ ", " ++ format o ++ "] : " ++ format ty ++ " := " ++ format y ++ ";" ++ Format.line ++ loop b | FnBody.setTag x cidx b => "setTag " ++ format x ++ " := " ++ format cidx ++ ";" ++ Format.line ++ loop b | FnBody.inc x n c _ b => "inc" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.dec x n c _ b => "dec" ++ (if n != 1 then Format.sbracket (format n) else "") ++ " " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.del x b => "del " ++ format x ++ ";" ++ Format.line ++ loop b | FnBody.mdata d b => "mdata " ++ format d ++ ";" ++ Format.line ++ loop b | FnBody.case tid x xType cs => "case " ++ format x ++ " : " ++ format xType ++ " of" ++ cs.foldl (fun r c => r ++ Format.line ++ formatAlt loop indent c) Format.nil | FnBody.jmp j ys => "jmp " ++ format j ++ formatArray ys | FnBody.ret x => "ret " ++ format x | FnBody.unreachable => "⊥" loop fnBody instance : ToFormat FnBody := ⟨formatFnBody⟩ instance : ToString FnBody := ⟨fun b => (format b).pretty⟩ def formatDecl (decl : Decl) (indent : Nat := 2) : Format := match decl with | Decl.fdecl f xs ty b _ => "def " ++ format f ++ formatParams xs ++ format " : " ++ format ty ++ " :=" ++ Format.nest indent (Format.line ++ formatFnBody b indent) | Decl.extern f xs ty _ => "extern " ++ format f ++ formatParams xs ++ format " : " ++ format ty instance : ToFormat Decl := ⟨formatDecl⟩ @[export lean_ir_decl_to_string] def declToString (d : Decl) : String := (format d).pretty instance : ToString Decl := ⟨declToString⟩ end Lean.IR
84a251e561e969f9823f0daeb21bb347aa891ce8
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/filtration.lean
6a117b916757d3f92448f882bf2ea773ee99ddeb
[ "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
6,899
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.noetherian import ring_theory.rees_algebra import ring_theory.finiteness /-! # `I`-filtrations of modules This file contains the definitions and basic results around (stable) `I`-filtrations of modules. -/ universes u v variables {R M : Type u} [comm_ring R] [add_comm_group M] [module R M] (I : ideal R) open polynomial open_locale polynomial big_operators /-- An `I`-filtration on the module `M` is a sequence of decreasing submodules `N i` such that `I • N ≤ I (i + 1)`. Note that we do not require the filtration to start from `⊤`. -/ @[ext] structure ideal.filtration (M : Type u) [add_comm_group M] [module R M] := (N : ℕ → submodule R M) (mono : ∀ i, N (i + 1) ≤ N i) (smul_le : ∀ i, I • N i ≤ N (i + 1)) variables (F F' : I.filtration M) {I} namespace ideal.filtration lemma pow_smul_le (i j : ℕ) : I ^ i • F.N j ≤ F.N (i + j) := begin induction i, { simp }, { rw [pow_succ, mul_smul, nat.succ_eq_add_one, add_assoc, add_comm 1, ← add_assoc], exact (submodule.smul_mono_right i_ih).trans (F.smul_le _) } end lemma pow_smul_le_pow_smul (i j k : ℕ) : I ^ (i + k) • F.N j ≤ I ^ k • F.N (i + j) := by { rw [add_comm, pow_add, mul_smul], exact submodule.smul_mono_right (F.pow_smul_le i j) } protected lemma antitone : antitone F.N := antitone_nat_of_succ_le F.mono /-- The trivial `I`-filtration of `N`. -/ @[simps] def _root_.ideal.trivial_filtration (I : ideal R) (N : submodule R M) : I.filtration M := { N := λ i, N, mono := λ i, le_of_eq rfl, smul_le := λ i, submodule.smul_le_right } /-- The `sup` of two `I.filtration`s is an `I.filtration`. -/ instance : has_sup (I.filtration M) := ⟨λ F F', ⟨F.N ⊔ F'.N, λ i, sup_le_sup (F.mono i) (F'.mono i), λ i, (le_of_eq (submodule.smul_sup _ _ _)).trans $ sup_le_sup (F.smul_le i) (F'.smul_le i)⟩⟩ /-- The `Sup` of a family of `I.filtration`s is an `I.filtration`. -/ instance : has_Sup (I.filtration M) := ⟨λ S, { N := Sup (ideal.filtration.N '' S), mono := λ i, begin apply Sup_le_Sup_of_forall_exists_le _, rintros _ ⟨⟨_, F, hF, rfl⟩, rfl⟩, exact ⟨_, ⟨⟨_, F, hF, rfl⟩, rfl⟩, F.mono i⟩, end, smul_le := λ i, begin rw [Sup_eq_supr', supr_apply, submodule.smul_supr, supr_apply], apply supr_mono _, rintro ⟨_, F, hF, rfl⟩, exact F.smul_le i, end }⟩ /-- The `inf` of two `I.filtration`s is an `I.filtration`. -/ instance : has_inf (I.filtration M) := ⟨λ F F', ⟨F.N ⊓ F'.N, λ i, inf_le_inf (F.mono i) (F'.mono i), λ i, (submodule.smul_inf_le _ _ _).trans $ inf_le_inf (F.smul_le i) (F'.smul_le i)⟩⟩ /-- The `Inf` of a family of `I.filtration`s is an `I.filtration`. -/ instance : has_Inf (I.filtration M) := ⟨λ S, { N := Inf (ideal.filtration.N '' S), mono := λ i, begin apply Inf_le_Inf_of_forall_exists_le _, rintros _ ⟨⟨_, F, hF, rfl⟩, rfl⟩, exact ⟨_, ⟨⟨_, F, hF, rfl⟩, rfl⟩, F.mono i⟩, end, smul_le := λ i, begin rw [Inf_eq_infi', infi_apply, infi_apply], refine submodule.smul_infi_le.trans _, apply infi_mono _, rintro ⟨_, F, hF, rfl⟩, exact F.smul_le i, end }⟩ instance : has_top (I.filtration M) := ⟨I.trivial_filtration ⊤⟩ instance : has_bot (I.filtration M) := ⟨I.trivial_filtration ⊥⟩ @[simp] lemma sup_N : (F ⊔ F').N = F.N ⊔ F'.N := rfl @[simp] lemma Sup_N (S : set (I.filtration M)) : (Sup S).N = Sup (ideal.filtration.N '' S) := rfl @[simp] lemma inf_N : (F ⊓ F').N = F.N ⊓ F'.N := rfl @[simp] lemma Inf_N (S : set (I.filtration M)) : (Inf S).N = Inf (ideal.filtration.N '' S) := rfl @[simp] lemma top_N : (⊤ : I.filtration M).N = ⊤ := rfl @[simp] lemma bot_N : (⊥ : I.filtration M).N = ⊥ := rfl @[simp] lemma supr_N {ι : Sort*} (f : ι → I.filtration M) : (supr f).N = ⨆ i, (f i).N := congr_arg Sup (set.range_comp _ _).symm @[simp] lemma infi_N {ι : Sort*} (f : ι → I.filtration M) : (infi f).N = ⨅ i, (f i).N := congr_arg Inf (set.range_comp _ _).symm instance : complete_lattice (I.filtration M) := function.injective.complete_lattice ideal.filtration.N ideal.filtration.ext sup_N inf_N (λ _, Sup_image) (λ _, Inf_image) top_N bot_N instance : inhabited (I.filtration M) := ⟨⊥⟩ /-- An `I` filtration is stable if `I • F.N n = F.N (n+1)` for large enough `n`. -/ def stable : Prop := ∃ n₀, ∀ n ≥ n₀, I • F.N n = F.N (n + 1) /-- The trivial stable `I`-filtration of `N`. -/ @[simps] def _root_.ideal.stable_filtration (I : ideal R) (N : submodule R M) : I.filtration M := { N := λ i, I ^ i • N, mono := λ i, by { rw [add_comm, pow_add, mul_smul], exact submodule.smul_le_right }, smul_le := λ i, by { rw [add_comm, pow_add, mul_smul, pow_one], exact le_refl _ } } lemma _root_.ideal.stable_filtration_stable (I : ideal R) (N : submodule R M) : (I.stable_filtration N).stable := by { use 0, intros n _, dsimp, rw [add_comm, pow_add, mul_smul, pow_one] } variables {F F'} (h : F.stable) include h lemma stable.exists_pow_smul_eq : ∃ n₀, ∀ k, F.N (n₀ + k) = I ^ k • F.N n₀ := begin obtain ⟨n₀, hn⟩ := h, use n₀, intro k, induction k, { simp }, { rw [nat.succ_eq_add_one, ← add_assoc, ← hn, k_ih, add_comm, pow_add, mul_smul, pow_one], linarith } end lemma stable.exists_pow_smul_eq_of_ge : ∃ n₀, ∀ n ≥ n₀, F.N n = I ^ (n - n₀) • F.N n₀ := begin obtain ⟨n₀, hn₀⟩ := h.exists_pow_smul_eq, use n₀, intros n hn, convert hn₀ (n - n₀), rw [add_comm, tsub_add_cancel_of_le hn], end omit h lemma stable_iff_exists_pow_smul_eq_of_ge : F.stable ↔ ∃ n₀, ∀ n ≥ n₀, F.N n = I ^ (n - n₀) • F.N n₀ := begin refine ⟨stable.exists_pow_smul_eq_of_ge, λ h, ⟨h.some, λ n hn, _⟩⟩, rw [h.some_spec n hn, h.some_spec (n+1) (by linarith), smul_smul, ← pow_succ, tsub_add_eq_add_tsub hn], end lemma stable.exists_forall_le (h : F.stable) (e : F.N 0 ≤ F'.N 0) : ∃ n₀, ∀ n, F.N (n + n₀) ≤ F'.N n := begin obtain ⟨n₀, hF⟩ := h, use n₀, intro n, induction n with n hn, { refine (F.antitone _).trans e, simp }, { rw [nat.succ_eq_one_add, add_assoc, add_comm, add_comm 1 n, ← hF], exact (submodule.smul_mono_right hn).trans (F'.smul_le _), simp }, end lemma stable.bounded_difference (h : F.stable) (h' : F'.stable) (e : F.N 0 = F'.N 0) : ∃ n₀, ∀ n, F.N (n + n₀) ≤ F'.N n ∧ F'.N (n + n₀) ≤ F.N n := begin obtain ⟨n₁, h₁⟩ := h.exists_forall_le (le_of_eq e), obtain ⟨n₂, h₂⟩ := h'.exists_forall_le (le_of_eq e.symm), use max n₁ n₂, intro n, refine ⟨(F.antitone _).trans (h₁ n), (F'.antitone _).trans (h₂ n)⟩; simp end end ideal.filtration
50953e4ea57385270ad19d60d65d64ddb04de936
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/ideal/cotangent.lean
d54cc285765d2666b751e4ec18200bb80a6e5ad0
[ "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
7,435
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.ideal.operations import algebra.module.torsion import algebra.ring.idempotents import linear_algebra.finite_dimensional import ring_theory.ideal.local_ring import ring_theory.nakayama /-! # The module `I ⧸ I ^ 2` In this file, we provide special API support for the module `I ⧸ I ^ 2`. The official definition is a quotient module of `I`, but the alternative definition as an ideal of `R ⧸ I ^ 2` is also given, and the two are `R`-equivalent as in `ideal.cotangent_equiv_ideal`. Additional support is also given to the cotangent space `m ⧸ m ^ 2` of a local ring. -/ namespace ideal variables {R S S' : Type*} [comm_ring R] [comm_semiring S] [algebra S R] variables [comm_semiring S'] [algebra S' R] [algebra S S'] [is_scalar_tower S S' R] (I : ideal R) /-- `I ⧸ I ^ 2` as a quotient of `I`. -/ @[derive [add_comm_group, module (R ⧸ I)]] def cotangent : Type* := I ⧸ (I • ⊤ : submodule R I) instance : inhabited I.cotangent := ⟨0⟩ instance cotangent.module_of_tower : module S I.cotangent := submodule.quotient.module' _ instance : is_scalar_tower S S' I.cotangent := begin delta cotangent, constructor, intros s s' x, rw [← @is_scalar_tower.algebra_map_smul S' R, ← @is_scalar_tower.algebra_map_smul S' R, ← smul_assoc, ← is_scalar_tower.to_alg_hom_apply S S' R, map_smul], refl end instance [is_noetherian R I] : is_noetherian R I.cotangent := by { delta cotangent, apply_instance } /-- The quotient map from `I` to `I ⧸ I ^ 2`. -/ @[simps apply (lemmas_only)] def to_cotangent : I →ₗ[R] I.cotangent := submodule.mkq _ lemma map_to_cotangent_ker : I.to_cotangent.ker.map I.subtype = I ^ 2 := by simp [ideal.to_cotangent, submodule.map_smul'', pow_two] lemma mem_to_cotangent_ker {x : I} : x ∈ I.to_cotangent.ker ↔ (x : R) ∈ I ^ 2 := begin rw ← I.map_to_cotangent_ker, simp, end lemma to_cotangent_eq {x y : I} : I.to_cotangent x = I.to_cotangent y ↔ (x - y : R) ∈ I ^ 2 := begin rw [← sub_eq_zero, ← map_sub], exact I.mem_to_cotangent_ker end lemma to_cotangent_eq_zero (x : I) : I.to_cotangent x = 0 ↔ (x : R) ∈ I ^ 2 := I.mem_to_cotangent_ker lemma to_cotangent_surjective : function.surjective I.to_cotangent := submodule.mkq_surjective _ lemma to_cotangent_range : I.to_cotangent.range = ⊤ := submodule.range_mkq _ lemma cotangent_subsingleton_iff : subsingleton I.cotangent ↔ is_idempotent_elem I := begin split, { introI H, refine (pow_two I).symm.trans (le_antisymm (ideal.pow_le_self two_ne_zero) _), exact λ x hx, (I.to_cotangent_eq_zero ⟨x, hx⟩).mp (subsingleton.elim _ _) }, { exact λ e, ⟨λ x y, quotient.induction_on₂' x y $ λ x y, I.to_cotangent_eq.mpr $ ((pow_two I).trans e).symm ▸ I.sub_mem x.prop y.prop⟩ } end /-- The inclusion map `I ⧸ I ^ 2` to `R ⧸ I ^ 2`. -/ def cotangent_to_quotient_square : I.cotangent →ₗ[R] R ⧸ I ^ 2 := submodule.mapq (I • ⊤) (I ^ 2) I.subtype (by { rw [← submodule.map_le_iff_le_comap, submodule.map_smul'', submodule.map_top, submodule.range_subtype, smul_eq_mul, pow_two], exact rfl.le }) lemma to_quotient_square_comp_to_cotangent : I.cotangent_to_quotient_square.comp I.to_cotangent = (I ^ 2).mkq.comp (submodule.subtype I) := linear_map.ext $ λ _, rfl @[simp] lemma to_cotangent_to_quotient_square (x : I) : I.cotangent_to_quotient_square (I.to_cotangent x) = (I ^ 2).mkq x := rfl /-- `I ⧸ I ^ 2` as an ideal of `R ⧸ I ^ 2`. -/ def cotangent_ideal (I : ideal R) : ideal (R ⧸ I ^ 2) := begin haveI : @ring_hom_surjective R (R ⧸ I ^ 2) _ _ _ := ⟨ideal.quotient.mk_surjective⟩, let rq := (I ^ 2)^.quotient.mk, exact submodule.map rq.to_semilinear_map I, end lemma cotangent_ideal_square (I : ideal R) : I.cotangent_ideal ^ 2 = ⊥ := begin rw [eq_bot_iff, pow_two I.cotangent_ideal, ← smul_eq_mul], intros x hx, apply submodule.smul_induction_on hx, { rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, apply (submodule.quotient.eq _).mpr _, rw [sub_zero, pow_two], exact ideal.mul_mem_mul hx hy }, { intros x y hx hy, exact add_mem hx hy } end lemma to_quotient_square_range : I.cotangent_to_quotient_square.range = I.cotangent_ideal.restrict_scalars R := begin transitivity (I.cotangent_to_quotient_square.comp I.to_cotangent).range, { rw [linear_map.range_comp, I.to_cotangent_range, submodule.map_top] }, { rw [to_quotient_square_comp_to_cotangent, linear_map.range_comp, I.range_subtype], ext, refl } end /-- The equivalence of the two definitions of `I / I ^ 2`, either as the quotient of `I` or the ideal of `R / I ^ 2`. -/ noncomputable def cotangent_equiv_ideal : I.cotangent ≃ₗ[R] I.cotangent_ideal := begin refine { ..(I.cotangent_to_quotient_square.cod_restrict (I.cotangent_ideal.restrict_scalars R) (λ x, by { rw ← to_quotient_square_range, exact linear_map.mem_range_self _ _ })), ..(equiv.of_bijective _ ⟨_, _⟩) }, { rintros x y e, replace e := congr_arg subtype.val e, obtain ⟨x, rfl⟩ := I.to_cotangent_surjective x, obtain ⟨y, rfl⟩ := I.to_cotangent_surjective y, rw I.to_cotangent_eq, dsimp only [to_cotangent_to_quotient_square, submodule.mkq_apply] at e, rwa submodule.quotient.eq at e }, { rintro ⟨_, x, hx, rfl⟩, refine ⟨I.to_cotangent ⟨x, hx⟩, subtype.ext rfl⟩ } end @[simp, nolint simp_nf] lemma cotangent_equiv_ideal_apply (x : I.cotangent) : ↑(I.cotangent_equiv_ideal x) = I.cotangent_to_quotient_square x := rfl lemma cotangent_equiv_ideal_symm_apply (x : R) (hx : x ∈ I) : I.cotangent_equiv_ideal.symm ⟨(I ^ 2).mkq x, submodule.mem_map_of_mem hx⟩ = I.to_cotangent ⟨x, hx⟩ := begin apply I.cotangent_equiv_ideal.injective, rw I.cotangent_equiv_ideal.apply_symm_apply, ext, refl end variables {A B : Type*} [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] /-- The lift of `f : A →ₐ[R] B` to `A ⧸ J ^ 2 →ₐ[R] B` with `J` being the kernel of `f`. -/ def _root_.alg_hom.ker_square_lift (f : A →ₐ[R] B) : A ⧸ f.to_ring_hom.ker ^ 2 →ₐ[R] B := begin refine { commutes' := _, ..(ideal.quotient.lift (f.to_ring_hom.ker ^ 2) f.to_ring_hom _) }, { intros a ha, exact ideal.pow_le_self two_ne_zero ha }, { intro r, rw [is_scalar_tower.algebra_map_apply R A, ring_hom.to_fun_eq_coe, ideal.quotient.algebra_map_eq, ideal.quotient.lift_mk], exact f.map_algebra_map r }, end lemma _root_.alg_hom.ker_ker_sqare_lift (f : A →ₐ[R] B) : f.ker_square_lift.to_ring_hom.ker = f.to_ring_hom.ker.cotangent_ideal := begin apply le_antisymm, { intros x hx, obtain ⟨x, rfl⟩ := ideal.quotient.mk_surjective x, exact ⟨x, hx, rfl⟩ }, { rintros _ ⟨x, hx, rfl⟩, exact hx } end end ideal namespace local_ring variables (R : Type*) [comm_ring R] [local_ring R] /-- The `A ⧸ I`-vector space `I ⧸ I ^ 2`. -/ @[reducible] def cotangent_space : Type* := (maximal_ideal R).cotangent instance : module (residue_field R) (cotangent_space R) := ideal.cotangent.module _ instance : is_scalar_tower R (residue_field R) (cotangent_space R) := module.is_torsion_by_set.is_scalar_tower _ instance [is_noetherian_ring R] : finite_dimensional (residue_field R) (cotangent_space R) := module.finite.of_restrict_scalars_finite R _ _ end local_ring
da3f8e331f889a9f654c891d64d51ebf0ba98794
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/simp_lemmas_with_mvars.lean
b60d75b33ee9133057616dc68587e094d6f98e50
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
792
lean
lemma {u} if_pos' {c : Prop} [h : decidable c] (hc : c) {α : Sort u} (t e : α) : (ite c t e) = t := if_pos hc example (a b : nat) (h : a = b) : (if a = b then 0 else 1) = cond (if a = b then tt else ff) 0 1 := begin simp only [if_pos' h, cond], end example (a b : nat) (h : a = b) : (if a = b then 0 else 1) = cond (if a = b then tt else ff) 0 1 := begin simp only [if_pos h, cond], end example (a b c : nat) : a + b + c = b + a + c := begin simp only [add_comm _ b] end example (a b c : nat) (h : c = 0) : a + b + 0 = b + a + c := begin simp only [add_comm _ b], guard_target b + a + 0 = b + a + c, rw h end example (a b c : nat) (h : c = 0) : 0 + (a + b) = b + a + c := begin simp only [add_comm _ c, add_comm a _], guard_target 0 + (b + a) = c + (b + a), rw h end
eabedcb98956c79e77c93daf8a838c595ddc9d2f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/int/range_auto.lean
e57c562322e9b777439979bcef5c505d33b67eb2
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,433
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro and Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.int.basic import Mathlib.data.list.range import Mathlib.PostPort namespace Mathlib namespace int /-- List enumerating `[m, n)`. -/ def range (m : ℤ) (n : ℤ) : List ℤ := list.map (fun (r : ℕ) => m + ↑r) (list.range (to_nat (n - m))) theorem mem_range_iff {m : ℤ} {n : ℤ} {r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := sorry protected instance decidable_le_lt (P : ℤ → Prop) [decidable_pred P] (m : ℤ) (n : ℤ) : Decidable (∀ (r : ℤ), m ≤ r → r < n → P r) := decidable_of_iff (∀ (r : ℤ), r ∈ range m n → P r) sorry protected instance decidable_le_le (P : ℤ → Prop) [decidable_pred P] (m : ℤ) (n : ℤ) : Decidable (∀ (r : ℤ), m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ (r : ℤ), r ∈ range m (n + 1) → P r) sorry protected instance decidable_lt_lt (P : ℤ → Prop) [decidable_pred P] (m : ℤ) (n : ℤ) : Decidable (∀ (r : ℤ), m < r → r < n → P r) := int.decidable_le_lt P (m + 1) n protected instance decidable_lt_le (P : ℤ → Prop) [decidable_pred P] (m : ℤ) (n : ℤ) : Decidable (∀ (r : ℤ), m < r → r ≤ n → P r) := int.decidable_le_le P (m + 1) n end Mathlib
362f0d66396fa70a86b1792ed31af8c92950551d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/open_fwd_bug.lean
c3b760f772e0dd15378dbe1244b93dabb5b5fa76
[ "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
21
lean
open - [forward] nat
286a303ca04b7ca6a03ed025281f62b380b38cea
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sum/default_auto.lean
db2573ea5726c424f519feb537c843aca22beb0f
[]
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
262
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.sum.basic namespace Mathlib end Mathlib
3e2b45def9890aa77813e18b4135d0c11557076c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/delta_instance.lean
0ffaf586c8a990f2e4e8749445cf3994ac93de4f
[ "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
3,063
lean
/- Copyright (c) 2019 Rob Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rob Lewis -/ import tactic.simp_result namespace tactic /-- `delta_instance ids` tries to solve the goal by calling `apply_instance`, first unfolding the definitions in `ids`. -/ -- We call `dsimp_result` here because otherwise -- `delta_target` will insert an `id` in the result. -- See the note [locally reducible category instances] -- https://github.com/leanprover-community/mathlib/blob/c9fca15420e2ad443707ace831679fd1762580fe/src/algebra/category/Mon/basic.lean#L27 -- for an example where this used to cause a problem. meta def delta_instance (ids : list name) : tactic unit := dsimp_result (intros >> reset_instance_cache >> delta_target ids >> apply_instance >> done) namespace interactive setup_tactic_parser /-- `delta_instance id₁ id₂ ...` tries to solve the goal by calling `apply_instance`, first unfolding the definitions in `idᵢ`. -/ meta def delta_instance (ids : parse ident*) : itactic := tactic.delta_instance ids end interactive /-- Guess a name for an instance from its expression. This is a poor-man's version of the C++ `heuristic_inst_name`, and tries much less hard to pick a good name. -/ meta def delta_instance_name : pexpr → string | (expr.app f _) := delta_instance_name f | (expr.pi _ _ _ body) := delta_instance_name body | (expr.lam _ _ _ body) := delta_instance_name body | (expr.const nm _) := nm.last | _ := "inst" /-- Tries to derive instances by unfolding the newly introduced type and applying type class resolution. For example, ```lean @[derive ring] def new_int : Type := ℤ ``` adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`. Multiple instances can be added with `@[derive [ring, module ℝ]]`. This derive handler applies only to declarations made using `def`, and will fail on such a declaration if it is unable to derive an instance. It is run with higher priority than the built-in handlers, which will fail on `def`s. -/ @[derive_handler, priority 2000] meta def delta_instance_handler : derive_handler := λ cls new_decl_name, do env ← get_env, if env.is_inductive new_decl_name then return ff else do new_decl ← get_decl new_decl_name, new_decl_pexpr ← resolve_name new_decl_name, arity ← get_pexpr_arg_arity_with_tgt cls new_decl.type, tgt ← to_expr $ apply_under_n_pis cls new_decl_pexpr new_decl.type (new_decl.type.pi_arity - arity), (vs, tgt') ← open_pis tgt, tgt ← whnf tgt' transparency.none >>= pis vs, (_, inst) ← solve_aux tgt $ tactic.delta_instance [new_decl_name], inst ← instantiate_mvars inst, inst ← replace_univ_metas_with_univ_params inst, tgt ← instantiate_mvars tgt, nm ← get_unused_decl_name $ new_decl_name <.> (delta_instance_name cls), add_protected_decl $ declaration.defn nm inst.collect_univ_params tgt inst new_decl.reducibility_hints new_decl.is_trusted, set_basic_attribute `instance nm tt, return tt end tactic
5f84c8b56592a36f90fb574ceba28181867ee9b6
f7315930643edc12e76c229a742d5446dad77097
/library/algebra/order.lean
1a291fadbad78b9d9e60e650cdff166e36f1f194
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,545
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.order Author: Jeremy Avigad Various types of orders. We develop weak orders "≤" and strict orders "<" separately. We also consider structures with both, where the two are related by x < y ↔ (x ≤ y ∧ x ≠ y) (order_pair) x ≤ y ↔ (x < y ∨ x = y) (strong_order_pair) These might not hold constructively in some applications, but we can define additional structures with both < and ≤ as needed. -/ import logic.eq logic.connectives open eq eq.ops namespace algebra variable {A : Type} /- overloaded symbols -/ structure has_le [class] (A : Type) := (le : A → A → Prop) structure has_lt [class] (A : Type) := (lt : A → A → Prop) infixl `<=` := has_le.le infixl `≤` := has_le.le infixl `<` := has_lt.lt definition has_le.ge [reducible] {A : Type} [s : has_le A] (a b : A) := b ≤ a notation a ≥ b := has_le.ge a b notation a >= b := has_le.ge a b definition has_lt.gt [reducible] {A : Type} [s : has_lt A] (a b : A) := b < a notation a > b := has_lt.gt a b /- weak orders -/ structure weak_order [class] (A : Type) extends has_le A := (le_refl : ∀a, le a a) (le_trans : ∀a b c, le a b → le b c → le a c) (le_antisymm : ∀a b, le a b → le b a → a = b) section variable [s : weak_order A] include s theorem le.refl (a : A) : a ≤ a := !weak_order.le_refl theorem le.trans {a b c : A} : a ≤ b → b ≤ c → a ≤ c := !weak_order.le_trans calc_trans le.trans theorem ge.trans {a b c : A} (H1 : a ≥ b) (H2: b ≥ c) : a ≥ c := le.trans H2 H1 calc_trans ge.trans theorem le.antisymm {a b : A} : a ≤ b → b ≤ a → a = b := !weak_order.le_antisymm end structure linear_weak_order [class] (A : Type) extends weak_order A := (le_total : ∀a b, le a b ∨ le b a) theorem le.total [s : linear_weak_order A] (a b : A) : a ≤ b ∨ b ≤ a := !linear_weak_order.le_total /- strict orders -/ structure strict_order [class] (A : Type) extends has_lt A := (lt_irrefl : ∀a, ¬ lt a a) (lt_trans : ∀a b c, lt a b → lt b c → lt a c) section variable [s : strict_order A] include s theorem lt.irrefl (a : A) : ¬ a < a := !strict_order.lt_irrefl theorem lt.trans {a b c : A} : a < b → b < c → a < c := !strict_order.lt_trans calc_trans lt.trans theorem gt.trans {a b c : A} (H1 : a > b) (H2: b > c) : a > c := lt.trans H2 H1 calc_trans gt.trans theorem ne_of_lt {a b : A} (lt_ab : a < b) : a ≠ b := assume eq_ab : a = b, show false, from lt.irrefl b (eq_ab ▸ lt_ab) theorem ne_of_gt {a b : A} (gt_ab : a > b) : a ≠ b := ne.symm (ne_of_lt gt_ab) theorem lt.asymm {a b : A} (H : a < b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt.trans H H1) end /- well-founded orders -/ -- TODO: do these duplicate what Leo has done? if so, eliminate structure wf_strict_order [class] (A : Type) extends strict_order A := (wf_rec : ∀P : A → Type, (∀x, (∀y, lt y x → P y) → P x) → ∀x, P x) definition wf.rec_on {A : Type} [s : wf_strict_order A] {P : A → Type} (x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x := wf_strict_order.wf_rec P H x theorem wf.ind_on.{u v} {A : Type.{u}} [s : wf_strict_order.{u 0} A] {P : A → Prop} (x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x := wf.rec_on x H /- structures with a weak and a strict order -/ structure order_pair [class] (A : Type) extends weak_order A, has_lt A := (lt_iff_le_ne : ∀a b, lt a b ↔ (le a b ∧ a ≠ b)) section variable [s : order_pair A] variables {a b c : A} include s theorem lt_iff_le_and_ne : a < b ↔ (a ≤ b ∧ a ≠ b) := !order_pair.lt_iff_le_ne theorem le_of_lt (H : a < b) : a ≤ b := and.elim_left (iff.mp lt_iff_le_and_ne H) theorem lt_of_le_of_ne (H1 : a ≤ b) (H2 : a ≠ b) : a < b := iff.mp (iff.symm lt_iff_le_and_ne) (and.intro H1 H2) private theorem lt_irrefl (s' : order_pair A) (a : A) : ¬ a < a := assume H : a < a, have H1 : a ≠ a, from and.elim_right (iff.mp !lt_iff_le_and_ne H), H1 rfl private theorem lt_trans (s' : order_pair A) (a b c: A) (lt_ab : a < b) (lt_bc : b < c) : a < c := have le_ab : a ≤ b, from le_of_lt lt_ab, have le_bc : b ≤ c, from le_of_lt lt_bc, have le_ac : a ≤ c, from le.trans le_ab le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm le_ab le_ba, have ne_ab : a ≠ b, from and.elim_right (iff.mp lt_iff_le_and_ne lt_ab), ne_ab eq_ab, show a < c, from lt_of_le_of_ne le_ac ne_ac definition order_pair.to_strict_order [instance] [coercion] [reducible] : strict_order A := ⦃ strict_order, s, lt_irrefl := lt_irrefl s, lt_trans := lt_trans s ⦄ theorem lt_of_lt_of_le : a < b → b ≤ c → a < c := assume lt_ab : a < b, assume le_bc : b ≤ c, have le_ac : a ≤ c, from le.trans (le_of_lt lt_ab) le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm (le_of_lt lt_ab) le_ba, show false, from ne_of_lt lt_ab eq_ab, show a < c, from lt_of_le_of_ne le_ac ne_ac theorem lt_of_le_of_lt : a ≤ b → b < c → a < c := assume le_ab : a ≤ b, assume lt_bc : b < c, have le_ac : a ≤ c, from le.trans le_ab (le_of_lt lt_bc), have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_cb : c ≤ b, from eq_ac ▸ le_ab, have eq_bc : b = c, from le.antisymm (le_of_lt lt_bc) le_cb, show false, from ne_of_lt lt_bc eq_bc, show a < c, from lt_of_le_of_ne le_ac ne_ac theorem gt_of_gt_of_ge (H1 : a > b) (H2 : b ≥ c) : a > c := lt_of_le_of_lt H2 H1 theorem gt_of_ge_of_gt (H1 : a ≥ b) (H2 : b > c) : a > c := lt_of_lt_of_le H2 H1 calc_trans lt_of_lt_of_le calc_trans lt_of_le_of_lt calc_trans gt_of_gt_of_ge calc_trans gt_of_ge_of_gt theorem not_le_of_lt (H : a < b) : ¬ b ≤ a := assume H1 : b ≤ a, lt.irrefl _ (lt_of_lt_of_le H H1) theorem not_lt_of_le (H : a ≤ b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt_of_le_of_lt H H1) end structure strong_order_pair [class] (A : Type) extends order_pair A := (le_iff_lt_or_eq : ∀a b, le a b ↔ lt a b ∨ a = b) theorem le_iff_lt_or_eq [s : strong_order_pair A] {a b : A} : a ≤ b ↔ a < b ∨ a = b := !strong_order_pair.le_iff_lt_or_eq theorem lt_or_eq_of_le [s : strong_order_pair A] {a b : A} (le_ab : a ≤ b) : a < b ∨ a = b := iff.mp le_iff_lt_or_eq le_ab -- We can also construct a strong order pair by defining a strict order, and then defining -- x ≤ y ↔ x < y ∨ x = y structure strict_order_with_le [class] (A : Type) extends strict_order A, has_le A := (le_iff_lt_or_eq : ∀a b, le a b ↔ lt a b ∨ a = b) private theorem le_refl (s : strict_order_with_le A) (a : A) : a ≤ a := iff.mp (iff.symm !strict_order_with_le.le_iff_lt_or_eq) (or.intro_right _ rfl) private theorem le_trans (s : strict_order_with_le A) (a b c : A) (le_ab : a ≤ b) (le_bc : b ≤ c) : a ≤ c := or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab) (assume lt_ab : a < b, or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_bc) (assume lt_bc : b < c, iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (or.intro_left _ (lt.trans lt_ab lt_bc))) (assume eq_bc : b = c, eq_bc ▸ le_ab)) (assume eq_ab : a = b, eq_ab⁻¹ ▸ le_bc) private theorem le_antisymm (s : strict_order_with_le A) (a b : A) (le_ab : a ≤ b) (le_ba : b ≤ a) : a = b := or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ab) (assume lt_ab : a < b, or.elim (iff.mp !strict_order_with_le.le_iff_lt_or_eq le_ba) (assume lt_ba : b < a, absurd (lt.trans lt_ab lt_ba) (lt.irrefl a)) (assume eq_ba : b = a, eq_ba⁻¹)) (assume eq_ab : a = b, eq_ab) private theorem lt_iff_le_ne (s : strict_order_with_le A) (a b : A) : a < b ↔ a ≤ b ∧ a ≠ b := iff.intro (assume lt_ab : a < b, have le_ab : a ≤ b, from iff.elim_right !strict_order_with_le.le_iff_lt_or_eq (or.intro_left _ lt_ab), show a ≤ b ∧ a ≠ b, from and.intro le_ab (ne_of_lt lt_ab)) (assume H : a ≤ b ∧ a ≠ b, have H1 : a < b ∨ a = b, from iff.mp !strict_order_with_le.le_iff_lt_or_eq (and.elim_left H), show a < b, from or_resolve_left H1 (and.elim_right H)) definition strict_order_with_le.to_order_pair [instance] [coercion] [reducible] [s : strict_order_with_le A] : strong_order_pair A := ⦃ strong_order_pair, s, le_refl := le_refl s, le_trans := le_trans s, le_antisymm := le_antisymm s, lt_iff_le_ne := lt_iff_le_ne s ⦄ /- linear orders -/ structure linear_order_pair [class] (A : Type) extends order_pair A, linear_weak_order A structure linear_strong_order_pair [class] (A : Type) extends strong_order_pair A, linear_weak_order A section variable [s : linear_strong_order_pair A] variables (a b c : A) include s theorem lt.trichotomy : a < b ∨ a = b ∨ b < a := or.elim (le.total a b) (assume H : a ≤ b, or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inl H1) (assume H1, or.inr (or.inl H1))) (assume H : b ≤ a, or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inr (or.inr H1)) (assume H1, or.inr (or.inl (H1⁻¹)))) theorem lt.by_cases {a b : A} {P : Prop} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := or.elim !lt.trichotomy (assume H, H1 H) (assume H, or.elim H (assume H', H2 H') (assume H', H3 H')) definition linear_strong_order_pair.to_linear_order_pair [instance] [coercion] [reducible] : linear_order_pair A := ⦃ linear_order_pair, s ⦄ theorem le_of_not_lt {a b : A} (H : ¬ a < b) : b ≤ a := lt.by_cases (assume H', absurd H' H) (assume H', H' ▸ !le.refl) (assume H', le_of_lt H') theorem lt_of_not_le {a b : A} (H : ¬ a ≤ b) : b < a := lt.by_cases (assume H', absurd (le_of_lt H') H) (assume H', absurd (H' ▸ !le.refl) H) (assume H', H') theorem lt_or_ge : a < b ∨ a ≥ b := lt.by_cases (assume H1 : a < b, or.inl H1) (assume H1 : a = b, or.inr (H1 ▸ le.refl a)) (assume H1 : a > b, or.inr (le_of_lt H1)) theorem le_or_gt : a ≤ b ∨ a > b := !or.swap (lt_or_ge b a) theorem lt_or_gt_of_ne {a b : A} (H : a ≠ b) : a < b ∨ a > b := lt.by_cases (assume H1, or.inl H1) (assume H1, absurd H1 H) (assume H1, or.inr H1) end structure decidable_linear_order [class] (A : Type) extends linear_strong_order_pair A := (decidable_lt : decidable_rel lt) section variable [s : decidable_linear_order A] variables {a b c d : A} include s open decidable definition decidable_lt [instance] : decidable (a < b) := @decidable_linear_order.decidable_lt _ _ _ _ definition decidable_le [instance] : decidable (a ≤ b) := by_cases (assume H : a < b, inl (le_of_lt H)) (assume H : ¬ a < b, have H1 : b ≤ a, from le_of_not_lt H, by_cases (assume H2 : b < a, inr (not_le_of_lt H2)) (assume H2 : ¬ b < a, inl (le_of_not_lt H2))) definition decidable_eq [instance] : decidable (a = b) := by_cases (assume H : a ≤ b, by_cases (assume H1 : b ≤ a, inl (le.antisymm H H1)) (assume H1 : ¬ b ≤ a, inr (assume H2 : a = b, H1 (H2 ▸ le.refl a)))) (assume H : ¬ a ≤ b, (inr (assume H1 : a = b, H (H1 ▸ !le.refl)))) -- testing equality first may result in more definitional equalities definition lt.cases {B : Type} (a b : A) (t_lt t_eq t_gt : B) : B := if a = b then t_eq else (if a < b then t_lt else t_gt) theorem lt.cases_of_eq {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a = b) : lt.cases a b t_lt t_eq t_gt = t_eq := if_pos H theorem lt.cases_of_lt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a < b) : lt.cases a b t_lt t_eq t_gt = t_lt := if_neg (ne_of_lt H) ⬝ if_pos H theorem lt.cases_of_gt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a > b) : lt.cases a b t_lt t_eq t_gt = t_gt := if_neg (ne.symm (ne_of_lt H)) ⬝ if_neg (lt.asymm H) end end algebra /- For reference, these are all the transitivity rules defined in this file: calc_trans le.trans calc_trans lt.trans calc_trans lt_of_lt_of_le calc_trans lt_of_le_of_lt calc_trans ge.trans calc_trans gt.trans calc_trans gt_of_gt_of_ge calc_trans gt_of_ge_of_gt -/
0780b580576b7edcc0afece6e995c54657f0ad94
0dc59d2b959c9b11a672f655b104d7d7d3e37660
/Lean4_filters/Lattice/CompleteLattice.lean
abd63ea3e34765474cc17ee416679888d609f3de
[]
no_license
kbuzzard/lean4-filters
5aa17d95079ceb906622543209064151fa645e71
29f90055b7a2341c86d924954463c439bd128fb7
refs/heads/master
1,679,762,259,673
1,616,701,300,000
1,616,701,300,000
350,784,493
5
1
null
1,625,691,081,000
1,616,517,435,000
Lean
UTF-8
Lean
false
false
698
lean
import Lean4_filters.Tactics.Basic import Lean4_filters.Set.Basic class HasTop (P : Type u) where top : P notation "⊤" => HasTop.top class HasBot (P : Type u) where bot : P notation "⊥" => HasBot.bot class CompleteLattice (P : Type u) extends Lattice P, HasTop P, HasBot P where leTop : ∀ (a : P), a ≤ ⊤ botLe : ∀ (a : P), ⊥ ≤ a supr : Set P → P infi : Set P → P leSupr : ∀ (s : Set P) (a : P), a ∈ s → a ≤ supr s suprLe : ∀ (s : Set P) (a : P), (∀ (b : P), b ∈ s → b ≤ a) → supr s ≤ a infiLe : ∀ (s : Set P) (a : P), a ∈ s → infi s ≤ a leInfi : ∀ (s : Set P) (a : P), (∀ (b : P), b ∈ s → a ≤ b) → a ≤ infi s
94670b29e01084a2754dce13cd1e222bf7ea6e37
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/389.lean
0ace9ff205155b9080bd0d7de94b4378faba5e90
[ "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
274
lean
structure Foo (A : Sort _) := (foo : A) structure Bar (A : Sort _) extends Foo A := (bar : A) instance {A} : Coe (Bar A) (Foo A) := {coe := Bar.toFoo} def getFoo {A} (F : Foo A) := F.foo def bar : Bar Nat := {foo := 0, bar := 1} #check getFoo bar #check (getFoo bar : Nat)
087a82bc229d9197916147cf44015bfad502caa7
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/lua17.lean
1ff3333ec03d011f14986c3580c57396e617e217
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
249
lean
import Int. variables a b : Int print options (* local ios = io_state() print(get_options()) print(get_options()) ios:print(parse_lean("a + b")) print(parse_lean("fun x, a + x")) print(get_options()) *) print options print environment 2
eb486994a97fbccd5524168c13f4b6f777d17021
b7fc5b86b12212bea5542eb2c9d9f0988fd78697
/src/exercises_sources/thursday/groups_rings_fields.lean
6768f0ce579a04cb3ec21238e7c7287d8c9d952d
[]
no_license
stjordanis/lftcm2020
3b16591aec853c8546d9c8b69c0bf3f5f3956fee
1f3485e4dafdc587b451ec5144a1d8d3ec9b411e
refs/heads/master
1,675,958,865,413
1,609,901,722,000
1,609,901,722,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,271
lean
import linear_algebra.finite_dimensional import ring_theory.algebraic import data.zmod.basic import data.real.basic import tactic /-! ``` ____ / ___|_ __ ___ _ _ _ __ ___ | | _| '__/ _ \| | | | '_ \/ __| | |_| | | | (_) | |_| | |_) \__ \_ \____|_| \___/ \__,_| .__/|___( ) |_| |/ _ __ (_) _ __ __ _ ___ | '__| | | | '_ \ / _` | / __| | | | | | | | | | (_| | \__ \ _ |_| |_| |_| |_| \__, | |___/ ( ) |___/ |/ _ __ _ _ _ __ _ _ __ __| | / _| (_) ___ | | __| | ___ / _` | | '_ \ / _` | | |_ | | / _ \ | | / _` | / __| | (_| | | | | | | (_| | | _| | | | __/ | | | (_| | \__ \ \__,_| |_| |_| \__,_| |_| |_| \___| |_| \__,_| |___/ ``` -/ /-! ## Reminder on updating the exercises These instructions are now available at: https://leanprover-community.github.io/lftcm2020/exercises.html To get a new copy of the exercises, run the following commands in your terminal: ``` leanproject get lftcm2020 cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises code lftcm2020 ``` To update your exercise files, run the following commands: ``` cd /path/to/lftcm2020 git pull leanproject get-mathlib-cache ``` Don’t forget to copy the updated files to `src/my_exercises`. -/ /-! ## What do we have? Too much to cover in detail in 10 minutes. Take a look at the “General algebra” section on https://leanprover-community.github.io/mathlib-overview.html All the basic concepts are there: `group`, `ring`, `field`, `module`, etc... Also versions that are compatible with an ordering, like `ordered_ring` And versions that express compatibility with a topology: `topological_group` Finally constructions, like `polynomial R`, or `mv_polynomial σ R`, or `monoid_algebra K G`, or `ℤ_[p]`, or `zmod n`, or `localization R S`. -/ /-! ## Morphisms We are in the middle of a transition to “bundled” morphisms. (Why? Long story... but they work better with `simp`) * `X → Y` -- ordinary function * `X →+ Y` -- function respects `0` and `+` * `X →* Y` -- function respects `1` and `*` * `X →+* Y` -- function respects `0`, `1`, `+`, `*` (surprise!) -/ section variables {R S : Type*} [ring R] [ring S] -- We used to write example (f : R → S) [is_ring_hom f] : true := trivial -- But now we write example (f : R →+* S) : true := trivial /- This heavily relies on the “coercion to function” that we have seen a couple of times this week. -/ end /-! ## Where are these things in the library? `algebra/` for basic definitions and properties; “algebraic hierarchy” `group_theory/` ⎫ `ring_theory/` ⎬ “advanced” and “specialised” material `field_theory/` ⎭ `data/` definitions and examples To give an idea: * `algebra/ordered_ring.lean` * `ring_theory/noetherian.lean` * `field_theory/chevalley_warning.lean` * `data/nat/*.lean`, `data/real/*.lean`, `data/padics/*.lean` -/ /-! ## How to find things (search tools) * `library_search` -- it often helps to carve out the exact lemma statement that you are looking for * online documentation: https://leanprover-community.github.io/mathlib_docs/ new search bar under construction * Old-skool: `grep` * Search in VS Code: - `Ctrl - Shift - F` -- don't forget to change settings, to search everywhere -- click the three dots (`…`) below the search bar -- disable the blue cogwheel - `Ctrl - P` -- search for filenames - `Ctrl - P`, `#` -- search for lemmas and definitions -/ /-! ## How to find things (autocomplete) Mathlib follows pretty strict naming conventions: ``` /-- The binomial theorem-/ theorem add_pow [comm_semiring α] (x y : α) (n : ℕ) : (x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m := (commute.all x y).add_pow n ``` After a while, you get the hang of this, and you can start guessing names. -/ open_locale big_operators -- nice notation ∑, ∏ open finset -- `finset.range n` is the finite set `{0,1,..., n-1}` -- Demonstrate autocompletion example (f : ℕ → ℝ) (n : ℕ) : 57 + ∑ i in range (n+1), f i = 57 + f n + ∑ i in range n, f i := begin sorry end /-! ## How to find things (jump to definition) Another good strategy for finding useful results about `X`, is to “jump to the definition” and scroll through the next 3 screens of lemmas. If you are looking for a basic fact about `X`, you will usually find it there. -/ -- demonstrate “jump to definition” #check polynomial.coeff /-! ## Exercise 1 We will warm up with a well-known result: “Subgroups of abelian groups are normal.” Hints for proving this result: * Notice that `normal` is a structure, which you can see by going to the definition. The `constructor` tactic will help you to get started. -/ namespace add_subgroup variables {A : Type*} [add_comm_group A] lemma normal_of_add_comm_group (H : add_subgroup A) : normal H := begin sorry end end add_subgroup /-! ## Exercise 2 The following exercise will show the classical fact: “Finite field extensions are algebraic.” Hints for proving this result: * Look up the definition of `finite_dimensional`. * Search the library for useful lemmas about `is_algebraic` and `is_integral`. -/ namespace algebra variables {K L : Type*} [field K] [field L] [algebra K L] [finite_dimensional K L] lemma is_algebraic_of_finite_dimensional : is_algebraic K L := begin sorry end end algebra /-! ## Exercise 3 In this exercise we will define the Frobenius morphism. -/ section variables (p : ℕ) [fact p.prime] variables (K : Type*) [field K] [char_p K p] /-! ### Subchallenge -/ lemma add_pow_char' (x y : K) : (x + y) ^ p = x ^ p + y ^ p := begin -- Hint: `add_pow_char` already exists. -- You can use it if you don't want to spend time on this. /- Hints if you do want to attempt this: * `finset.sum_range_succ` * `finset.sum_eq_single` * `nat.prime.ne_zero` * `char_p.cast_eq_zero_iff` * `nat.prime.dvd_choose_self` -/ sorry end def frobenius_hom : K →+* K := { to_fun := λ x, x^p, map_zero' := begin -- Hint: `zero_pow`, search for lemmas near `nat.prime` sorry end, map_one' := begin sorry end, map_mul' := begin sorry end, map_add' := begin -- Hint: `add_pow_char` -- can you prove that one yourself? sorry end } end /-! ## Exercise 4 [challenging] The next exercise asks to show that a monic polynomial `f ∈ ℤ[X]` is irreducible if it is irreducible modulo a prime `p`. This fact is also not in mathlib. Hint: prove the helper lemma that is stated first. Follow-up question: Can you generalise `irreducible_of_irreducible_mod_prime`? -/ namespace polynomial variables {R S : Type*} [semiring R] [integral_domain S] (φ : R →+* S) /- Useful library lemmas (in no particular order): - `degree_eq_zero_of_is_unit` - `eq_C_of_degree_eq_zero` - `is_unit.map'` - `leading_coeff_C` - `degree_map_eq_of_leading_coeff_ne_zero` - `is_unit.map'` - `is_unit.ne_zero` -/ lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map' (f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := begin sorry end /- Useful library lemmas (in no particular order): - `is_unit.map'` - `is_unit_of_mul_is_unit_left` (also `_right`) - `leading_coeff_mul` - `is_unit_of_is_unit_leading_coeff_of_is_unit_map` (the helper lemma we just proved) - `is_unit_one` -/ lemma irreducible_of_irreducible_mod_prime (f : polynomial ℤ) (p : ℕ) [fact p.prime] (h_mon : monic f) (h_irr : irreducible (map (int.cast_ring_hom (zmod p)) f)) : irreducible f := begin sorry end end polynomial -- SCROLL DOWN FOR THE BONUS EXERCISE section /-! ## Bonus exercise (wicked hard) -/ noncomputable theory -- because `polynomial` is noncomputable (implementation detail) open polynomial -- we want to write `X`, instead of `polynomial.X` /- First we make some definitions Scroll to the end for the actual exercise -/ def partial_ramanujan_tau_polynomial (n : ℕ) : polynomial ℤ := X * ∏ k in finset.Ico 1 n, (1 - X^k)^24 def ramanujan_tau (n : ℕ) : ℤ := coeff (partial_ramanujan_tau_polynomial n) n -- Some nice suggestive notation prefix `τ`:300 := ramanujan_tau /- Some lemmas to warm up Hint: unfold definitions, `simp` -/ example : τ 0 = 0 := begin sorry end example : τ 1 = 1 := begin sorry end -- This one is nontrivial -- Use `have : subresult,` or state helper lemmas and prove them first! example : τ 2 = -24 := begin -- Really, we ought to have a tactic that makes this easy delta ramanujan_tau partial_ramanujan_tau_polynomial, rw [mul_comm, coeff_mul_X], suffices : ((1 - X) ^ 24 : polynomial ℤ).coeff 1 = -(24 : ℕ), by simpa, generalize : (24 : ℕ) = n, sorry end /- The actual exercise. Good luck (-; -/ theorem deligne (p : ℕ) (hp : p.prime) : (abs (τ p) : ℝ) ≤ 2 * p^(11/2) := begin sorry end end
eaed74e0f09dbc293c1eb7ac723b8f719548352b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/contradiction1.lean
46ec227dbd46edebabf3c2229c5e4f33bbf7d86d
[ "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
543
lean
inductive MyFin : Nat → Type | z : MyFin (n+1) | s : MyFin n → MyFin (n+1) theorem ex1 (x : MyFin 0) : False := by contradiction inductive Color | Red | Black open Color inductive rbnode : Nat → Color → Type where | Leaf : rbnode 1 Black | R {h} (left : rbnode h Black) (value : Int) (right : rbnode h Black) : rbnode h Red | B {h cl cr} (left : rbnode h cl) (value : Int) (right : rbnode h cr) : rbnode (h+1) Black theorem ex2 (x : rbnode 0 Color.Red) : False := by contradiction
25a8862d1c02f3044d50bee705aaff496a7f78e2
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/analysis/normed_space/basic.lean
80c3dae6db8f5727651ac21b32e0d3adae5f51fc
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
23,940
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.basic import topology.instances.nnreal topology.instances.complex import topology.algebra.module variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp), eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h, dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_triangle_sum {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) := finset.le_sum_of_subadditive norm norm_zero norm_triangle lemma norm_pos_iff (g : α) : 0 < ∥ g ∥ ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma norm_reverse_triangle' (a b : α) : ∥a∥ - ∥b∥ ≤ ∥a - b∥ := by simpa using add_le_add (norm_triangle (a - b) (b)) (le_refl (-∥b∥)) lemma norm_reverse_triangle (a b : α) : abs(∥a∥ - ∥b∥) ≤ ∥a - b∥ := suffices -(∥a∥ - ∥b∥) ≤ ∥a - b∥, from abs_le_of_le_of_neg_le (norm_reverse_triangle' a b) this, calc -(∥a∥ - ∥b∥) = ∥b∥ - ∥a∥ : by abel ... ≤ ∥b - a∥ : norm_reverse_triangle' b a ... = ∥a - b∥ : by rw ← norm_neg (a - b); simp lemma norm_triangle_sub {a b : α} : ∥a - b∥ ≤ ∥a∥ + ∥b∥ := by simpa only [sub_eq_add_neg, norm_neg] using norm_triangle a (-b) lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by rw ←norm_neg; simp lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (nhds 0) ↔ ∀ ε > 0, { x | ∥ f x ∥ < ε } ∈ l := begin rw [metric.tendsto_nhds], simp only [normed_group.dist_eq, sub_zero], split, { intros h ε εgt0, rcases h ε εgt0 with ⟨s, ssets, hs⟩, exact mem_sets_of_superset ssets hs }, intros h ε εgt0, exact ⟨_, h ε εgt0, set.subset.refl _⟩ end section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := nnreal.coe_le.2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e ∥) a (nhds 0) := have tendsto f a (nhds 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (nhds 0) := tendsto_iff_norm_tendsto_zero, by simpa lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x) lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous (λg:α, ∥g∥) := begin rw continuous_iff_continuous_at, intro x, rw [continuous_at, tendsto_iff_dist_tendsto_zero], exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm instance normed_uniform_group : uniform_add_group α := begin refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩, rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h, calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ : by simp [dist_eq_norm] ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_triangle_sub ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end instance normed_top_monoid : topological_add_monoid α := by apply_instance instance normed_top_group : topological_add_group α := by apply_instance end normed_group section normed_ring class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring instance normed_ring_top_monoid [normed_ring α] : topological_monoid α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd = e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel, begin apply squeeze_zero, { intro, apply norm_nonneg }, { simp only [this], intro, apply norm_triangle }, { rw ←zero_add (0 : ℝ), apply tendsto_add, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥, rw ←mul_sub, apply norm_mul_le }, { rw ←mul_zero (∥x.fst∥), apply tendsto_mul, { apply continuous_iff_continuous_at.1, apply continuous_norm.comp continuous_fst }, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_snd }}}, { apply squeeze_zero, { intro, apply norm_nonneg }, { intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥, rw ←sub_mul, apply norm_mul_le }, { rw ←zero_mul (∥x.snd∥), apply tendsto_mul, { apply tendsto_iff_norm_tendsto_zero.1, apply continuous_iff_continuous_at.1, apply continuous_fst }, { apply tendsto_const_nhds }}}} end ⟩ instance normed_top_ring [normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply lim_norm ⟩ class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 := have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul' ... = ∥(1 : α)∥ * 1 : by simp, eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this @[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := norm_mul } @[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n := is_monoid_hom.map_pow norm a @[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) : ∥s.prod f∥ = s.prod (λb, ∥f b∥) := eq.symm (finset.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := if hb : b = 0 then by simp [hb] else begin apply eq_div_of_mul_eq, { apply ne_of_gt, apply (norm_pos_iff _).mpr hb }, { rw [←normed_field.norm_mul, div_mul_cancel _ hb] } end @[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := by simp only [inv_eq_one_div, norm_div, norm_one] @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } end normed_field lemma real.norm_eq_abs (r : ℝ) : norm r = abs r := rfl @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] section normed_space class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends vector_space α β := (norm_smul : ∀ (a:α) (b:β), norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul := normed_field.norm_mul } set_option class.instance_max_depth 43 lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul s x lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp (continuous_iff_continuous_at.1 continuous_norm _) limg, have lim1 := tendsto_mul limf' limg', simp only [zero_mul, sub_eq_add_neg] at lim1, have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 := tendsto_mul (tendsto_const_nhds : tendsto _ _ (nhds ∥ s ∥)) limg3, simp only [sub_eq_add_neg, mul_zero] at lim2, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end lemma tendsto_smul_const {g : γ → F} {e : filter γ} (s : α) {b : F} : (tendsto g e (nhds b)) → tendsto (λ x, s • (g x)) e (nhds (s • b)) := tendsto_smul tendsto_const_nhds instance normed_space.topological_vector_space : topological_vector_space α E := { continuous_smul := continuous_iff_continuous_at.2 $ λp, tendsto_smul (continuous_iff_continuous_at.1 continuous_fst _) (continuous_iff_continuous_at.1 continuous_snd _) } open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos ((norm_pos_iff _).2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥), rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)] end, add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _), smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _), ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } end normed_space section summable open_locale classical open finset filter variables [normed_group α] [complete_space α] lemma summable_iff_vanishing_norm {f : ι → α} : summable f ↔ ∀ε>0, (∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε) := begin simp only [summable_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib], split, { assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] }, { assume h s ε hε hs, rcases h ε hε with ⟨t, ht⟩, refine ⟨t, assume u hu, hs _⟩, rw [ball_0_eq], exact ht u hu } end lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hf : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := summable_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hf ε hε in ⟨s, assume t ht, have ∥t.sum g∥ < ε := hs t ht, have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_triangle_sum t f) $ lt_of_le_of_lt (finset.sum_le_sum $ assume i _, h i) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑i, f i)∥ ≤ (∑ i, ∥f i∥) := have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (nhds ∥(∑ i, f i)∥) := (continuous_norm.tendsto _).comp (has_sum_tsum $ summable_of_summable_norm hf), have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (nhds (∑ i, ∥f i∥)) := has_sum_tsum hf, le_of_tendsto_of_tendsto at_top_ne_bot h₁ h₂ $ univ_mem_sets' $ assume s, norm_triangle_sum _ _ end summable namespace complex instance : normed_field ℂ := { norm := complex.abs, dist_eq := λ _ _, rfl, norm_mul' := complex.abs_mul, .. complex.discrete_field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := complex.abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := complex.abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn end complex
bcf79d2de063ac60bc0fcb316960b4c910041058
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/local_ctx_bug.lean
3e167f5209f47d8716d876b0dc07b40f3f9732fb
[ "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
888
lean
import data.finset data.finset.card data.finset.equiv open nat decidable namespace finset variable {A : Type} open finset (to_nat) open finset (of_nat) private lemma of_nat_eq_insert : ∀ {n s : nat}, n ∉ of_nat s → of_nat (2^n + s) = insert n (of_nat s) | 0 s h := sorry | (succ n) s h := have n ∉ of_nat s, from sorry, assert of_nat s = insert n (of_nat s), from sorry, finset.ext (λ x, have gen : ∀ m, m ∈ of_nat (2^(succ n) + s) ↔ m ∈ insert (succ n) (of_nat s) | zero := assert aux₁ : odd (2^(succ n) + s) ↔ odd s, from sorry, calc 0 ∈ of_nat (2^(succ n) + s) ↔ odd (2^(succ n) + s) : sorry ... ↔ odd s : aux₁ ... ↔ 0 ∈ insert (succ n) (of_nat s) : sorry | (succ m) := sorry, gen x) end finset
aa039ec9627d69b0d2ec47fce03b43889575a6b0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/moments.lean
64126645bbb0acf0c8d02aed004adc4582ea48f0
[ "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
15,764
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import probability.variance /-! # Moments and moment generating function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `probability_theory.moment X p μ`: `p`th moment of a real random variable `X` with respect to measure `μ`, `μ[X^p]` * `probability_theory.central_moment X p μ`:`p`th central moment of `X` with respect to measure `μ`, `μ[(X - μ[X])^p]` * `probability_theory.mgf X μ t`: moment generating function of `X` with respect to measure `μ`, `μ[exp(t*X)]` * `probability_theory.cgf X μ t`: cumulant generating function, logarithm of the moment generating function ## Main results * `probability_theory.indep_fun.mgf_add`: if two real random variables `X` and `Y` are independent and their mgf are defined at `t`, then `mgf (X + Y) μ t = mgf X μ t * mgf Y μ t` * `probability_theory.indep_fun.cgf_add`: if two real random variables `X` and `Y` are independent and their mgf are defined at `t`, then `cgf (X + Y) μ t = cgf X μ t + cgf Y μ t` * `probability_theory.measure_ge_le_exp_cgf` and `probability_theory.measure_le_le_exp_cgf`: Chernoff bound on the upper (resp. lower) tail of a random variable. For `t` nonnegative such that the cgf exists, `ℙ(ε ≤ X) ≤ exp(- t*ε + cgf X ℙ t)`. See also `probability_theory.measure_ge_le_exp_mul_mgf` and `probability_theory.measure_le_le_exp_mul_mgf` for versions of these results using `mgf` instead of `cgf`. -/ open measure_theory filter finset real noncomputable theory open_locale big_operators measure_theory probability_theory ennreal nnreal namespace probability_theory variables {Ω ι : Type*} {m : measurable_space Ω} {X : Ω → ℝ} {p : ℕ} {μ : measure Ω} include m /-- Moment of a real random variable, `μ[X ^ p]`. -/ def moment (X : Ω → ℝ) (p : ℕ) (μ : measure Ω) : ℝ := μ[X ^ p] /-- Central moment of a real random variable, `μ[(X - μ[X]) ^ p]`. -/ def central_moment (X : Ω → ℝ) (p : ℕ) (μ : measure Ω) : ℝ := μ[(X - (λ x, μ[X])) ^ p] @[simp] lemma moment_zero (hp : p ≠ 0) : moment 0 p μ = 0 := by simp only [moment, hp, zero_pow', ne.def, not_false_iff, pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero] @[simp] lemma central_moment_zero (hp : p ≠ 0) : central_moment 0 p μ = 0 := by simp only [central_moment, hp, pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_sub, pi.pow_apply, pi.neg_apply, neg_zero, zero_pow', ne.def, not_false_iff] lemma central_moment_one' [is_finite_measure μ] (h_int : integrable X μ) : central_moment X 1 μ = (1 - (μ set.univ).to_real) * μ[X] := begin simp only [central_moment, pi.sub_apply, pow_one], rw integral_sub h_int (integrable_const _), simp only [sub_mul, integral_const, algebra.id.smul_eq_mul, one_mul], end @[simp] lemma central_moment_one [is_probability_measure μ] : central_moment X 1 μ = 0 := begin by_cases h_int : integrable X μ, { rw central_moment_one' h_int, simp only [measure_univ, ennreal.one_to_real, sub_self, zero_mul], }, { simp only [central_moment, pi.sub_apply, pow_one], have : ¬ integrable (λ x, X x - integral μ X) μ, { refine λ h_sub, h_int _, have h_add : X = (λ x, X x - integral μ X) + (λ x, integral μ X), { ext1 x, simp, }, rw h_add, exact h_sub.add (integrable_const _), }, rw integral_undef this, }, end lemma central_moment_two_eq_variance [is_finite_measure μ] (hX : mem_ℒp X 2 μ) : central_moment X 2 μ = variance X μ := by { rw hX.variance_eq, refl, } section moment_generating_function variables {t : ℝ} /-- Moment generating function of a real random variable `X`: `λ t, μ[exp(t*X)]`. -/ def mgf (X : Ω → ℝ) (μ : measure Ω) (t : ℝ) : ℝ := μ[λ ω, exp (t * X ω)] /-- Cumulant generating function of a real random variable `X`: `λ t, log μ[exp(t*X)]`. -/ def cgf (X : Ω → ℝ) (μ : measure Ω) (t : ℝ) : ℝ := log (mgf X μ t) @[simp] lemma mgf_zero_fun : mgf 0 μ t = (μ set.univ).to_real := by simp only [mgf, pi.zero_apply, mul_zero, exp_zero, integral_const, algebra.id.smul_eq_mul, mul_one] @[simp] lemma cgf_zero_fun : cgf 0 μ t = log (μ set.univ).to_real := by simp only [cgf, mgf_zero_fun] @[simp] lemma mgf_zero_measure : mgf X (0 : measure Ω) t = 0 := by simp only [mgf, integral_zero_measure] @[simp] lemma cgf_zero_measure : cgf X (0 : measure Ω) t = 0 := by simp only [cgf, log_zero, mgf_zero_measure] @[simp] lemma mgf_const' (c : ℝ) : mgf (λ _, c) μ t = (μ set.univ).to_real * exp (t * c) := by simp only [mgf, integral_const, algebra.id.smul_eq_mul] @[simp] lemma mgf_const (c : ℝ) [is_probability_measure μ] : mgf (λ _, c) μ t = exp (t * c) := by simp only [mgf_const', measure_univ, ennreal.one_to_real, one_mul] @[simp] lemma cgf_const' [is_finite_measure μ] (hμ : μ ≠ 0) (c : ℝ) : cgf (λ _, c) μ t = log (μ set.univ).to_real + t * c := begin simp only [cgf, mgf_const'], rw log_mul _ (exp_pos _).ne', { rw log_exp _, }, { rw [ne.def, ennreal.to_real_eq_zero_iff, measure.measure_univ_eq_zero], simp only [hμ, measure_ne_top μ set.univ, or_self, not_false_iff], }, end @[simp] lemma cgf_const [is_probability_measure μ] (c : ℝ) : cgf (λ _, c) μ t = t * c := by simp only [cgf, mgf_const, log_exp] @[simp] lemma mgf_zero' : mgf X μ 0 = (μ set.univ).to_real := by simp only [mgf, zero_mul, exp_zero, integral_const, algebra.id.smul_eq_mul, mul_one] @[simp] lemma mgf_zero [is_probability_measure μ] : mgf X μ 0 = 1 := by simp only [mgf_zero', measure_univ, ennreal.one_to_real] @[simp] lemma cgf_zero' : cgf X μ 0 = log (μ set.univ).to_real := by simp only [cgf, mgf_zero'] @[simp] lemma cgf_zero [is_probability_measure μ] : cgf X μ 0 = 0 := by simp only [cgf_zero', measure_univ, ennreal.one_to_real, log_one] lemma mgf_undef (hX : ¬ integrable (λ ω, exp (t * X ω)) μ) : mgf X μ t = 0 := by simp only [mgf, integral_undef hX] lemma cgf_undef (hX : ¬ integrable (λ ω, exp (t * X ω)) μ) : cgf X μ t = 0 := by simp only [cgf, mgf_undef hX, log_zero] lemma mgf_nonneg : 0 ≤ mgf X μ t := begin refine integral_nonneg _, intro ω, simp only [pi.zero_apply], exact (exp_pos _).le, end lemma mgf_pos' (hμ : μ ≠ 0) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) : 0 < mgf X μ t := begin simp_rw mgf, have : ∫ (x : Ω), exp (t * X x) ∂μ = ∫ (x : Ω) in set.univ, exp (t * X x) ∂μ, { simp only [measure.restrict_univ], }, rw [this, set_integral_pos_iff_support_of_nonneg_ae _ _], { have h_eq_univ : function.support (λ (x : Ω), exp (t * X x)) = set.univ, { ext1 x, simp only [function.mem_support, set.mem_univ, iff_true], exact (exp_pos _).ne', }, rw [h_eq_univ, set.inter_univ _], refine ne.bot_lt _, simp only [hμ, ennreal.bot_eq_zero, ne.def, measure.measure_univ_eq_zero, not_false_iff], }, { refine eventually_of_forall (λ x, _), rw pi.zero_apply, exact (exp_pos _).le, }, { rwa integrable_on_univ, }, end lemma mgf_pos [is_probability_measure μ] (h_int_X : integrable (λ ω, exp (t * X ω)) μ) : 0 < mgf X μ t := mgf_pos' (is_probability_measure.ne_zero μ) h_int_X lemma mgf_neg : mgf (-X) μ t = mgf X μ (-t) := by simp_rw [mgf, pi.neg_apply, mul_neg, neg_mul] lemma cgf_neg : cgf (-X) μ t = cgf X μ (-t) := by simp_rw [cgf, mgf_neg] /-- This is a trivial application of `indep_fun.comp` but it will come up frequently. -/ lemma indep_fun.exp_mul {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (s t : ℝ) : indep_fun (λ ω, exp (s * X ω)) (λ ω, exp (t * Y ω)) μ := begin have h_meas : ∀ t, measurable (λ x, exp (t * x)) := λ t, (measurable_id'.const_mul t).exp, change indep_fun ((λ x, exp (s * x)) ∘ X) ((λ x, exp (t * x)) ∘ Y) μ, exact indep_fun.comp h_indep (h_meas s) (h_meas t), end lemma indep_fun.mgf_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (hX : ae_strongly_measurable (λ ω, exp (t * X ω)) μ) (hY : ae_strongly_measurable (λ ω, exp (t * Y ω)) μ) : mgf (X + Y) μ t = mgf X μ t * mgf Y μ t := begin simp_rw [mgf, pi.add_apply, mul_add, exp_add], exact (h_indep.exp_mul t t).integral_mul hX hY, end lemma indep_fun.mgf_add' {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (hX : ae_strongly_measurable X μ) (hY : ae_strongly_measurable Y μ) : mgf (X + Y) μ t = mgf X μ t * mgf Y μ t := begin have A : continuous (λ (x : ℝ), exp (t * x)), by continuity, have h'X : ae_strongly_measurable (λ ω, exp (t * X ω)) μ := A.ae_strongly_measurable.comp_ae_measurable hX.ae_measurable, have h'Y : ae_strongly_measurable (λ ω, exp (t * Y ω)) μ := A.ae_strongly_measurable.comp_ae_measurable hY.ae_measurable, exact h_indep.mgf_add h'X h'Y end lemma indep_fun.cgf_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : cgf (X + Y) μ t = cgf X μ t + cgf Y μ t := begin by_cases hμ : μ = 0, { simp [hμ], }, simp only [cgf, h_indep.mgf_add h_int_X.ae_strongly_measurable h_int_Y.ae_strongly_measurable], exact log_mul (mgf_pos' hμ h_int_X).ne' (mgf_pos' hμ h_int_Y).ne', end lemma ae_strongly_measurable_exp_mul_add {X Y : Ω → ℝ} (h_int_X : ae_strongly_measurable (λ ω, exp (t * X ω)) μ) (h_int_Y : ae_strongly_measurable (λ ω, exp (t * Y ω)) μ) : ae_strongly_measurable (λ ω, exp (t * (X + Y) ω)) μ := begin simp_rw [pi.add_apply, mul_add, exp_add], exact ae_strongly_measurable.mul h_int_X h_int_Y, end lemma ae_strongly_measurable_exp_mul_sum {X : ι → Ω → ℝ} {s : finset ι} (h_int : ∀ i ∈ s, ae_strongly_measurable (λ ω, exp (t * X i ω)) μ) : ae_strongly_measurable (λ ω, exp (t * (∑ i in s, X i) ω)) μ := begin classical, induction s using finset.induction_on with i s hi_notin_s h_rec h_int, { simp only [pi.zero_apply, sum_apply, sum_empty, mul_zero, exp_zero], exact ae_strongly_measurable_const, }, { have : ∀ (i : ι), i ∈ s → ae_strongly_measurable (λ (ω : Ω), exp (t * X i ω)) μ, from λ i hi, h_int i (mem_insert_of_mem hi), specialize h_rec this, rw sum_insert hi_notin_s, apply ae_strongly_measurable_exp_mul_add (h_int i (mem_insert_self _ _)) h_rec } end lemma indep_fun.integrable_exp_mul_add {X Y : Ω → ℝ} (h_indep : indep_fun X Y μ) (h_int_X : integrable (λ ω, exp (t * X ω)) μ) (h_int_Y : integrable (λ ω, exp (t * Y ω)) μ) : integrable (λ ω, exp (t * (X + Y) ω)) μ := begin simp_rw [pi.add_apply, mul_add, exp_add], exact (h_indep.exp_mul t t).integrable_mul h_int_X h_int_Y, end lemma Indep_fun.integrable_exp_mul_sum [is_probability_measure μ] {X : ι → Ω → ℝ} (h_indep : Indep_fun (λ i, infer_instance) X μ) (h_meas : ∀ i, measurable (X i)) {s : finset ι} (h_int : ∀ i ∈ s, integrable (λ ω, exp (t * X i ω)) μ) : integrable (λ ω, exp (t * (∑ i in s, X i) ω)) μ := begin classical, induction s using finset.induction_on with i s hi_notin_s h_rec h_int, { simp only [pi.zero_apply, sum_apply, sum_empty, mul_zero, exp_zero], exact integrable_const _, }, { have : ∀ (i : ι), i ∈ s → integrable (λ (ω : Ω), exp (t * X i ω)) μ, from λ i hi, h_int i (mem_insert_of_mem hi), specialize h_rec this, rw sum_insert hi_notin_s, refine indep_fun.integrable_exp_mul_add _ (h_int i (mem_insert_self _ _)) h_rec, exact (h_indep.indep_fun_finset_sum_of_not_mem h_meas hi_notin_s).symm, }, end lemma Indep_fun.mgf_sum [is_probability_measure μ] {X : ι → Ω → ℝ} (h_indep : Indep_fun (λ i, infer_instance) X μ) (h_meas : ∀ i, measurable (X i)) (s : finset ι) : mgf (∑ i in s, X i) μ t = ∏ i in s, mgf (X i) μ t := begin classical, induction s using finset.induction_on with i s hi_notin_s h_rec h_int, { simp only [sum_empty, mgf_zero_fun, measure_univ, ennreal.one_to_real, prod_empty], }, { have h_int' : ∀ (i : ι), ae_strongly_measurable (λ (ω : Ω), exp (t * X i ω)) μ, from λ i, ((h_meas i).const_mul t).exp.ae_strongly_measurable, rw [sum_insert hi_notin_s, indep_fun.mgf_add (h_indep.indep_fun_finset_sum_of_not_mem h_meas hi_notin_s).symm (h_int' i) (ae_strongly_measurable_exp_mul_sum (λ i hi, h_int' i)), h_rec, prod_insert hi_notin_s] } end lemma Indep_fun.cgf_sum [is_probability_measure μ] {X : ι → Ω → ℝ} (h_indep : Indep_fun (λ i, infer_instance) X μ) (h_meas : ∀ i, measurable (X i)) {s : finset ι} (h_int : ∀ i ∈ s, integrable (λ ω, exp (t * X i ω)) μ) : cgf (∑ i in s, X i) μ t = ∑ i in s, cgf (X i) μ t := begin simp_rw cgf, rw ← log_prod _ _ (λ j hj, _), { rw h_indep.mgf_sum h_meas }, { exact (mgf_pos (h_int j hj)).ne', }, end /-- **Chernoff bound** on the upper tail of a real random variable. -/ lemma measure_ge_le_exp_mul_mgf [is_finite_measure μ] (ε : ℝ) (ht : 0 ≤ t) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | ε ≤ X ω}).to_real ≤ exp (- t * ε) * mgf X μ t := begin cases ht.eq_or_lt with ht_zero_eq ht_pos, { rw ht_zero_eq.symm, simp only [neg_zero, zero_mul, exp_zero, mgf_zero', one_mul], rw ennreal.to_real_le_to_real (measure_ne_top μ _) (measure_ne_top μ _), exact measure_mono (set.subset_univ _), }, calc (μ {ω | ε ≤ X ω}).to_real = (μ {ω | exp (t * ε) ≤ exp (t * X ω)}).to_real : begin congr' with ω, simp only [exp_le_exp, eq_iff_iff], exact ⟨λ h, mul_le_mul_of_nonneg_left h ht_pos.le, λ h, le_of_mul_le_mul_left h ht_pos⟩, end ... ≤ (exp (t * ε))⁻¹ * μ[λ ω, exp (t * X ω)] : begin have : exp (t * ε) * (μ {ω | exp (t * ε) ≤ exp (t * X ω)}).to_real ≤ μ[λ ω, exp (t * X ω)], from mul_meas_ge_le_integral_of_nonneg (λ x, (exp_pos _).le) h_int _, rwa [mul_comm (exp (t * ε))⁻¹, ← div_eq_mul_inv, le_div_iff' (exp_pos _)], end ... = exp (- t * ε) * mgf X μ t : by { rw [neg_mul, exp_neg], refl, }, end /-- **Chernoff bound** on the lower tail of a real random variable. -/ lemma measure_le_le_exp_mul_mgf [is_finite_measure μ] (ε : ℝ) (ht : t ≤ 0) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | X ω ≤ ε}).to_real ≤ exp (- t * ε) * mgf X μ t := begin rw [← neg_neg t, ← mgf_neg, neg_neg, ← neg_mul_neg (-t)], refine eq.trans_le _ (measure_ge_le_exp_mul_mgf (-ε) (neg_nonneg.mpr ht) _), { congr' with ω, simp only [pi.neg_apply, neg_le_neg_iff], }, { simp_rw [pi.neg_apply, neg_mul_neg], exact h_int, }, end /-- **Chernoff bound** on the upper tail of a real random variable. -/ lemma measure_ge_le_exp_cgf [is_finite_measure μ] (ε : ℝ) (ht : 0 ≤ t) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | ε ≤ X ω}).to_real ≤ exp (- t * ε + cgf X μ t) := begin refine (measure_ge_le_exp_mul_mgf ε ht h_int).trans _, rw exp_add, exact mul_le_mul le_rfl (le_exp_log _) mgf_nonneg (exp_pos _).le, end /-- **Chernoff bound** on the lower tail of a real random variable. -/ lemma measure_le_le_exp_cgf [is_finite_measure μ] (ε : ℝ) (ht : t ≤ 0) (h_int : integrable (λ ω, exp (t * X ω)) μ) : (μ {ω | X ω ≤ ε}).to_real ≤ exp (- t * ε + cgf X μ t) := begin refine (measure_le_le_exp_mul_mgf ε ht h_int).trans _, rw exp_add, exact mul_le_mul le_rfl (le_exp_log _) mgf_nonneg (exp_pos _).le, end end moment_generating_function end probability_theory
ae499671ea9b21ba1dc254ee3151a810cd894a6b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/equiv/embedding.lean
def6917e6f6227350e1b25971c8aabdb3e96d213
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,777
lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import logic.embedding import data.set.lattice /-! # Equivalences on embeddings This file shows some advanced equivalences on embeddings, useful for constructing larger embeddings from smaller ones. -/ open function.embedding namespace equiv /-- Embeddings from a sum type are equivalent to two separate embeddings with disjoint ranges. -/ def sum_embedding_equiv_prod_embedding_disjoint {α β γ : Type*} : ((α ⊕ β) ↪ γ) ≃ {f : (α ↪ γ) × (β ↪ γ) // disjoint (set.range f.1) (set.range f.2)} := { to_fun := λ f, ⟨(inl.trans f, inr.trans f), begin rintros _ ⟨⟨a, h⟩, ⟨b, rfl⟩⟩, simp only [trans_apply, inl_apply, inr_apply] at h, have : sum.inl a = sum.inr b := f.injective h, simp only at this, assumption end⟩, inv_fun := λ ⟨⟨f, g⟩, disj⟩, ⟨λ x, match x with | (sum.inl a) := f a | (sum.inr b) := g b end, begin rintros (a₁|b₁) (a₂|b₂) f_eq; simp only [equiv.coe_fn_symm_mk, sum.elim_inl, sum.elim_inr] at f_eq, { rw f.injective f_eq }, { simp! only at f_eq, exfalso, exact disj ⟨⟨a₁, by simp⟩, ⟨b₂, by simp [f_eq]⟩⟩ }, { simp! only at f_eq, exfalso, exact disj ⟨⟨a₂, by simp⟩, ⟨b₁, by simp [f_eq]⟩⟩ }, { rw g.injective f_eq } end⟩, left_inv := λ f, by { dsimp only, ext, cases x; simp! }, right_inv := λ ⟨⟨f, g⟩, _⟩, by { simp only [prod.mk.inj_iff], split; ext; simp! } } /-- Embeddings whose range lies within a set are equivalent to embeddings to that set. This is `function.embedding.cod_restrict` as an equiv. -/ def cod_restrict (α : Type*) {β : Type*} (bs : set β) : {f : α ↪ β // ∀ a, f a ∈ bs} ≃ (α ↪ bs) := { to_fun := λ f, (f : α ↪ β).cod_restrict bs f.prop, inv_fun := λ f, ⟨f.trans (function.embedding.subtype _), λ a, (f a).prop⟩, left_inv := λ x, by ext; refl, right_inv := λ x, by ext; refl } /-- Pairs of embeddings with disjoint ranges are equivalent to a dependent sum of embeddings, in which the second embedding cannot take values in the range of the first. -/ def prod_embedding_disjoint_equiv_sigma_embedding_restricted {α β γ : Type*} : {f : (α ↪ γ) × (β ↪ γ) // disjoint (set.range f.1) (set.range f.2)} ≃ (Σ f : α ↪ γ, β ↪ ↥((set.range f)ᶜ)) := (subtype_prod_equiv_sigma_subtype $ λ (a : α ↪ γ) (b : β ↪ _), disjoint (set.range a) (set.range b)).trans $ equiv.sigma_congr_right $ λ a, (subtype_equiv_prop begin ext f, rw [←set.range_subset_iff, set.subset_compl_iff_disjoint], exact disjoint.comm.trans disjoint_iff, end).trans (cod_restrict _ _) /-- A combination of the above results, allowing us to turn one embedding over a sum type into two dependent embeddings, the second of which avoids any members of the range of the first. This is helpful for constructing larger embeddings out of smaller ones. -/ def sum_embedding_equiv_sigma_embedding_restricted {α β γ : Type*} : ((α ⊕ β) ↪ γ) ≃ (Σ f : α ↪ γ, β ↪ ↥((set.range f)ᶜ)) := equiv.trans sum_embedding_equiv_prod_embedding_disjoint prod_embedding_disjoint_equiv_sigma_embedding_restricted /-- Embeddings from a single-member type are equivalent to members of the target type. -/ def unique_embedding_equiv_result {α β : Type*} [unique α] : (α ↪ β) ≃ β := { to_fun := λ f, f (default α), inv_fun := λ x, ⟨λ _, x, λ _ _ _, subsingleton.elim _ _⟩, left_inv := λ _, by { ext, simp_rw [function.embedding.coe_fn_mk], congr }, right_inv := λ _, by simp } end equiv
5e319d0088b9489714af8d690809efd440e7957b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/computability/partrec.lean
3e8274c3961b7a7ca30c4973f6c03a033c17c156
[ "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
28,403
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import computability.primrec import data.nat.psub import data.pfun /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable roption namespace nat section rfind parameter (p : ℕ →. bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : ∀m k, n ≤ k + m → acc (lbp p) k, { from λa, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} := suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m}, from this 0 (λ n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, h₂⟩, rcases decidable.lt_trichotomy m n with h₃|h₃|h₃, { exact h₂ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)), intros n h, cases decidable.lt_or_eq_of_le h with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : ℕ →. bool) : roption ℕ := ⟨_, λ h, (rfind_x p h).1⟩ theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := h.snd ▸ (rfind_x p h.fst).2.1 theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → ff ∈ p m := h.snd ▸ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom := iff.rfl theorem rfind_dom' {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom := exists_congr $ λ n, and_congr_right $ λ pn, ⟨λ H m h, (eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _), λ H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (h₂ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ λ h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ λ a h, let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in (p0 ▸ h₂ (zero_le _) : (@roption.none bool).dom) def rfind_opt {α} (f : ℕ → option α) : roption α := (rfind (λ n, (f n).is_some)).bind (λ n, f n) theorem rfind_opt_spec {α} {f : ℕ → option α} {a} (h : a ∈ rfind_opt f) : ∃ n, a ∈ f n := let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩ theorem rfind_opt_dom {α} {f : ℕ → option α} : (rfind_opt f).dom ↔ ∃ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩), λ h, begin have h' : ∃ n, (f n).is_some := h.imp (λ n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (λ n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊢, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {α} {f : ℕ → option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n := ⟨rfind_opt_spec, λ ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (ℕ →. ℕ) → Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec ↑(λ n : ℕ, n.unpair.1) | right : partrec ↑(λ n : ℕ, n.unpair.2) | pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n) | comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f) | prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n, n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f → partrec (λ a, rfind (λ n, (λ m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g := hf.of_eq (λ n, eq_some_iff.2 (H n)) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (λ n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (λ n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (λ n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (λ n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (λ a, (f a).bind (λ n, n.elim (g a) (λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ λ a, ext $ λ s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩, λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩ theorem ppred : partrec (λ n, ppred n) := have primrec₂ (λ n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).to₂, (of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $ λ n, begin cases n; simp, { exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {α σ} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec (λ n, roption.bind (decode α n) (λ a, (f a).map encode)) def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2) def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ) def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable (λ p : α × β, f p.1 p.2) theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ λ n, by simp; cases decode α n; simp theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp theorem computable.part {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf theorem computable₂.part {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : computable (λ a : α, s) := (primrec.const _).to_comp theorem of_option {f : α → option β} (hf : computable f) : partrec (λ a, (f a : roption β)) := (nat.partrec.ppred.comp hf).of_eq $ λ n, begin cases decode α n with a; simp, cases f a with b; simp end theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl protected theorem id : computable (@id α) := primrec.id.to_comp theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp theorem pair {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) := (hf.pair hg).of_eq $ λ n, by cases decode α n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length α) := primrec.list_length.to_comp theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode α _) := primrec.encode.to_comp protected theorem decode : computable (decode α) := primrec.decode.to_comp protected theorem of_nat (α) [denumerable α] : computable (of_nat α) := (primrec.of_nat _).to_comp theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some α) := primrec.option_some.to_comp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g := hf.of_eq (λ a, eq_some_iff.2 (H a)) theorem none : partrec (λ a : α, @roption.none σ) := nat.partrec.none.of_eq $ λ n, by cases decode α n; simp protected theorem some : partrec (@roption.some α) := computable.id theorem const' (s : roption σ) : partrec (λ a : α, s) := by haveI := classical.dec s.dom; exact (of_option (const (to_option s))).of_eq (λ a, of_to_option s) protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ λ n, by simp [(<*>)]; cases e : decode α n with a; simp [e, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (λ a b, roption.some (g a b)) hf hg theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ λ n, begin cases e : decode α n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [encodek] end theorem comp {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) := (hf.comp hg).of_eq $ λ n, by simp; cases e : decode α n with a; simp [e, encodek] theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrec₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := ⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp, λ h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end partrec₂ namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem comp {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, f (g a)) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ (λ a b, f (g a b)) := hf.comp hg end computable namespace computable₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end computable₂ namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) : partrec (λ a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (λ b, cond b 0 1)) .comp primrec.snd).to₂.to_comp).of_eq $ λ n, begin cases e : decode α n with a; simp [e, nat.rfind_zero_none, map_id'], congr, funext n, simp [roption.map_map, (∘)], apply map_id' (λ b, _), cases b; refl end theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) : partrec (λ a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).part.to₂).bind (of_option hf) theorem nat_cases_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec (λ a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $ λ a, begin simp, cases f a; simp, refine ext (λ b, ⟨λ H, _, λ H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ }, { have : ∀ m, (nat.elim (roption.some (g a)) (λ y IH, IH.bind (λ _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode2_iff {f : α →. σ} : partrec f ↔ nat.partrec (λ n, roption.bind (decode2 α n) (λ a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $ (map hf (computable.encode.comp snd).to₂).comp snd, λ h, map_encode_iff.1 $ by simpa [encodek2] using (nat_iff.2 h).comp (@computable.encode α _)⟩ theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) → partrec (λ (a : α), vector.m_of_fn (λ i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_roption_some {α n} : ∀ (f : fin n → α), vector.m_of_fn (λ i, roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n, (decode β n).bind (f a)) ↔ computable₂ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind (computable.comp hf fst).to₂.part) $ λ n, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; simp, λ hf, begin have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases (some option.none) (λ n, roption.map (f a.1) (decode β n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).to₂), refine this.of_eq (λ a, _), simp, cases decode β a.2; simp [encodek] end⟩ theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n, (decode β n).map (f a)) ↔ computable₂ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.part).of_eq $ λ a, by simp; induction f a; simp * theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂ theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : @computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ λ a, by cases o a; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ λ a, by cases f a; refl theorem option_map {f : α → option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : @computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f := suffices computable₂ (λ a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_concat] end theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ λ a, by simp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem option_some_iff {f : α →. σ} : partrec (λ a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ λ n, by simp [roption.bind_assoc, bind_some_eq_map], λ hf, hf.map (option_some.comp snd).to₂⟩ theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : @partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (λ (a : α), nat.cases (roption.some (f a)) (λ n, roption.bind (decode β n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.part $ ((@computable.decode β _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).to₂, this.of_eq $ λ a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) := have partrec (λ a, (option.cases_on (sum.cases_on (f a) (λ b, option.none) option.some : option γ) (some (sum.cases_on (f a) (λ b, some (g a b)) (λ c, option.none))) (λ c, (h a c).map option.some) : roption (option σ))) := option_cases_right (sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂) (sum_cases hf (option_some.comp hg) (const option.none).to₂) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp theorem sum_cases_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $ λ a, by cases f a; simp private lemma fix_aux {f : α →. σ ⊕ α} (hf : partrec f) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in (∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩, have : ∀ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨a₂, am₂, fa₂⟩, exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) }, cases n; simp [F] at h₂, {cases h₂}, rcases h₂ with h₂ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h h₂ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), ∃ n, sum.inl b ∈ F a n ∧ ∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩, exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ }, intros a₁ h₁, apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk, rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩, { refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, h₂⟩ }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩, { refine ⟨n, hn₁, λ m mn km, _⟩, cases lt_or_eq_of_le km with km km, { exact hn₂ _ mn km }, { exact km ▸ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, am₃⟩ } } } end theorem fix {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, roption.some s) f in have hF : partrec₂ F := partrec.nat_elim snd (sum_inr.comp fst).part (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).to₂ (hf.comp snd).to₂).to₂, let p := λ a n, @roption.map _ bool (λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in have hp : partrec₂ p := hF.map ((sum_cases computable.id (const tt).to₂ (const ff).to₂).comp snd).to₂, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $ λ a, ext $ λ b, by simp; apply fix_aux hf end partrec
62a267483356a738b7316365960c576cc62d9115
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/pnat/xgcd.lean
d10d9b5c6298ce137ea2bf00d9de4e695baf3ace
[ "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
13,386
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland This file sets up a version of the Euclidean algorithm that works only with natural numbers. Given a, b > 0, it computes the unique system (w, x, y, z, d) such that the following identities hold: w * z = x * y + 1 a = (w + x) d b = (y + z) d These equations force w, z, d > 0. They also imply that the integers a' = w + x = a / d and b' = y + z = b / d are coprime, and that d is the gcd of a and b. This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions. -/ import tactic.ring import tactic.abel namespace pnat open nat pnat /-- A term of xgcd_type is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1]. -/ @[derive inhabited] structure xgcd_type := (wp x y zp ap bp : ℕ) namespace xgcd_type variable (u : xgcd_type) instance : has_sizeof xgcd_type := ⟨λ u, u.bp⟩ /-- The has_repr instance converts terms to strings in a way that reflects the matrix/vector interpretation as above. -/ instance : has_repr xgcd_type := ⟨λ u, "[[[" ++ (repr (u.wp + 1)) ++ ", " ++ (repr u.x) ++ "], [" ++ (repr u.y) ++ ", " ++ (repr (u.zp + 1)) ++ "]], [" ++ (repr (u.ap + 1)) ++ ", " ++ (repr (u.bp + 1)) ++ "]]"⟩ def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : xgcd_type := mk w.val.pred x y z.val.pred a.val.pred b.val.pred def w : ℕ+ := succ_pnat u.wp def z : ℕ+ := succ_pnat u.zp def a : ℕ+ := succ_pnat u.ap def b : ℕ+ := succ_pnat u.bp def r : ℕ := (u.ap + 1) % (u.bp + 1) def q : ℕ := (u.ap + 1) / (u.bp + 1) def qp : ℕ := u.q - 1 /-- The map v gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map vp gives [sp, tp] such that v = [sp + 1, tp + 1]. -/ def vp : ℕ × ℕ := ⟨ u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp, u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp ⟩ def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩ def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩ theorem v_eq_succ_vp : u.v = succ₂ u.vp := by { ext; dsimp [v, vp, w, z, a, b, succ₂]; repeat { rw [nat.succ_eq_add_one] }; ring } /-- is_special holds if the matrix has determinant one. -/ def is_special : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y def is_special' : Prop := u.w * u.z = succ_pnat (u.x * u.y) theorem is_special_iff : u.is_special ↔ u.is_special' := begin dsimp [is_special, is_special'], split; intro h, { apply eq, dsimp [w, z, succ_pnat], rw [← h], repeat { rw [nat.succ_eq_add_one] }, ring }, { apply nat.succ.inj, replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [mul_coe, w, z] at h, repeat { rw [succ_pnat_coe, nat.succ_eq_add_one] at h }, repeat { rw [nat.succ_eq_add_one] }, rw [← h], ring } end /-- is_reduced holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system. -/ def is_reduced : Prop := u.ap = u.bp def is_reduced' : Prop := u.a = u.b theorem is_reduced_iff : u.is_reduced ↔ u.is_reduced' := ⟨ congr_arg succ_pnat, succ_pnat_inj ⟩ def flip : xgcd_type := { wp := u.zp, x := u.y, y := u.x, zp := u.wp, ap := u.bp, bp := u.ap } @[simp] theorem flip_w : (flip u).w = u.z := rfl @[simp] theorem flip_x : (flip u).x = u.y := rfl @[simp] theorem flip_y : (flip u).y = u.x := rfl @[simp] theorem flip_z : (flip u).z = u.w := rfl @[simp] theorem flip_a : (flip u).a = u.b := rfl @[simp] theorem flip_b : (flip u).b = u.a := rfl theorem flip_is_reduced : (flip u).is_reduced ↔ u.is_reduced := by { dsimp [is_reduced, flip], split; intro h; exact h.symm } theorem flip_is_special : (flip u).is_special ↔ u.is_special := by { dsimp [is_special, flip], rw[mul_comm u.x, mul_comm u.zp, add_comm u.zp] } theorem flip_v : (flip u).v = (u.v).swap := by { dsimp [v], ext, { simp only, ring }, { simp only, ring } } /-- Properties of division with remainder for a / b. -/ theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 := nat.mod_add_div (u.ap + 1) (u.bp + 1) theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 := begin by_cases hq : u.q = 0, { let h := u.rq_eq, rw [hr, hq, mul_zero, add_zero] at h, cases h }, { exact (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hq)).symm } end /-- The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying is_reduced. The gcd can be read off from this final system. -/ def start (a b : ℕ+) : xgcd_type := ⟨0, 0, 0, 0, a - 1, b - 1⟩ theorem start_is_special (a b : ℕ+) : (start a b).is_special := by { dsimp [start, is_special], refl } theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ := begin dsimp [start, v, xgcd_type.a, xgcd_type.b, w, z], rw [one_mul, one_mul, zero_mul, zero_mul, zero_add, add_zero], rw [← nat.pred_eq_sub_one, ← nat.pred_eq_sub_one], rw [nat.succ_pred_eq_of_pos a.pos, nat.succ_pred_eq_of_pos b.pos] end def finish : xgcd_type := xgcd_type.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp theorem finish_is_reduced : u.finish.is_reduced := by { dsimp [is_reduced], refl } theorem finish_is_special (hs : u.is_special) : u.finish.is_special := begin dsimp [is_special, finish] at hs ⊢, rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs], ring end theorem finish_v (hr : u.r = 0) : u.finish.v = u.v := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, rw [hr, zero_add] at ha, ext, { change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b, have : u.wp + 1 = u.w := rfl, rw [this, ← ha, u.qp_eq hr], ring }, { change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b, rw [← ha, u.qp_eq hr], ring } end /-- This is the main reduction step, which is used when u.r ≠ 0, or equivalently b does not divide a. -/ def step : xgcd_type := xgcd_type.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1) /-- We will apply the above step recursively. The following result is used to ensure that the process terminates. -/ theorem step_wf (hr : u.r ≠ 0) : sizeof u.step < sizeof u := begin change u.r - 1 < u.bp, have h₀ : (u.r - 1) + 1 = u.r := nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hr), have h₁ : u.r < u.bp + 1 := nat.mod_lt (u.ap + 1) u.bp.succ_pos, rw[← h₀] at h₁, exact lt_of_succ_lt_succ h₁, end theorem step_is_special (hs : u.is_special) : u.step.is_special := begin dsimp [is_special, step] at hs ⊢, rw [mul_add, mul_comm u.y u.x, ← hs], ring end /-- The reduction step does not change the product vector. -/ theorem step_v (hr : u.r ≠ 0) : u.step.v = (u.v).swap := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, let hr : (u.r - 1) + 1 = u.r := (add_comm _ 1).trans (nat.add_sub_of_le (nat.pos_of_ne_zero hr)), ext, { change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b, rw [← ha, hr], ring }, { change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b, rw [← ha, hr], ring } end /-- We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below. -/ def reduce : xgcd_type → xgcd_type | u := dite (u.r = 0) (λ h, u.finish) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, flip (reduce u.step)) theorem reduce_a {u : xgcd_type} (h : u.r = 0) : u.reduce = u.finish := by { rw [reduce], simp only, rw [if_pos h] } theorem reduce_b {u : xgcd_type} (h : u.r ≠ 0) : u.reduce = u.step.reduce.flip := by { rw [reduce], simp only, rw [if_neg h, step] } theorem reduce_reduced : ∀ (u : xgcd_type), u.reduce.is_reduced | u := dite (u.r = 0) (λ h, by { rw [reduce_a h], exact u.finish_is_reduced }) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h, flip_is_reduced], apply reduce_reduced }) theorem reduce_reduced' (u : xgcd_type) : u.reduce.is_reduced' := (is_reduced_iff _).mp u.reduce_reduced theorem reduce_special : ∀ (u : xgcd_type), u.is_special → u.reduce.is_special | u := dite (u.r = 0) (λ h hs, by { rw [reduce_a h], exact u.finish_is_special hs }) (λ h hs, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h], let u' := u.step.reduce, have : u'.is_special := reduce_special u.step (u.step_is_special hs), exact (flip_is_special _).mpr (reduce_special _ (u.step_is_special hs)) }) theorem reduce_special' (u : xgcd_type) (hs : u.is_special) : u.reduce.is_special' := (is_special_iff _).mp (u.reduce_special hs) theorem reduce_v : ∀ (u : xgcd_type), u.reduce.v = u.v | u := dite (u.r = 0) (λ h, by {rw[reduce_a h, finish_v u h]}) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw[reduce_b h, flip_v, reduce_v (step u), step_v u h, prod.swap_swap] }) end xgcd_type section gcd variables (a b : ℕ+) def xgcd: xgcd_type := (xgcd_type.start a b).reduce def gcd_d : ℕ+ := (xgcd a b).a def gcd_w : ℕ+ := (xgcd a b).w def gcd_x : ℕ := (xgcd a b).x def gcd_y : ℕ := (xgcd a b).y def gcd_z : ℕ+ := (xgcd a b).z def gcd_a' : ℕ+ := succ_pnat ((xgcd a b).wp + (xgcd a b).x) def gcd_b' : ℕ+ := succ_pnat ((xgcd a b).y + (xgcd a b).zp) theorem gcd_a'_coe : ((gcd_a' a b) : ℕ) = (gcd_w a b) + (gcd_x a b) := by { dsimp [gcd_a', gcd_w, xgcd_type.w], rw [nat.succ_eq_add_one, nat.succ_eq_add_one], ring } theorem gcd_b'_coe : ((gcd_b' a b) : ℕ) = (gcd_y a b) + (gcd_z a b) := by { dsimp [gcd_b', gcd_z, xgcd_type.z], rw [nat.succ_eq_add_one, nat.succ_eq_add_one], ring } theorem gcd_props : let d := gcd_d a b, w := gcd_w a b, x := gcd_x a b, y := gcd_y a b, z := gcd_z a b, a' := gcd_a' a b, b' := gcd_b' a b in (w * z = succ_pnat (x * y) ∧ (a = a' * d) ∧ (b = b' * d) ∧ z * a' = succ_pnat (x * b') ∧ w * b' = succ_pnat (y * a') ∧ (z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d ) := begin intros, let u := (xgcd_type.start a b), let ur := u.reduce, have ha : d = ur.a := rfl, have hb : d = ur.b := u.reduce_reduced', have ha' : (a' : ℕ) = w + x := gcd_a'_coe a b, have hb' : (b' : ℕ) = y + z := gcd_b'_coe a b, have hdet : w * z = succ_pnat (x * y) := u.reduce_special' rfl, split, exact hdet, have hdet' : ((w * z) : ℕ) = x * y + 1 := by { rw [← mul_coe, hdet, succ_pnat_coe] }, have huv : u.v = ⟨a, b⟩ := (xgcd_type.start_v a b), let hv : prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ := u.reduce_v.trans (xgcd_type.start_v a b), rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv, have ha'' : (a : ℕ) = a' * d := (congr_arg prod.fst hv).symm, have hb'' : (b : ℕ) = b' * d := (congr_arg prod.snd hv).symm, split, exact eq ha'', split, exact eq hb'', have hza' : (z * a' : ℕ) = x * b' + 1, by { rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'], ring }, have hwb' : (w * b' : ℕ) = y * a' + 1, by { rw [ha', hb', mul_add, mul_add, hdet'], ring }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hza'] }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hwb'] }, rw [ha'', hb''], repeat { rw [← mul_assoc] }, rw [hza', hwb'], split; ring, end theorem gcd_eq : gcd_d a b = gcd a b := begin rcases gcd_props a b with ⟨h₀, h₁, h₂, h₃, h₄, h₅, h₆⟩, apply dvd_antisymm, { apply dvd_gcd, exact dvd_intro (gcd_a' a b) (h₁.trans (mul_comm _ _)).symm, exact dvd_intro (gcd_b' a b) (h₂.trans (mul_comm _ _)).symm}, { have h₇ := calc ((gcd a b) : ℕ) ∣ a : nat.gcd_dvd_left a b ... ∣ (gcd_z a b) * a : dvd_mul_left _ _, have h₈ := calc ((gcd a b) : ℕ) ∣ b : nat.gcd_dvd_right a b ... ∣ (gcd_x a b) * b : dvd_mul_left _ _, rw[h₅] at h₇, exact (nat.dvd_add_iff_right h₈).mpr h₇} end theorem gcd_det_eq : (gcd_w a b) * (gcd_z a b) = succ_pnat ((gcd_x a b) * (gcd_y a b)) := (gcd_props a b).1 theorem gcd_a_eq : a = (gcd_a' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.1 theorem gcd_b_eq : b = (gcd_b' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.1 theorem gcd_rel_left' : (gcd_z a b) * (gcd_a' a b) = succ_pnat ((gcd_x a b) * (gcd_b' a b)) := (gcd_props a b).2.2.2.1 theorem gcd_rel_right' : (gcd_w a b) * (gcd_b' a b) = succ_pnat ((gcd_y a b) * (gcd_a' a b)) := (gcd_props a b).2.2.2.2.1 theorem gcd_rel_left : ((gcd_z a b) * a : ℕ) = (gcd_x a b) * b + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.1 theorem gcd_rel_right : ((gcd_w a b) * b : ℕ) = (gcd_y a b) * a + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.2 end gcd end pnat
036ab98fa11c78311b123c0fa80ed3ec5a0c159e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/gcd_monoid/nat.lean
a76b075f41962e389ac1376925c0aed9720b8661
[ "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
1,299
lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import algebra.gcd_monoid.finset import number_theory.padics.padic_norm /-! # Basic results about setwise gcds on ℕ This file proves some basic results about `finset.gcd` on `ℕ`. ## Main results * `finset.coprime_of_div_gcd`: The elements of a set divided through by their gcd are coprime. -/ instance : is_idempotent ℕ gcd_monoid.gcd := ⟨nat.gcd_self⟩ namespace finset theorem coprime_of_div_gcd (s : finset ℕ) {x : ℕ} (hx : x ∈ s) (hnz : x ≠ 0) : s.gcd (/ (s.gcd id)) = 1 := begin rw nat.eq_one_iff_not_exists_prime_dvd, intros p hp hdvd, haveI : fact p.prime := ⟨hp⟩, rw dvd_gcd_iff at hdvd, replace hdvd : ∀ b ∈ s, s.gcd id * p ∣ b, { intros b hb, specialize hdvd b hb, rwa nat.dvd_div_iff at hdvd, apply gcd_dvd hb }, have : s.gcd id ≠ 0 := (not_iff_not.mpr gcd_eq_zero_iff).mpr (λ h, hnz $ h x hx), apply @pow_succ_padic_val_nat_not_dvd p _ _ this.bot_lt, apply dvd_gcd, intros b hb, obtain ⟨k, rfl⟩ := hdvd b hb, rw [id, mul_right_comm, pow_succ', mul_dvd_mul_iff_right hp.ne_zero], apply dvd_mul_of_dvd_left, exact pow_padic_val_nat_dvd end end finset
ef80539d7bea3a34733be537733b85b67971050f
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_4/Part_B_option.lean
1f1073dadd630d2568f6bc5c70c7c043e81b855a
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
3,296
lean
import tactic /- # Option Much of this part is optional, if you just want to get to the topology. ## The definition If `X : Type` then `option X : Type` is a type with "one more element than `X`". The disadvantage of type theory over set theory is that distinct types are always disjoint. So if `x : X` then `x : option X` can't make sense. The way it's set up is that there's a map called `some : X → option X` which is an injection, and there's exactly one element of `option X` which is not in the image, and it's called `none`. ## The API Injectivity of `some` is `option.some_injective X : injective (some : X → option X)` and it's implied by `option.some_inj : some a = some b ↔ a = b` To define a function `option X → Y` we have to say where `some x` goes for `x : X`, and also where `none` goes. So we need a function `X → Y` for `some` and a term `y : Y` for `none`. You make the function itself with the recursor for `option`, namely `option.rec`. -/ variables {X Y : Type} def g (y : Y) (f : X → Y) : option X → Y := λ t, option.rec y f t -- I claim that `g` is the function we require. Note -- that `g` takes `f` and `y` as explicit inputs -- so it's `g f y`. Its values on `none` and `some x` are *by definition* -- what we want them to be: variables (f : X → Y) (y : Y) example : (g y f) none = y := begin refl end example (x : X) : (g y f) (some x) = f x := begin refl end -- That's all you need to know about `option` really, but -- it turns out that `option` is a `monad` so if you want to put -- off doing topology you could do this instead. -- https://en.wikipedia.org/wiki/Monad_%28category_theory%29 -- look at "formal definition" -- option is a functor `Type → Type`; we've defined it on objects -- so let's define it on morphisms: def option_func (f : X → Y) : option X → option Y := λ t, option.rec none (some ∘ f) t -- now check two axioms for a functor, `option_id` and `option_comp` -- NB you can do `cases ox with x` on `ox : option X` to break down into the -- `none` and `some x` cases. lemma option_id (ox : option X) : option_func (id : X → X) ox = ox := begin sorry end variable (Z : Type) lemma option_comp (f : X → Y) (g : Y → Z) (ox : option X) : option_func (g ∘ f) ox = (option_func g) (option_func f ox) := begin sorry end -- Now we define the structure of a monad, an `eta` and a `mu`. def eta {X : Type} : X → option X := some def mu {X : Type} : option (option X) → option X := -- function which sends `none` to `none` and `some ox` to `ox` λ t, option.rec none id t -- eta is a natural transformation lemma eta_nat (f : X → Y) (x : X) : option_func f (eta x) = eta (f x) := begin sorry end -- mu is a natural transformation lemma mu_nat (f : X → Y) (oox : option (option X)) : option_func f (mu oox) = mu (option_func (option_func f) oox) := begin sorry end -- coherence conditions (if I got them right!) lemma coherence1 (ooox : option (option (option X))) : mu ((option_func mu) ooox) = mu (mu ooox) := begin sorry end lemma coherence2a (ox : option X) : mu (eta ox) = ox := begin sorry end lemma coherence2b (ox : option X) : mu (option_func eta ox) = ox := begin sorry end -- please feel free to check -- I don't know much about monads!
6094f9039cfc713d3849af7650f3d41ef2d676eb
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/tactic14.lean
3476a9697f6fbbf33a8dd8b4b302f4b52a31bee4
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
440
lean
import Int. (* -- Tactic for trying to prove goal using reflexivity, congruence and available assumptions congr_tac = Try(unfold_tac("eq")) .. Repeat(OrElse(apply_tac("refl"), apply_tac("congr"), assumption_tac())) *) exit -- temporarily disable the following test theorem T1 (a b : Int) (f : Int -> Int) : a = b -> (f (f a)) = (f (f b)) := fun assumption : a = b, have (f (f a)) = (f (f b)) by congr_tac print environment 1.
f37d6b8e29f79f8f65d09cc07165924ced333f53
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/data/stream.lean
460abce775b206e369008d7405805b23030fdc0a
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,341
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ open nat function option universes u v w def stream (α : Type u) := nat → α namespace stream variables {α : Type u} {β : Type v} {δ : Type w} def cons (a : α) (s : stream α) : stream α := λ i, match i with | 0 := a | succ n := s n end notation h :: t := cons h t @[reducible] def head (s : stream α) : α := s 0 def tail (s : stream α) : stream α := λ i, s (i+1) def drop (n : nat) (s : stream α) : stream α := λ i, s (i+n) @[reducible] def nth (n : nat) (s : stream α) : α := s n protected lemma eta (s : stream α) : head s :: tail s = s := funext (λ i, begin cases i, repeat {reflexivity} end) lemma nth_zero_cons (a : α) (s : stream α) : nth 0 (a :: s) = a := rfl lemma head_cons (a : α) (s : stream α) : head (a :: s) = a := rfl lemma tail_cons (a : α) (s : stream α) : tail (a :: s) = s := rfl lemma tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) := funext (λ i, begin unfold tail drop, simp end) lemma nth_drop (n m : nat) (s : stream α) : nth n (drop m s) = nth (n+m) s := rfl lemma tail_eq_drop (s : stream α) : tail s = drop 1 s := rfl lemma drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s := funext (λ i, begin unfold drop, rw add_assoc end) lemma nth_succ (n : nat) (s : stream α) : nth (succ n) s = nth n (tail s) := rfl lemma drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) := rfl protected lemma ext {s₁ s₂ : stream α} : (∀ n, nth n s₁ = nth n s₂) → s₁ = s₂ := assume h, funext h def all (p : α → Prop) (s : stream α) := ∀ n, p (nth n s) def any (p : α → Prop) (s : stream α) := ∃ n, p (nth n s) lemma all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth n s) := rfl lemma any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth n s) := rfl protected def mem (a : α) (s : stream α) := any (λ b, a = b) s instance : has_mem α (stream α) := ⟨stream.mem⟩ lemma mem_cons (a : α) (s : stream α) : a ∈ (a::s) := exists.intro 0 rfl lemma mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s := assume ⟨n, h⟩, exists.intro (succ n) (by rw [nth_succ, tail_cons, h]) lemma eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s := assume ⟨n, h⟩, begin cases n with n', {left, exact h}, {right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩} end lemma mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth n s → a ∈ s := assume h, exists.intro n h section map variable (f : α → β) def map (s : stream α) : stream β := λ n, f (nth n s) lemma drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) := stream.ext (λ i, rfl) lemma nth_map (n : nat) (s : stream α) : nth n (map f s) = f (nth n s) := rfl lemma tail_map (s : stream α) : tail (map f s) = map f (tail s) := begin rw tail_eq_drop, reflexivity end lemma head_map (s : stream α) : head (map f s) = f (head s) := rfl lemma map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) := by rw [-stream.eta (map f s), tail_map, head_map] lemma map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s := begin rw [-stream.eta (map f (a :: s)), map_eq], reflexivity end lemma map_id (s : stream α) : map id s = s := rfl lemma map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl lemma mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s := assume ⟨n, h⟩, exists.intro n (by rw [nth_map, h]) end map section zip variable (f : α → β → δ) def zip (s₁ : stream α) (s₂ : stream β) : stream δ := λ n, f (nth n s₁) (nth n s₂) lemma drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) := stream.ext (λ i, rfl) lemma nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) : nth n (zip f s₁ s₂) = f (nth n s₁) (nth n s₂) := rfl lemma head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl lemma tail_zip (s₁ : stream α) (s₂ : stream β) : tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl lemma zip_eq (s₁ : stream α) (s₂ : stream β) : zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) := begin rw [-stream.eta (zip f s₁ s₂)], reflexivity end end zip def const (a : α) : stream α := λ n, a lemma mem_const (a : α) : a ∈ const a := exists.intro 0 rfl lemma const_eq (a : α) : const a = a :: const a := begin apply stream.ext, intro n, cases n, repeat {reflexivity} end lemma tail_const (a : α) : tail (const a) = const a := suffices tail (a :: const a) = const a, by rwa -const_eq at this, rfl lemma map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl lemma nth_const (n : nat) (a : α) : nth n (const a) = a := rfl lemma drop_const (n : nat) (a : α) : drop n (const a) = const a := stream.ext (λ i, rfl) def iterate (f : α → α) (a : α) : stream α := λ n, nat.rec_on n a (λ n r, f r) lemma head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl lemma tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) := begin apply funext, intro n, induction n with n' ih, {reflexivity}, {unfold tail iterate, unfold tail iterate at ih, rw add_one_eq_succ at ih, dsimp at ih, rw add_one_eq_succ, dsimp, rw ih} end lemma iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) := begin rw [-stream.eta (iterate f a)], rw tail_iterate, reflexivity end lemma nth_zero_iterate (f : α → α) (a : α) : nth 0 (iterate f a) = a := rfl lemma nth_succ_iterate (n : nat) (f : α → α) (a : α) : nth (succ n) (iterate f a) = nth n (iterate f (f a)) := by rw [nth_succ, tail_iterate] section bisim variable (R : stream α → stream α → Prop) local infix ~ := R def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂ lemma nth_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂} n, s₁ ~ s₂ → nth n s₁ = nth n s₂ ∧ drop (n+1) s₁ ~ drop (n+1) s₂ | s₁ s₂ 0 h := bisim h | s₁ s₂ (n+1) h := match bisim h with | ⟨h₁, trel⟩ := nth_of_bisim n trel end -- If two streams are bisimilar, then they are equal lemma eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ := λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r)) end bisim lemma bisim_simple (s₁ s₂ : stream α) : head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ := assume hh ht₁ ht₂, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂) (λ s₁ s₂ ⟨h₁, h₂, h₃⟩, begin constructor, exact h₁, rw [-h₂, -h₃], repeat {constructor, repeat {assumption}} end) (and.intro hh (and.intro ht₁ ht₂)) lemma coinduction {s₁ s₂ : stream α} : head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ := assume hh ht, eq_of_bisim (λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) (λ s₁ s₂ h, have h₁ : head s₁ = head s₂, from and.elim_left h, have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁, have h₃ : ∀ (β : Type u) (fr : stream α → β), fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)), from λ β fr, and.elim_right h β (λ s, fr (tail s)), and.intro h₁ (and.intro h₂ h₃)) (and.intro hh ht) lemma iterate_id (a : α) : iterate id a = const a := coinduction rfl (λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end) local attribute [reducible] stream lemma map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) := begin apply funext, intro n, induction n with n' ih, {reflexivity}, { unfold map iterate nth, dsimp, unfold map iterate nth at ih, dsimp at ih, rw ih } end section corec def corec (f : α → β) (g : α → α) : α → stream β := λ a, map f (iterate g a) def corec_on (a : α) (f : α → β) (g : α → α) : stream β := corec f g a lemma corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl lemma corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) := begin rw [corec_def, map_eq, head_iterate, tail_iterate], reflexivity end lemma corec_id_id_eq_const (a : α) : corec id id a = const a := by rw [corec_def, map_id, iterate_id] lemma corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl end corec -- corec is also known as unfold def unfolds (g : α → β) (f : α → α) (a : α) : stream β := corec g f a lemma unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) := begin unfold unfolds, rw [corec_eq] end lemma nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth n (unfolds head tail s) = nth n s := begin intro n, induction n with n' ih, {intro s, reflexivity}, {intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih]} end lemma unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s := λ s, stream.ext (λ n, nth_unfolds_head_tail n s) def interleave (s₁ s₂ : stream α) : stream α := corec_on (s₁, s₂) (λ ⟨s₁, s₂⟩, head s₁) (λ ⟨s₁, s₂⟩, (s₂, tail s₁)) infix `⋈`:65 := interleave lemma interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) := begin unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, reflexivity end lemma tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) := begin unfold interleave corec_on, rw corec_eq, reflexivity end lemma interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) := begin rw [interleave_eq s₁ s₂], reflexivity end lemma nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n) (s₁ ⋈ s₂) = nth n s₁ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n))) (s₁ ⋈ s₂) = nth (succ n) s₁, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left], reflexivity end lemma nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (2*n+1) (s₁ ⋈ s₂) = nth n s₂ | 0 s₁ s₂ := rfl | (succ n) s₁ s₂ := begin change nth (succ (succ (2*n+1))) (s₁ ⋈ s₂) = nth (succ n) s₂, rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right], reflexivity end lemma mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_interleave_left]) lemma mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_interleave_right]) def even (s : stream α) : stream α := corec (λ s, head s) (λ s, tail (tail s)) s def odd (s : stream α) : stream α := even (tail s) lemma odd_eq (s : stream α) : odd s = even (tail s) := rfl lemma head_even (s : stream α) : head (even s) = head s := rfl lemma tail_even (s : stream α) : tail (even s) = even (tail (tail s)) := begin unfold even, rw corec_eq, reflexivity end lemma even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s := begin unfold even, rw corec_eq, reflexivity end lemma even_tail (s : stream α) : even (tail s) = odd s := rfl lemma even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ := eq_of_bisim (λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂)) (λ s₁' s₁ ⟨s₂, h₁⟩, begin rw h₁, constructor, {refl}, {exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩} end) (exists.intro s₂ rfl) lemma interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ := eq_of_bisim (λ s' s, s' = even s ⋈ odd s) (λ s' s (h : s' = even s ⋈ odd s), begin rw h, constructor, {reflexivity}, {simp [odd_eq, odd_eq, tail_interleave, tail_even]} end) rfl lemma nth_even : ∀ (n : nat) (s : stream α), nth n (even s) = nth (2*n) s | 0 s := rfl | (succ n) s := begin change nth (succ n) (even s) = nth (succ (succ (2 * n))) s, rw [nth_succ, nth_succ, tail_even, nth_even], reflexivity end lemma nth_odd : ∀ (n : nat) (s : stream α), nth n (odd s) = nth (2*n + 1) s := λ n s, begin rw [odd_eq, nth_even], reflexivity end lemma mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n) (by rw [h, nth_even]) lemma mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s := assume ⟨n, h⟩, exists.intro (2*n+1) (by rw [h, nth_odd]) def append_stream : list α → stream α → stream α | [] s := s | (list.cons a l) s := a :: append_stream l s lemma nil_append_stream (s : stream α) : append_stream [] s = s := rfl lemma cons_append_stream (a : α) (l : list α) (s : stream α) : append_stream (a::l) s = a :: append_stream l s := rfl infix `++ₛ`:65 := append_stream lemma append_append_stream : ∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s) | [] l₂ s := rfl | (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream, append_append_stream] lemma map_append_stream (f : α → β) : ∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s | [] s := rfl | (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream, map_append_stream] lemma drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s | [] s := by reflexivity | (list.cons a l) s := by rw [list.length_cons, add_one_eq_succ, drop_succ, cons_append_stream, tail_cons, drop_append_stream] lemma append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s := by rw [cons_append_stream, nil_append_stream, stream.eta] lemma mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s | a [] s h := h | a (list.cons b l) s h := have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h, mem_cons_of_mem _ ih lemma mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s | a [] s h := absurd h (list.not_mem_nil _) | a (list.cons b l) s h := or.elim (list.eq_or_mem_of_mem_cons h) (λ (aeqb : a = b), exists.intro 0 aeqb) (λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl)) def approx : nat → stream α → list α | 0 s := [] | (n+1) s := list.cons (head s) (approx n (tail s)) lemma approx_zero (s : stream α) : approx 0 s = [] := rfl lemma approx_succ (n : nat) (s : stream α) : approx (succ n) s = head s :: approx n (tail s) := rfl lemma nth_approx : ∀ (n : nat) (s : stream α), list.nth (approx (succ n) s) n = some (nth n s) | 0 s := rfl | (n+1) s := begin rw [approx_succ, add_one_eq_succ, list.nth_succ, nth_approx], reflexivity end lemma append_approx_drop : ∀ (n : nat) (s : stream α), append_stream (approx n s) (drop n s) = s := begin intro n, induction n with n' ih, {intro s, reflexivity}, {intro s, rw [approx_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta]} end -- Take lemma reduces a proof of equality of infinite streams to an -- induction over all their finite approximations. lemma take_lemma (s₁ s₂ : stream α) : (∀ (n : nat), approx n s₁ = approx n s₂) → s₁ = s₂ := begin intro h, apply stream.ext, intro n, induction n with n ih, {note aux := h 1, unfold approx at aux, injection aux with aux, exact aux}, {assert h₁ : some (nth (succ n) s₁) = some (nth (succ n) s₂), {rw [-nth_approx, -nth_approx, h (succ (succ n))]}, injection h₁, assumption} end -- auxiliary def for cycle corecursive def private def cycle_f : α × list α × α × list α → α | (v, _, _, _) := v -- auxiliary def for cycle corecursive def private def cycle_g : α × list α × α × list α → α × list α × α × list α | (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀) | (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀) private lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) : cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl def cycle : Π (l : list α), l ≠ [] → stream α | [] h := absurd rfl h | (list.cons a l) h := corec cycle_f cycle_g (a, l, a, l) lemma cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h | [] h := absurd rfl h | (list.cons a l) h := have gen : ∀ l' a', corec cycle_f cycle_g (a', l', a, l) = (a' :: l') ++ₛ corec cycle_f cycle_g (a, l, a, l), begin intro l', induction l' with a₁ l₁ ih, {intros, rw [corec_eq], reflexivity}, {intros, rw [corec_eq, cycle_g_cons, ih a₁], reflexivity} end, gen l a lemma mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h := assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end lemma cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a := coinduction rfl (λ β fr ch, by rwa [cycle_eq, const_eq]) def tails (s : stream α) : stream (stream α) := corec id tail (tail s) lemma tails_eq (s : stream α) : tails s = tail s :: tails (tail s) := by unfold tails; rw [corec_eq]; reflexivity lemma nth_tails : ∀ (n : nat) (s : stream α), nth n (tails s) = drop n (tail s) := begin intro n, induction n with n' ih, {intros, reflexivity}, {intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih]} end lemma tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) := rfl def inits_core (l : list α) (s : stream α) : stream (list α) := corec_on (l, s) (λ ⟨a, b⟩, a) (λ p, match p with (l', s') := (l' ++ [head s'], tail s') end) def inits (s : stream α) : stream (list α) := inits_core [head s] (tail s) lemma inits_core_eq (l : list α) (s : stream α) : inits_core l s = l :: inits_core (l ++ [head s]) (tail s) := begin unfold inits_core corec_on, rw [corec_eq], reflexivity end lemma tail_inits (s : stream α) : tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) := begin unfold inits, rw inits_core_eq, reflexivity end lemma inits_tail (s : stream α) : inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl lemma cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α), a :: nth n (inits_core l s) = nth n (inits_core (a::l) s) := begin intros a n, induction n with n' ih, {intros, reflexivity}, {intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], reflexivity } end lemma nth_inits : ∀ (n : nat) (s : stream α), nth n (inits s) = approx (succ n) s := begin intro n, induction n with n' ih, {intros, reflexivity}, {intros, rw [nth_succ, approx_succ, -ih, tail_inits, inits_tail, cons_nth_inits_core]} end lemma inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) := begin apply stream.ext, intro n, cases n, {reflexivity}, {rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], reflexivity} end lemma zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s := begin apply stream.ext, intro n, rw [nth_zip, nth_inits, nth_tails, nth_const, approx_succ, cons_append_stream, append_approx_drop, stream.eta] end def pure (a : α) : stream α := const a def apply (f : stream (α → β)) (s : stream α) : stream β := λ n, (nth n f) (nth n s) infix `⊛`:75 := apply -- input as \o* lemma identity (s : stream α) : pure id ⊛ s = s := rfl lemma composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) : pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl lemma homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl lemma interchange (fs : stream (α → β)) (a : α) : fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs := rfl lemma map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s := rfl def nats : stream nat := λ n, n lemma nth_nats (n : nat) : nth n nats = n := rfl lemma nats_eq : nats = 0 :: map succ nats := begin apply stream.ext, intro n, cases n, reflexivity, rw [nth_succ], reflexivity end end stream
6ef0d036cecdf3819b6ab38452f1f2781557f955
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/calculus/deriv.lean
9ece092be761a79ea2b1afdc70d83fd7f7255f99
[ "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
70,682
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s \ {x}] x) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s] x) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[{x}ᶜ] x) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) : deriv_within f s x = deriv f x := by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl } section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg _) hh, calc map h (𝓝[s] x) ≤ 𝓝[h '' s] (h x) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (h x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (mem_nhds_sets (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv' $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} : differentiable_within_at 𝕜 (λx, c x / d) s x := by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc] @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : differentiable_at 𝕜 (λ x, c x / d) x := by simp [div_eq_inv_mul, hc] lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} : differentiable_on 𝕜 (λx, c x / d) s := by simp [div_eq_inv_mul, differentiable_on.const_mul, hc] @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} : differentiable 𝕜 (λx, c x / d) := by simp [div_eq_inv_mul, differentiable.const_mul, hc] lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : deriv (λx, c x / d) x = (deriv c x) / d := by simp [div_eq_inv_mul, deriv_const_mul, hc] end division theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_C_mul_X_pow], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, nat.sub_zero, nat.cast_one] }, { simp only [function.iterate_succ_apply', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i) : ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_strict_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_fpow m hx).has_deriv_at theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = (∏ i in finset.range k, (m - i) : ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, function.iterate_zero_apply, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [function.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], exact filter.eventually_eq.deriv_eq (eventually.mono (mem_nhds_sets is_open_ne hx) @ihk) } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in 𝓝[s \ {x}] x, (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in 𝓝[s] x, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
fee205b6c19ca77116cc3eefe6bdc20ffcef8569
ebb7367fa8ab324601b5abf705720fd4cc0e8598
/algebra/direct_sum.hlean
074d1d10518f7e7476cb153f933d4f835c0180d4
[ "Apache-2.0" ]
permissive
radams78/Spectral
3e34916d9bbd0939ee6a629e36744827ff27bfc2
c8145341046cfa2b4960ef3cc5a1117d12c43f63
refs/heads/master
1,610,421,583,830
1,481,232,014,000
1,481,232,014,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,348
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke Constructions with groups -/ import .quotient_group .free_commutative_group open eq algebra is_trunc set_quotient relation sigma prod sum list trunc function equiv sigma.ops namespace group variables {G G' : Group} (H : subgroup_rel G) (N : normal_subgroup_rel G) {g g' h h' k : G} {A B : AbGroup} variables (X : Set) {l l' : list (X ⊎ X)} section parameters {I : Set} (Y : I → AbGroup) variables {A' : AbGroup} definition dirsum_carrier : AbGroup := free_ab_group (trunctype.mk (Σi, Y i) _) local abbreviation ι [constructor] := @free_ab_group_inclusion inductive dirsum_rel : dirsum_carrier → Type := | rmk : Πi y₁ y₂, dirsum_rel (ι ⟨i, y₁⟩ * ι ⟨i, y₂⟩ * (ι ⟨i, y₁ * y₂⟩)⁻¹) definition dirsum : AbGroup := quotient_ab_group_gen dirsum_carrier (λg, ∥dirsum_rel g∥) -- definition dirsum_carrier_incl [constructor] (i : I) : Y i →g dirsum_carrier := definition dirsum_incl [constructor] (i : I) : Y i →g dirsum := homomorphism.mk (λy, class_of (ι ⟨i, y⟩)) begin intro g h, symmetry, apply gqg_eq_of_rel, apply tr, apply dirsum_rel.rmk end definition dirsum_elim_resp_quotient (f : Πi, Y i →g A') (g : dirsum_carrier) (r : ∥dirsum_rel g∥) : free_ab_group_elim (λv, f v.1 v.2) g = 1 := begin induction r with r, induction r, rewrite [to_respect_mul, to_respect_inv], apply mul_inv_eq_of_eq_mul, rewrite [one_mul, to_respect_mul, ▸*, ↑foldl, +one_mul, to_respect_mul] end definition dirsum_elim [constructor] (f : Πi, Y i →g A') : dirsum →g A' := gqg_elim _ (free_ab_group_elim (λv, f v.1 v.2)) (dirsum_elim_resp_quotient f) definition dirsum_elim_compute (f : Πi, Y i →g A') (i : I) : dirsum_elim f ∘g dirsum_incl i ~ f i := begin intro g, apply one_mul end definition dirsum_elim_unique (f : Πi, Y i →g A') (k : dirsum →g A') (H : Πi, k ∘g dirsum_incl i ~ f i) : k ~ dirsum_elim f := begin apply gqg_elim_unique, apply free_ab_group_elim_unique, intro x, induction x with i y, exact H i y end end end group
c379f63ed91d699f927856e4dd8db02cac6384fc
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/measure_theory/set_integral.lean
b4a741bc72ebce039ebf6d14c14539acad43d396
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
13,598
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.bochner_integration import measure_theory.indicator_function import measure_theory.lebesgue_measure /-! # Set integral Integrate a function over a subset of a measure space. ## Main definition `measurable_on`, `integrable_on`, `integral_on` ## Tags indicator, characteristic -/ noncomputable theory open_locale classical topological_space open set lattice filter topological_space ennreal emetric measure_theory set_option class.instance_max_depth 50 universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section measurable_on variables [measurable_space α] [measurable_space β] [has_zero β] {s : set α} {f : α → β} /-- `measurable_on s f` means `f` is measurable over the set `s`. -/ @[reducible] def measurable_on (s : set α) (f : α → β) : Prop := measurable (indicator s f) lemma measurable_on_empty : measurable_on ∅ f := by { rw [measurable_on, indicator_empty], exact measurable_const } lemma measurable_on_univ (hf : measurable f) : measurable_on univ f := hf.if is_measurable.univ measurable_const lemma measurable.measurable_on (hs : is_measurable s) (hf : measurable f) : measurable_on s f := hf.if hs measurable_const lemma is_measurable.inter_preimage {B : set β} (hs : is_measurable s) (hB : is_measurable B) (hf : measurable_on s f): is_measurable (s ∩ f ⁻¹' B) := begin replace hf : is_measurable ((indicator s f)⁻¹' B) := hf B hB, rw indicator_preimage at hf, replace hf := hf.diff _, rwa union_diff_cancel_right at hf, { assume a, simp {contextual := tt} }, exact hs.compl.inter (measurable_const.preimage hB) end lemma measurable_on.subset {t : set α} (hs : is_measurable s) (h : s ⊆ t) (hf : measurable_on t f) : measurable_on s f := begin have : measurable_on s (indicator t f) := measurable.measurable_on hs hf, simp only [measurable_on, indicator_indicator] at this, rwa [inter_eq_self_of_subset_left h] at this, end lemma measurable_on.union {t : set α} {f : α → β} (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (htm : measurable_on t f) : measurable_on (s ∪ t) f := begin assume B hB, show is_measurable ((indicator (s ∪ t) f)⁻¹' B), rw indicator_preimage, refine is_measurable.union _ ((hs.union ht).compl.inter (measurable_const.preimage hB)), simp only [union_inter_distrib_right], exact (hs.inter_preimage hB hsm).union (ht.inter_preimage hB htm) end lemma measurable_on_singleton {α} [topological_space α] [t1_space α] {a : α} {f : α → β} : measurable_on {a} f := λ s hs, show is_measurable ((indicator _ _)⁻¹' s), begin rw indicator_preimage, refine is_measurable.union _ (is_measurable_singleton.compl.inter $ measurable_const.preimage hs), by_cases h : a ∈ f⁻¹' s, { rw inter_eq_self_of_subset_left, { exact is_measurable_singleton }, rwa singleton_subset_iff }, rw [singleton_inter_eq_empty.2 h], exact is_measurable.empty end end measurable_on section integrable_on variables [measure_space α] [normed_group β] {s t : set α} {f g : α → β} /-- `integrable_on s f` means `f` is integrable over the set `s`. -/ @[reducible] def integrable_on (s : set α) (f : α → β) : Prop := integrable (indicator s f) lemma integrable_on_congr (h : ∀x, x ∈ s → f x = g x) : integrable_on s f ↔ integrable_on s g := by simp only [integrable_on, indicator_congr h] lemma integrable_on_congr_ae (h : ∀ₘx, x ∈ s → f x = g x) : integrable_on s f ↔ integrable_on s g := by { apply integrable_congr_ae, exact indicator_congr_ae h } lemma integrable_on_empty : integrable_on ∅ f := by { simp only [integrable_on, indicator_empty], apply integrable_zero } lemma integrable_on_of_integrable (s : set α) (hf : integrable f) : integrable_on s f := by { refine integrable_of_le (λa, _) hf, apply norm_indicator_le_norm_self } lemma integrable_on.subset (h : s ⊆ t) : integrable_on t f → integrable_on s f := by { apply integrable_of_le_ae, filter_upwards [] norm_indicator_le_of_subset h _ } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable_on.smul (s : set α) (c : 𝕜) {f : α → β} : integrable_on s f → integrable_on s (λa, c • f a) := by { simp only [integrable_on, indicator_smul], apply integrable.smul } lemma integrable_on.mul_left (s : set α) (r : ℝ) {f : α → ℝ} (hf : integrable_on s f) : integrable_on s (λa, r * f a) := by { simp only [smul_eq_mul.symm], exact hf.smul s r } lemma integrable_on.mul_right (s : set α) (r : ℝ) {f : α → ℝ} (hf : integrable_on s f) : integrable_on s (λa, f a * r) := by { simp only [mul_comm], exact hf.mul_left _ _ } lemma integrable_on.divide (s : set α) (r : ℝ) {f : α → ℝ} (hf : integrable_on s f) : integrable_on s (λa, f a / r) := by { simp only [div_eq_mul_inv], exact hf.mul_right _ _ } lemma integrable_on.add (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : integrable_on s (λa, f a + g a) := by { rw [integrable_on, indicator_add], exact hfi.add hfm hgm hgi } lemma integrable_on.neg (hf : integrable_on s f) : integrable_on s (λa, -f a) := by { rw [integrable_on, indicator_neg], exact hf.neg } lemma integrable_on.sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : integrable_on s (λa, f a - g a) := by { rw [integrable_on, indicator_sub], exact hfi.sub hfm hgm hgi } lemma integrable_on.union (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) : integrable_on (s ∪ t) f := begin rw ← union_diff_self, rw [integrable_on, indicator_union_of_disjoint], { refine integrable.add hsm hsi (htm.subset _ _) (hti.subset _), { exact ht.diff hs }, { exact diff_subset _ _ }, { exact diff_subset _ _ } }, exact disjoint_diff end lemma integrable_on_norm_iff (s : set α) (f : α → β) : integrable_on s (λa, ∥f a∥) ↔ integrable_on s f := begin simp only [integrable_on], convert integrable_norm_iff (indicator s f), funext, rw norm_indicator_eq_indicator_norm, end end integrable_on section integral_on variables [measure_space α] [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] {s t : set α} {f g : α → β} {a b : ℝ} {h : ℝ → β} notation `∫` binders ` in ` s `, ` r:(scoped f, integral (indicator s f)) := r variables (β) @[simp] lemma integral_on_zero (s : set α) : (∫ a in s, (0:β)) = 0 := by rw [indicator_zero, integral_zero] variables {β} lemma integral_on_congr (h : ∀ x ∈ s, f x = g x) : (∫ a in s, f a) = (∫ a in s, g a) := by simp only [indicator_congr h] lemma integral_on_congr_of_ae_eq (hf : measurable_on s f) (hg : measurable_on s g) (h : ∀ₘ x, x ∈ s → f x = g x) : (∫ a in s, f a) = (∫ a in s, g a) := integral_congr_ae hf hg (indicator_congr_ae h) lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f) (h : ∀ₘ x, x ∈ s ↔ x ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) := integral_congr_ae hsm htm $ indicator_congr_of_set h variables (s t) lemma integral_on_smul (r : ℝ) (f : α → β) : (∫ a in s, r • (f a)) = r • (∫ a in s, f a) := by rw [← integral_smul, indicator_smul] lemma integral_on_mul_left (r : ℝ) (f : α → ℝ) : (∫ a in s, r * (f a)) = r * (∫ a in s, f a) := integral_on_smul s r f lemma integral_on_mul_right (r : ℝ) (f : α → ℝ) : (∫ a in s, (f a) * r) = (∫ a in s, f a) * r := by { simp only [mul_comm], exact integral_on_mul_left s r f } lemma integral_on_div (r : ℝ) (f : α → ℝ) : (∫ a in s, (f a) / r) = (∫ a in s, f a) / r := by { simp only [div_eq_mul_inv], apply integral_on_mul_right } lemma integral_on_neg (f : α → β) : (∫ a in s, -f a) = - (∫ a in s, f a) := by { simp only [indicator_neg], exact integral_neg _ } variables {s t} lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) := by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi } lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) := by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi } lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ₘ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := begin apply integral_le_integral_ae hfm hfi hgm hgi, apply indicator_le_indicator_ae, exact h end lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] } lemma integral_on_union_ae (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : ∀ₘ a, a ∉ s ∩ t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := begin have := integral_congr_ae _ _ (indicator_union_ae h f), rw [this, integral_add hsm hsi htm hti], { exact hsm.union hs ht htm }, { exact hsm.add htm } end lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, is_measurable (s i)) (h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) := let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, exact hfm.subset (hsm i) (subset_Union _ _) }, { assumption }, { show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply all_ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) } end lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, is_measurable (s i)) (h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) := let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) }, { exact hfm.subset (is_measurable.Inter hsm) (Inter_subset _ _) }, { show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply all_ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) } end -- TODO : prove this for an encodable type -- by proving an encodable version of `filter.has_countable_basis_at_top_finset_nat` lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, is_measurable (s i)) (hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : (∫ a in (Union s), f a) = ∑i, ∫ a in s i, f a := suffices h : tendsto (λn:finset ℕ, n.sum (λ i, ∫ a in s i, f a)) at_top (𝓝 $ (∫ a in (Union s), f a)), by { rwa tsum_eq_has_sum }, begin have : (λn:finset ℕ, n.sum (λ i, ∫ a in s i, f a)) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a, { funext, rw [← integral_finset_sum, indicator_finset_bUnion], { assume i hi j hj hij, exact hd i j hij }, { assume i, refine hfm.subset (hm _) (subset_Union _ _) }, { assume i, refine hfi.subset (subset_Union _ _) } }, rw this, refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _, { exact indicator (Union s) (λ a, ∥f a∥) }, { exact has_countable_basis_at_top_finset_nat }, { refine univ_mem_sets' (λ n, _), simp only [mem_set_of_eq], refine hfm.subset (is_measurable.Union (λ i, is_measurable.Union_Prop (λh, hm _))) (bUnion_subset_Union _ _), }, { assumption }, { refine univ_mem_sets' (λ n, univ_mem_sets' $ _), simp only [mem_set_of_eq], assume a, rw ← norm_indicator_eq_indicator_norm, refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ }, { rw [← integrable_on, integrable_on_norm_iff], assumption }, { filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) } end end integral_on
a48071078df15377f8134620b83e1981253e4d8e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/isomorphism.lean
916b8cd2ca7bcc504a22d7546e1f454a29a39fc1
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,210
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor /-! # Isomorphisms This file defines isomorphisms between objects of a category. ## Main definitions - `structure iso` : a bundled isomorphism between two objects of a category; - `class is_iso` : an unbundled version of `iso`; note that `is_iso f` is a `Prop`, and only asserts the existence of an inverse. Of course, this inverse is unique, so it doesn't cost us much to use choice to retrieve it. - `inv f`, for the inverse of a morphism with `[is_iso f]` - `as_iso` : convert from `is_iso` to `iso` (noncomputable); - `of_iso` : convert from `iso` to `is_iso`; - standard operations on isomorphisms (composition, inverse etc) ## Notations - `X ≅ Y` : same as `iso X Y`; - `α ≪≫ β` : composition of two isomorphisms; it is called `iso.trans` ## Tags category, category theory, isomorphism -/ universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category /-- An isomorphism (a.k.a. an invertible morphism) between two objects of a category. The inverse morphism is bundled. See also `category_theory.core` for the category with the same objects and isomorphisms playing the role of morphisms. See https://stacks.math.columbia.edu/tag/0017. -/ structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp, reassoc] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [category.{v} C] variables {X Y Z : C} namespace iso @[ext] lemma ext ⦃α β : X ≅ Y⦄ (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] /-- Inverse isomorphism. -/ @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[simp] lemma symm_symm_eq {X Y : C} (α : X ≅ Y) : α.symm.symm = α := by cases α; refl @[simp] lemma symm_eq_iff {X Y : C} {α β : X ≅ Y} : α.symm = β.symm ↔ α = β := ⟨λ h, symm_symm_eq α ▸ symm_symm_eq β ▸ congr_arg symm h, congr_arg symm⟩ /-- Identity isomorphism. -/ @[refl, simps] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } instance : inhabited (X ≅ X) := ⟨iso.refl X⟩ @[simp] lemma refl_symm (X : C) : (iso.refl X).symm = iso.refl X := rfl /-- Composition of two isomorphisms -/ @[trans, simps] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = { hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).symm = β.symm ≪≫ α.symm := rfl @[simp] lemma trans_assoc {Z' : C} (α : X ≅ Y) (β : Y ≅ Z) (γ : Z ≅ Z') : (α ≪≫ β) ≪≫ γ = α ≪≫ β ≪≫ γ := by ext; simp only [trans_hom, category.assoc] @[simp] lemma refl_trans (α : X ≅ Y) : (iso.refl X) ≪≫ α = α := by ext; apply category.id_comp @[simp] lemma trans_refl (α : X ≅ Y) : α ≪≫ (iso.refl Y) = α := by ext; apply category.comp_id @[simp] lemma symm_self_id (α : X ≅ Y) : α.symm ≪≫ α = iso.refl Y := ext α.inv_hom_id @[simp] lemma self_symm_id (α : X ≅ Y) : α ≪≫ α.symm = iso.refl X := ext α.hom_inv_id @[simp] lemma symm_self_id_assoc (α : X ≅ Y) (β : Y ≅ Z) : α.symm ≪≫ α ≪≫ β = β := by rw [← trans_assoc, symm_self_id, refl_trans] @[simp] lemma self_symm_id_assoc (α : X ≅ Y) (β : X ≅ Z) : α ≪≫ α.symm ≪≫ β = β := by rw [← trans_assoc, self_symm_id, refl_trans] lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm lemma inv_eq_inv (f g : X ≅ Y) : f.inv = g.inv ↔ f.hom = g.hom := have ∀{X Y : C} (f g : X ≅ Y), f.hom = g.hom → f.inv = g.inv, from λ X Y f g h, by rw [ext h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (α : X ≅ Y) {f : Y ⟶ X} : α.hom ≫ f = 𝟙 X ↔ f = α.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (α : X ≅ Y) {f : Y ⟶ X} : f ≫ α.hom = 𝟙 Y ↔ f = α.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (α : X ≅ Y) (β : Y ≅ X) : α.hom = β.inv ↔ β.hom = α.inv := by { erw [inv_eq_inv α.symm β, eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. -/ def is_iso (f : X ⟶ Y) : Prop := ∃ inv : Y ⟶ X, f ≫ inv = 𝟙 X ∧ inv ≫ f = 𝟙 Y attribute [class] is_iso /-- The inverse of a morphism `f` when we have `[is_iso f]`. -/ noncomputable def inv (f : X ⟶ Y) [I : is_iso f] := classical.some I namespace is_iso @[simp, reassoc] lemma hom_inv_id (f : X ⟶ Y) [I : is_iso f] : f ≫ inv f = 𝟙 X := (classical.some_spec I).left @[simp, reassoc] lemma inv_hom_id (f : X ⟶ Y) [I : is_iso f] : inv f ≫ f = 𝟙 Y := (classical.some_spec I).right end is_iso open is_iso /-- Reinterpret a morphism `f` with an `is_iso f` instance as an `iso`. -/ noncomputable def as_iso (f : X ⟶ Y) [h : is_iso f] : X ≅ Y := ⟨f, inv f, hom_inv_id f, inv_hom_id f⟩ @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl namespace is_iso @[priority 100] -- see Note [lower instance priority] instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := λ Z g h w, -- This is an interesting test case for better rewrite automation. by rw [← is_iso.inv_hom_id_assoc f g, w, is_iso.inv_hom_id_assoc f h] } @[priority 100] -- see Note [lower instance priority] instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := λ Z g h w, by rw [← category.comp_id g, ← category.comp_id h, ← is_iso.hom_inv_id f, ← category.assoc, w, ← category.assoc] } @[ext] lemma inv_eq_of_hom_inv_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (hom_inv_id : f ≫ g = 𝟙 X) : inv f = g := begin apply (cancel_epi f).mp, simp [hom_inv_id], end lemma inv_eq_of_inv_hom_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (inv_hom_id : g ≫ f = 𝟙 Y) : inv f = g := begin apply (cancel_mono f).mp, simp [inv_hom_id], end @[ext] lemma eq_inv_of_hom_inv_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (hom_inv_id : f ≫ g = 𝟙 X) : g = inv f := (inv_eq_of_hom_inv_id hom_inv_id).symm lemma eq_inv_of_inv_hom_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (inv_hom_id : g ≫ f = 𝟙 Y) : g = inv f := (inv_eq_of_inv_hom_id inv_hom_id).symm instance id (X : C) : is_iso (𝟙 X) := ⟨𝟙 X, by simp⟩ instance of_iso (f : X ≅ Y) : is_iso f.hom := ⟨f.inv, by simp⟩ instance of_iso_inv (f : X ≅ Y) : is_iso f.inv := is_iso.of_iso f.symm variables {f g : X ⟶ Y} {h : Y ⟶ Z} instance inv_is_iso [is_iso f] : is_iso (inv f) := is_iso.of_iso_inv (as_iso f) instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := is_iso.of_iso $ (as_iso f) ≪≫ (as_iso h) @[simp] lemma inv_id : inv (𝟙 X) = 𝟙 X := by { ext, simp, } @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := by { ext, simp, } @[simp] lemma inv_inv [is_iso f] : inv (inv f) = f := by { ext, simp, } @[simp] lemma iso.inv_inv (f : X ≅ Y) : inv (f.inv) = f.hom := by { ext, simp, } @[simp] lemma iso.inv_hom (f : X ≅ Y) : inv (f.hom) = f.inv := by { ext, simp, } @[simp] lemma inv_comp_eq (α : X ⟶ Y) [is_iso α] {f : X ⟶ Z} {g : Y ⟶ Z} : inv α ≫ f = g ↔ f = α ≫ g := (as_iso α).inv_comp_eq @[simp] lemma eq_inv_comp (α : X ⟶ Y) [is_iso α] {f : X ⟶ Z} {g : Y ⟶ Z} : g = inv α ≫ f ↔ α ≫ g = f := (as_iso α).eq_inv_comp @[simp] lemma comp_inv_eq (α : X ⟶ Y) [is_iso α] {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ inv α = g ↔ f = g ≫ α := (as_iso α).comp_inv_eq @[simp] lemma eq_comp_inv (α : X ⟶ Y) [is_iso α] {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ inv α ↔ g ≫ α = f := (as_iso α).eq_comp_inv end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end lemma is_iso.inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) lemma hom_comp_eq_id (g : X ⟶ Y) [is_iso g] {f : Y ⟶ X} : g ≫ f = 𝟙 X ↔ f = inv g := (as_iso g).hom_comp_eq_id lemma comp_hom_eq_id (g : X ⟶ Y) [is_iso g] {f : Y ⟶ X} : f ≫ g = 𝟙 Y ↔ f = inv g := (as_iso g).comp_hom_eq_id namespace iso @[ext] lemma inv_ext {f : X ≅ Y} {g : Y ⟶ X} (hom_inv_id : f.hom ≫ g = 𝟙 X) : f.inv = g := begin apply (cancel_epi f.hom).mp, simp [hom_inv_id], end @[ext] lemma inv_ext' {f : X ≅ Y} {g : Y ⟶ X} (hom_inv_id : f.hom ≫ g = 𝟙 X) : g = f.inv := by { symmetry, ext, assumption, } /-! All these cancellation lemmas can be solved by `simp [cancel_mono]` (or `simp [cancel_epi]`), but with the current design `cancel_mono` is not a good `simp` lemma, because it generates a typeclass search. When we can see syntactically that a morphism is a `mono` or an `epi` because it came from an isomorphism, it's fine to do the cancellation via `simp`. In the longer term, it might be worth exploring making `mono` and `epi` structures, rather than typeclasses, with coercions back to `X ⟶ Y`. Presumably we could write `X ↪ Y` and `X ↠ Y`. -/ @[simp] lemma cancel_iso_hom_left {X Y Z : C} (f : X ≅ Y) (g g' : Y ⟶ Z) : f.hom ≫ g = f.hom ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_inv_left {X Y Z : C} (f : Y ≅ X) (g g' : Y ⟶ Z) : f.inv ≫ g = f.inv ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_hom_right {X Y Z : C} (f f' : X ⟶ Y) (g : Y ≅ Z) : f ≫ g.hom = f' ≫ g.hom ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_iso_inv_right {X Y Z : C} (f f' : X ⟶ Y) (g : Z ≅ Y) : f ≫ g.inv = f' ≫ g.inv ↔ f = f' := by simp only [cancel_mono] /- Unfortunately cancelling an isomorphism from the right of a chain of compositions is awkward. We would need separate lemmas for each chain length (worse: for each pair of chain lengths). We provide two more lemmas, for case of three morphisms, because this actually comes up in practice, but then stop. -/ @[simp] lemma cancel_iso_hom_right_assoc {W X X' Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) (h : Y ≅ Z) : f ≫ g ≫ h.hom = f' ≫ g' ≫ h.hom ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_iso_inv_right_assoc {W X X' Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) (h : Z ≅ Y) : f ≫ g ≫ h.inv = f' ≫ g' ≫ h.inv ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end iso namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [category.{v₂} D] /-- A functor `F : C ⥤ D` sends isomorphisms `i : X ≅ Y` to isomorphisms `F.obj X ≅ F.obj Y` -/ @[simps] def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_symm (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.map_iso i.symm = (F.map_iso i).symm := rfl @[simp] lemma map_iso_trans (F : C ⥤ D) {X Y Z : C} (i : X ≅ Y) (j : Y ≅ Z) : F.map_iso (i ≪≫ j) = (F.map_iso i) ≪≫ (F.map_iso j) := by ext; apply functor.map_comp @[simp] lemma map_iso_refl (F : C ⥤ D) (X : C) : F.map_iso (iso.refl X) = iso.refl (F.obj X) := iso.ext $ F.map_id X instance map_is_iso (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := is_iso.of_iso $ F.map_iso (as_iso f) @[simp] lemma map_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := by { ext, simp [←F.map_comp], } lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) := by simp lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) := by simp end functor end category_theory
5fbaff018ecee81b80be64ec6711267aab0e5a37
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Compiler/Util.lean
491d3761c492f6ef93c7ff4bed1afcfce143d062
[ "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
3,514
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.Environment namespace Lean namespace Compiler def neutralExpr : Expr := mkConst `_neutral def unreachableExpr : Expr := mkConst `_unreachable def objectType : Expr := mkConst `_obj def voidType : Expr := mkConst `_void def mkLcProof (pred : Expr) := mkApp (mkConst `lcProof []) pred namespace atMostOnce structure AtMostOnceData := (found result : Bool) def Visitor := AtMostOnceData → AtMostOnceData @[inline] def seq (f g : Visitor) : Visitor := fun d => match f d with | ⟨found, false⟩ => ⟨found, false⟩ | other => g other instance : HasAndthen Visitor := ⟨seq⟩ @[inline] def skip : Visitor := id @[inline] def visitFVar (x y : Name) : Visitor | d@{result := false, ..} => d | {found := false, result := true} => {found := x == y, result := true} | {found := true, result := true} => {found := true, result := x != y} def visit (x : Name) : Expr → Visitor | Expr.fvar y _ => visitFVar y x | Expr.app f a _ => visit a >> visit f | Expr.lam _ d b _ => visit d >> visit b | Expr.forallE _ d b _ => visit d >> visit b | Expr.letE _ t v b _ => visit t >> visit v >> visit b | Expr.mdata _ e _ => visit e | Expr.proj _ _ e _ => visit e | _ => skip end atMostOnce /-- Return true iff the free variable with id `x` occurs at most once in `e` -/ @[export lean_at_most_once] def atMostOnce (e : Expr) (x : Name) : Bool := let {result := result, ..} := atMostOnce.visit x e {found := false, result := true}; result /- Helper functions for creating auxiliary names used in compiler passes. -/ @[export lean_mk_eager_lambda_lifting_name] def mkEagerLambdaLiftingName (n : Name) (idx : Nat) : Name := mkNameStr n ("_elambda_" ++ toString idx) @[export lean_is_eager_lambda_lifting_name] def isEagerLambdaLiftingName : Name → Bool | Name.str p s _ => "_elambda".isPrefixOf s || isEagerLambdaLiftingName p | Name.num p _ _ => isEagerLambdaLiftingName p | _ => false /-- Return the name of new definitions in the a given declaration. Here we consider only declarations we generate code for. We use this definition to implement `add_and_compile`. -/ @[export lean_get_decl_names_for_code_gen] private def getDeclNamesForCodeGen : Declaration → List Name | Declaration.defnDecl { name := n, .. } => [n] | Declaration.mutualDefnDecl defs => defs.map $ fun d => d.name | Declaration.opaqueDecl { name := n, .. } => [n] | _ => [] def checkIsDefinition (env : Environment) (n : Name) : Except String Unit := match env.find? n with | (some (ConstantInfo.defnInfo _)) => Except.ok () | none => Except.error "unknow declaration" | _ => Except.error "declaration is not a definition" /-- We generate auxiliary unsafe definitions for regular recursive definitions. The auxiliary unsafe definition has a clear runtime cost execution model. This function returns the auxiliary unsafe definition name for the given name. -/ @[export lean_mk_unsafe_rec_name] def mkUnsafeRecName (declName : Name) : Name := mkNameStr declName "_unsafe_rec" /-- Return `some _` if the given name was created using `mkUnsafeRecName` -/ @[export lean_is_unsafe_rec_name] def isUnsafeRecName? : Name → Option Name | Name.str n "_unsafe_rec" _ => some n | _ => none end Compiler end Lean
d361ad3480c8efcb93005be50a33df9f955d0682
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/rb_map1.lean
c83063fdd88061d87562e93e62eb31f6e5eb117b
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
693
lean
import system.io section open nat_map vm_eval size (insert (insert (mk nat) 10 20) 10 21) meta definition m := (insert (insert (insert (mk nat) 10 20) 5 50) 10 21) vm_eval find m 10 vm_eval find m 5 vm_eval find m 8 vm_eval contains m 5 vm_eval contains m 8 open list meta definition m2 := of_list [((1:nat), "one"), (2, "two"), (3, "three")] vm_eval size m2 vm_eval find m2 1 vm_eval find m2 4 vm_eval find m2 3 vm_eval do pp m2, put_str "\n" vm_eval m2 end section open rb_map -- Mapping from (nat × nat) → nat meta definition m3 := insert (insert (mk (nat × nat) nat) (1, 2) 3) (2, 2) 4 vm_eval find m3 (1, 2) vm_eval find m3 (2, 1) vm_eval find m3 (2, 2) vm_eval pp m3 end
e403e7fe6de56d081178fc9836637836312a38b0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/products/associator.lean
c3d571ef59f3c3898b26c21aa96f54982241830c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,345
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.products.basic import Mathlib.PostPort universes u₁ u₂ u₃ v₁ v₂ v₃ namespace Mathlib /-# The associator functor `((C × D) × E) ⥤ (C × (D × E))` and its inverse form an equivalence. -/ namespace category_theory.prod /-- The associator functor `(C × D) × E ⥤ C × (D × E)`. -/ @[simp] theorem associator_map (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] (_x : (C × D) × E) : ∀ (_x_1 : (C × D) × E) (f : _x ⟶ _x_1), functor.map (associator C D E) f = (prod.fst (prod.fst f), prod.snd (prod.fst f), prod.snd f) := fun (_x_1 : (C × D) × E) (f : _x ⟶ _x_1) => Eq.refl (functor.map (associator C D E) f) /-- The inverse associator functor `C × (D × E) ⥤ (C × D) × E `. -/ @[simp] theorem inverse_associator_map (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] (_x : C × D × E) : ∀ (_x_1 : C × D × E) (f : _x ⟶ _x_1), functor.map (inverse_associator C D E) f = ((prod.fst f, prod.fst (prod.snd f)), prod.snd (prod.snd f)) := fun (_x_1 : C × D × E) (f : _x ⟶ _x_1) => Eq.refl (functor.map (inverse_associator C D E) f) /-- The equivalence of categories expressing associativity of products of categories. -/ def associativity (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : (C × D) × E ≌ C × D × E := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (fun (X : (C × D) × E) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : C × D × E) => eq_to_iso sorry) sorry) protected instance associator_is_equivalence (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : is_equivalence (associator C D E) := is_equivalence.of_equivalence (associativity C D E) protected instance inverse_associator_is_equivalence (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : is_equivalence (inverse_associator C D E) := is_equivalence.of_equivalence_inverse (associativity C D E)
5a42652a0f4244e91cdd27684a3eb702c0dc0558
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/undergraduate/MAS114/Semester 2/Q01.lean
e5ec5b785eaef0e17c641c7e04f2b502c7202c27
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,297
lean
import data.fintype group_theory.group_action algebra.group_power algebra.big_operators data.zmod.basic import tactic.ring import group_theory.pow_mod group_theory.self_map group_theory.burnside_count namespace MAS114 namespace exercises_2 namespace Q01 def s_W : (fin 4) → (fin 4) := λ ⟨i,i_is_lt⟩, ⟨3 - i,nat.lt_succ_of_le (nat.sub_le 3 i)⟩ lemma hs_W : ∀ i, s_W (s_W i) = i := λ ⟨i,i_is_lt⟩, begin have i_is_le : i ≤ 3 := nat.le_of_lt_succ i_is_lt, let h := nat.add_sub_of_le i_is_le, apply fin.eq_of_veq, change 3 - (3 - i) = i, exact calc 3 - (3 - i) = (i + (3 - i)) - (3 - i) : by rw[h] ... = i : nat.add_sub_cancel i (3 - i), end def X := (fin 4) × (fin 4) def s_X : X → X := λ ⟨i,j⟩, ⟨i,s_W j⟩ def r_X : X → X := λ ⟨i,j⟩, ⟨s_W j,i⟩ lemma hs_X : ∀ ij, s_X (s_X ij) = ij := λ ⟨i,j⟩, by { change prod.mk i (s_W (s_W j)) = prod.mk i j, rw[hs_W j], } lemma hr_X : ∀ ij, r_X (r_X (r_X (r_X ij))) = ij := λ ⟨i,j⟩, by { change prod.mk (s_W (s_W i)) (s_W (s_W j)) = prod.mk i j, rw[hs_W i,hs_W j], } lemma hrs_X : ∀ ij, r_X (s_X (r_X ij)) = s_X ij := λ ⟨i,j⟩, by { change prod.mk (s_W (s_W i)) (s_W j) = prod.mk i (s_W j), rw[hs_W i], } end Q01 end exercises_2 end MAS114
bc3274e0b23f821b09426b304ba481a4ba95f445
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/data/mv_polynomial/monad.lean
90f7c98eb675291d3e809d675c10586ffe4a18f1
[ "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
14,196
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.mv_polynomial.rename /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ open_locale big_operators noncomputable theory namespace mv_polynomial open finsupp variables {σ : Type*} {τ : Type*} variables {R S T : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring T] /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → mv_polynomial τ R) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : mv_polynomial (mv_polynomial σ R) R →ₐ[R] mv_polynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id _) X @[simp] lemma aeval_eq_bind₁ (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] lemma eval₂_hom_C_eq_bind₁ (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl @[simp] lemma eval₂_hom_eq_bind₂ (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl section variables (σ R) @[simp] lemma aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl lemma eval₂_hom_C_id_eq_join₁ (φ : mv_polynomial (mv_polynomial σ R) R) : eval₂_hom C id φ = join₁ φ := rfl @[simp] lemma eval₂_hom_id_X_eq_join₂ : eval₂_hom (ring_hom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards local attribute [-simp] aeval_eq_bind₁ eval₂_hom_C_eq_bind₁ eval₂_hom_eq_bind₂ aeval_id_eq_join₁ eval₂_hom_id_X_eq_join₂ @[simp] lemma bind₁_X_right (f : σ → mv_polynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] lemma bind₂_X_right (f : R →+* mv_polynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂_hom_X' f X i @[simp] lemma bind₁_X_left : bind₁ (X : σ → mv_polynomial σ R) = alg_hom.id R _ := begin ext1 φ, apply φ.induction_on, { intro, exact aeval_C _ _, }, { intros p q hp hq, simp only [hp, hq, alg_hom.map_add] }, { intros p n hp, simp only [hp, alg_hom.id_apply, bind₁_X_right, alg_hom.map_mul] } end lemma aeval_X_left : aeval (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by rw [aeval_eq_bind₁, bind₁_X_left] lemma aeval_X_left_apply (φ : mv_polynomial σ R) : aeval X φ = φ := by rw [aeval_eq_bind₁, bind₁_X_left, alg_hom.id_apply] variable (f : σ → mv_polynomial τ R) @[simp] lemma bind₁_C_right (f : σ → mv_polynomial τ R) (x) : bind₁ f (C x) = C x := by simp [bind₁, C, aeval_monomial, finsupp.prod_zero_index]; refl @[simp] lemma bind₂_C_left : bind₂ (C : R →+* mv_polynomial σ R) = ring_hom.id _ := by { ext1, simp [bind₂] } @[simp] lemma bind₂_C_right (f : R →+* mv_polynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂_hom_C f X r @[simp] lemma bind₂_comp_C (f : R →+* mv_polynomial σ S) : (bind₂ f).comp C = f := by { ext1, apply bind₂_C_right } @[simp] lemma join₂_map (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂_hom_map_hom, ring_hom.id_comp] @[simp] lemma join₂_comp_map (f : R →+* mv_polynomial σ S) : join₂.comp (map f) = bind₂ f := by { ext1, simp [join₂, bind₂] } lemma aeval_rename (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : aeval id (rename f p) = aeval f p := begin apply p.induction_on, { simp only [aeval_C, forall_const, eq_self_iff_true, rename_C] }, { intros p q hp hq, simp only [hp, hq, alg_hom.map_add, ring_hom.map_add] }, { intros p n hp, simp only [hp, rename_X, ring_hom.id_apply, aeval_X, ring_hom.map_mul, alg_hom.map_mul, id] } end @[simp] lemma join₁_rename (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_rename _ _ @[simp] lemma bind₁_id : bind₁ (@id (mv_polynomial σ R)) = join₁ := rfl @[simp] lemma bind₂_id : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl lemma bind₁_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (λ i, bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] lemma bind₁_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ (λ i, bind₁ g (f i)) := by { ext1, apply bind₁_bind₁ } lemma bind₂_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := begin dsimp [bind₂], apply φ.induction_on, { simp }, { intros p q hp hq, simp only [hp, hq, eval₂_add] }, { intros p n hp, simp only [hp, eval₂_mul, eval₂_X] } end lemma bind₂_comp_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by { ext1, simp only [function.comp_app, ring_hom.coe_comp, bind₂_bind₂], } lemma rename_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : rename g (bind₁ f φ) = bind₁ (λ i, rename g $ f i) φ := begin apply φ.induction_on, { intro a, simp }, { intros p q hp hq, simp [hp, hq] }, { intros p n hp, simp [hp] } end lemma map_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := begin simp only [bind₂, eval₂_comp_right, coe_eval₂_hom, eval₂_map], congr' 1 with : 1, simp only [function.comp_app, map_X] end lemma bind₁_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := begin dsimp [bind₁], apply φ.induction_on, { simp }, { intros p q hp hq, simp only [hp, hq, alg_hom.map_add, ring_hom.map_add] }, { intros p n hp, simp only [hp, rename_X, aeval_X, ring_hom.map_mul, alg_hom.map_mul] } end lemma bind₂_map (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] lemma map_comp_C (f : R →+* S) : (map f).comp (C : R →+* mv_polynomial σ R) = C.comp f := by { ext1, apply map_C } -- mixing the two monad structures lemma hom_bind₁ (f : mv_polynomial τ R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : f (bind₁ g φ) = eval₂_hom (f.comp C) (λ i, f (g i)) φ := by rw [bind₁, map_aeval, algebra_map_eq] lemma map_bind₁ (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : map f (bind₁ g φ) = bind₁ (λ (i : σ), (map f) (g i)) (map f φ) := by { rw [hom_bind₁, map_comp_C, ← eval₂_hom_map_hom], refl } @[simp] lemma eval₂_hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂_hom f g).comp C = f := by { ext1 r, exact eval₂_C f g r } lemma eval₂_hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₁ h φ) = eval₂_hom f (λ i, eval₂_hom f g (h i)) φ := by rw [hom_bind₁, eval₂_hom_comp_C] lemma aeval_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : aeval f (bind₁ g φ) = aeval (λ i, aeval f (g i)) φ := eval₂_hom_bind₁ _ _ _ _ lemma aeval_comp_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : (aeval f).comp (bind₁ g) = aeval (λ i, aeval f (g i)) := by { ext1, apply aeval_bind₁ } lemma eval₂_hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₂ h φ) = eval₂_hom ((eval₂_hom f g).comp h) g φ := begin apply induction_on φ, { intro r, simp only [bind₂_C_right, ring_hom.coe_comp, eval₂_hom_C] }, { intros, simp only [ring_hom.map_add, *] }, { intros, simp only [*, bind₂_X_right, eval₂_hom_X', ring_hom.map_mul] } end lemma eval₂_hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : (eval₂_hom f g).comp (bind₂ h) = eval₂_hom ((eval₂_hom f g).comp h) g := by { ext1, apply eval₂_hom_bind₂ } lemma aeval_bind₂ [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : aeval f (bind₂ g φ) = eval₂_hom ((@aeval σ S T f _ _ _ : mv_polynomial σ S →+* T).comp g) f φ := eval₂_hom_bind₂ _ _ _ _ lemma eval₂_hom_C_left (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl lemma bind₁_monomial (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i in d.support, f i ^ d i := by simp only [monomial_eq, alg_hom.map_mul, bind₁_C_right, finsupp.prod, alg_hom.map_prod, alg_hom.map_pow, bind₁_X_right] lemma bind₂_monomial (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, ring_hom.map_mul, bind₂_C_right, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, bind₂_X_right, C_1, one_mul] @[simp] lemma bind₂_monomial_one (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] instance : monad (λ σ, mv_polynomial σ R) := { map := λ α β f p, rename f p, pure := λ _, X, bind := λ _ _ p f, bind₁ f p } instance : is_lawful_functor (λ σ, mv_polynomial σ R) := { id_map := by intros; simp [(<$>)], comp_map := by intros; simp [(<$>)] } instance : is_lawful_monad (λ σ, mv_polynomial σ R) := { pure_bind := by intros; simp [pure, bind], bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] } /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end mv_polynomial
acd477bebcdc2e75c321bb5ddb46c209446c6e58
618003631150032a5676f229d13a079ac875ff77
/test/matrix.lean
554dc02d156c28b7e418b885e85e189ac65be6ab
[ "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
649
lean
import data.matrix.notation variables {α : Type} [semiring α] namespace matrix open_locale matrix example {a a' b b' c c' d d' : α} : ![![a, b], ![c, d]] + ![![a', b'], ![c', d']] = ![![a + a', b + b'], ![c + c', d + d']] := by simp example {a a' b b' c c' d d' : α} : ![![a, b], ![c, d]] ⬝ ![![a', b'], ![c', d']] = ![![a * a' + b * c', a * b' + b * d'], ![c * a' + d * c', c * b' + d * d']] := by simp example {a b c d x y : α} : mul_vec ![![a, b], ![c, d]] ![x, y] = ![a * x + b * y, c * x + d * y] := by simp example {a b c d : α} : minor ![![a, b], ![c, d]] ![1, 0] ![0] = ![![c], ![a]] := by { ext, simp } end matrix
bc2f85feb9a5085bd89db4f5b4b0f62918f9c02b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/model_theory/syntax.lean
471f52d01f344449e1b44947aebc54e264f11a43
[ "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
38,837
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import data.list.prod_sigma import data.set.prod import logic.equiv.fin import model_theory.language_map /-! # Basics on First-Order Syntax This file defines first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions * A `first_order.language.term` is defined so that `L.term α` is the type of `L`-terms with free variables indexed by `α`. * A `first_order.language.formula` is defined so that `L.formula α` is the type of `L`-formulas with free variables indexed by `α`. * A `first_order.language.sentence` is a formula with no free variables. * A `first_order.language.Theory` is a set of sentences. * The variables of terms and formulas can be relabelled with `first_order.language.term.relabel`, `first_order.language.bounded_formula.relabel`, and `first_order.language.formula.relabel`. * Given an operation on terms and an operation on relations, `first_order.language.bounded_formula.map_term_rel` gives an operation on formulas. * `first_order.language.bounded_formula.cast_le` adds more `fin`-indexed variables. * `first_order.language.bounded_formula.lift_at` raises the indexes of the `fin`-indexed variables above a particular index. * `first_order.language.term.subst` and `first_order.language.bounded_formula.subst` substitute variables with given terms. * Language maps can act on syntactic objects with functions such as `first_order.language.Lhom.on_formula`. * `first_order.language.term.constants_vars_equiv` and `first_order.language.bounded_formula.constants_vars_equiv` switch terms and formulas between having constants in the language and having extra variables indexed by the same type. ## Implementation Notes * Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n` is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula `∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by `n : fin (n + 1)`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v w u' v' namespace first_order namespace language variables (L : language.{u v}) {L' : language} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} {γ : Type*} open_locale first_order open Structure fin /-- A term on `α` is either a variable indexed by an element of `α` or a function symbol applied to simpler terms. -/ inductive term (α : Type u') : Type (max u u') | var {} : ∀ (a : α), term | func {} : ∀ {l : ℕ} (f : L.functions l) (ts : fin l → term), term export term variable {L} namespace term open finset /-- The `finset` of variables used in a given term. -/ @[simp] def var_finset [decidable_eq α] : L.term α → finset α | (var i) := {i} | (func f ts) := univ.bUnion (λ i, (ts i).var_finset) /-- The `finset` of variables from the left side of a sum used in a given term. -/ @[simp] def var_finset_left [decidable_eq α] : L.term (α ⊕ β) → finset α | (var (sum.inl i)) := {i} | (var (sum.inr i)) := ∅ | (func f ts) := univ.bUnion (λ i, (ts i).var_finset_left) /-- Relabels a term's variables along a particular function. -/ @[simp] def relabel (g : α → β) : L.term α → L.term β | (var i) := var (g i) | (func f ts) := func f (λ i, (ts i).relabel) lemma relabel_id (t : L.term α) : t.relabel id = t := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_id_eq_id : (term.relabel id : L.term α → L.term α) = id := funext relabel_id @[simp] lemma relabel_relabel (f : α → β) (g : β → γ) (t : L.term α) : (t.relabel f).relabel g = t.relabel (g ∘ f) := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_comp_relabel (f : α → β) (g : β → γ) : (term.relabel g ∘ term.relabel f : L.term α → L.term γ) = term.relabel (g ∘ f) := funext (relabel_relabel f g) /-- Relabels a term's variables along a bijection. -/ @[simps] def relabel_equiv (g : α ≃ β) : L.term α ≃ L.term β := ⟨relabel g, relabel g.symm, λ t, by simp, λ t, by simp⟩ /-- Restricts a term to use only a set of the given variables. -/ def restrict_var [decidable_eq α] : Π (t : L.term α) (f : t.var_finset → β), L.term β | (var a) f := var (f ⟨a, mem_singleton_self a⟩) | (func F ts) f := func F (λ i, (ts i).restrict_var (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) /-- Restricts a term to use only a set of the given variables on the left side of a sum. -/ def restrict_var_left [decidable_eq α] {γ : Type*} : Π (t : L.term (α ⊕ γ)) (f : t.var_finset_left → β), L.term (β ⊕ γ) | (var (sum.inl a)) f := var (sum.inl (f ⟨a, mem_singleton_self a⟩)) | (var (sum.inr a)) f := var (sum.inr a) | (func F ts) f := func F (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) end term /-- The representation of a constant symbol as a term. -/ def constants.term (c : L.constants) : (L.term α) := func c default /-- Applies a unary function to a term. -/ def functions.apply₁ (f : L.functions 1) (t : L.term α) : L.term α := func f ![t] /-- Applies a binary function to two terms. -/ def functions.apply₂ (f : L.functions 2) (t₁ t₂ : L.term α) : L.term α := func f ![t₁, t₂] namespace term /-- Sends a term with constants to a term with extra variables. -/ @[simp] def constants_to_vars : L[[γ]].term α → L.term (γ ⊕ α) | (var a) := var (sum.inr a) | (@func _ _ 0 f ts) := sum.cases_on f (λ f, func f (λ i, (ts i).constants_to_vars)) (λ c, var (sum.inl c)) | (@func _ _ (n + 1) f ts) := sum.cases_on f (λ f, func f (λ i, (ts i).constants_to_vars)) (λ c, is_empty_elim c) /-- Sends a term with extra variables to a term with constants. -/ @[simp] def vars_to_constants : L.term (γ ⊕ α) → L[[γ]].term α | (var (sum.inr a)) := var a | (var (sum.inl c)) := constants.term (sum.inr c) | (func f ts) := func (sum.inl f) (λ i, (ts i).vars_to_constants) /-- A bijection between terms with constants and terms with extra variables. -/ @[simps] def constants_vars_equiv : L[[γ]].term α ≃ L.term (γ ⊕ α) := ⟨constants_to_vars, vars_to_constants, begin intro t, induction t with _ n f _ ih, { refl }, { cases n, { cases f, { simp [constants_to_vars, vars_to_constants, ih] }, { simp [constants_to_vars, vars_to_constants, constants.term] } }, { cases f, { simp [constants_to_vars, vars_to_constants, ih] }, { exact is_empty_elim f } } } end, begin intro t, induction t with x n f _ ih, { cases x; refl }, { cases n; { simp [vars_to_constants, constants_to_vars, ih] } } end⟩ /-- A bijection between terms with constants and terms with extra variables. -/ def constants_vars_equiv_left : L[[γ]].term (α ⊕ β) ≃ L.term ((γ ⊕ α) ⊕ β) := constants_vars_equiv.trans (relabel_equiv (equiv.sum_assoc _ _ _)).symm @[simp] lemma constants_vars_equiv_left_apply (t : L[[γ]].term (α ⊕ β)) : constants_vars_equiv_left t = (constants_to_vars t).relabel (equiv.sum_assoc _ _ _).symm := rfl @[simp] lemma constants_vars_equiv_left_symm_apply (t : L.term ((γ ⊕ α) ⊕ β)) : constants_vars_equiv_left.symm t = vars_to_constants (t.relabel (equiv.sum_assoc _ _ _)) := rfl instance inhabited_of_var [inhabited α] : inhabited (L.term α) := ⟨var default⟩ instance inhabited_of_constant [inhabited L.constants] : inhabited (L.term α) := ⟨(default : L.constants).term⟩ /-- Raises all of the `fin`-indexed variables of a term greater than or equal to `m` by `n'`. -/ def lift_at {n : ℕ} (n' m : ℕ) : L.term (α ⊕ fin n) → L.term (α ⊕ fin (n + n')) := relabel (sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) /-- Substitutes the variables in a given term with terms. -/ @[simp] def subst : L.term α → (α → L.term β) → L.term β | (var a) tf := tf a | (func f ts) tf := (func f (λ i, (ts i).subst tf)) end term localized "prefix (name := language.term.var) `&`:max := first_order.language.term.var ∘ sum.inr" in first_order namespace Lhom /-- Maps a term's symbols along a language map. -/ @[simp] def on_term (φ : L →ᴸ L') : L.term α → L'.term α | (var i) := var i | (func f ts) := func (φ.on_function f) (λ i, on_term (ts i)) @[simp] lemma id_on_term : ((Lhom.id L).on_term : L.term α → L.term α) = id := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end @[simp] lemma comp_on_term {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_term : L.term α → L''.term α) = φ.on_term ∘ ψ.on_term := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end end Lhom /-- Maps a term's symbols along a language equivalence. -/ @[simps] def Lequiv.on_term (φ : L ≃ᴸ L') : L.term α ≃ L'.term α := { to_fun := φ.to_Lhom.on_term, inv_fun := φ.inv_Lhom.on_term, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_term, φ.left_inv, Lhom.id_on_term], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_term, φ.right_inv, Lhom.id_on_term] } variables (L) (α) /-- `bounded_formula α n` is the type of formulas with free variables indexed by `α` and up to `n` additional free variables. -/ inductive bounded_formula : ℕ → Type (max u v u') | falsum {} {n} : bounded_formula n | equal {n} (t₁ t₂ : L.term (α ⊕ fin n)) : bounded_formula n | rel {n l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : bounded_formula n | imp {n} (f₁ f₂ : bounded_formula n) : bounded_formula n | all {n} (f : bounded_formula (n+1)) : bounded_formula n /-- `formula α` is the type of formulas with all free variables indexed by `α`. -/ @[reducible] def formula := L.bounded_formula α 0 /-- A sentence is a formula with no free variables. -/ @[reducible] def sentence := L.formula empty /-- A theory is a set of sentences. -/ @[reducible] def Theory := set L.sentence variables {L} {α} {n : ℕ} /-- Applies a relation to terms as a bounded formula. -/ def relations.bounded_formula {l : ℕ} (R : L.relations n) (ts : fin n → L.term (α ⊕ fin l)) : L.bounded_formula α l := bounded_formula.rel R ts /-- Applies a unary relation to a term as a bounded formula. -/ def relations.bounded_formula₁ (r : L.relations 1) (t : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t] /-- Applies a binary relation to two terms as a bounded formula. -/ def relations.bounded_formula₂ (r : L.relations 2) (t₁ t₂ : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t₁, t₂] /-- The equality of two terms as a bounded formula. -/ def term.bd_equal (t₁ t₂ : L.term (α ⊕ fin n)) : (L.bounded_formula α n) := bounded_formula.equal t₁ t₂ /-- Applies a relation to terms as a bounded formula. -/ def relations.formula (R : L.relations n) (ts : fin n → L.term α) : L.formula α := R.bounded_formula (λ i, (ts i).relabel sum.inl) /-- Applies a unary relation to a term as a formula. -/ def relations.formula₁ (r : L.relations 1) (t : L.term α) : L.formula α := r.formula ![t] /-- Applies a binary relation to two terms as a formula. -/ def relations.formula₂ (r : L.relations 2) (t₁ t₂ : L.term α) : L.formula α := r.formula ![t₁, t₂] /-- The equality of two terms as a first-order formula. -/ def term.equal (t₁ t₂ : L.term α) : (L.formula α) := (t₁.relabel sum.inl).bd_equal (t₂.relabel sum.inl) namespace bounded_formula instance : inhabited (L.bounded_formula α n) := ⟨falsum⟩ instance : has_bot (L.bounded_formula α n) := ⟨falsum⟩ /-- The negation of a bounded formula is also a bounded formula. -/ @[pattern] protected def not (φ : L.bounded_formula α n) : L.bounded_formula α n := φ.imp ⊥ /-- Puts an `∃` quantifier on a bounded formula. -/ @[pattern] protected def ex (φ : L.bounded_formula α (n + 1)) : L.bounded_formula α n := φ.not.all.not instance : has_top (L.bounded_formula α n) := ⟨bounded_formula.not ⊥⟩ instance : has_inf (L.bounded_formula α n) := ⟨λ f g, (f.imp g.not).not⟩ instance : has_sup (L.bounded_formula α n) := ⟨λ f g, f.not.imp g⟩ /-- The biimplication between two bounded formulas. -/ protected def iff (φ ψ : L.bounded_formula α n) := φ.imp ψ ⊓ ψ.imp φ open finset /-- The `finset` of variables used in a given formula. -/ @[simp] def free_var_finset [decidable_eq α] : ∀ {n}, L.bounded_formula α n → finset α | n falsum := ∅ | n (equal t₁ t₂) := t₁.var_finset_left ∪ t₂.var_finset_left | n (rel R ts) := univ.bUnion (λ i, (ts i).var_finset_left) | n (imp f₁ f₂) := f₁.free_var_finset ∪ f₂.free_var_finset | n (all f) := f.free_var_finset /-- Casts `L.bounded_formula α m` as `L.bounded_formula α n`, where `m ≤ n`. -/ @[simp] def cast_le : ∀ {m n : ℕ} (h : m ≤ n), L.bounded_formula α m → L.bounded_formula α n | m n h falsum := falsum | m n h (equal t₁ t₂) := equal (t₁.relabel (sum.map id (fin.cast_le h))) (t₂.relabel (sum.map id (fin.cast_le h))) | m n h (rel R ts) := rel R (term.relabel (sum.map id (fin.cast_le h)) ∘ ts) | m n h (imp f₁ f₂) := (f₁.cast_le h).imp (f₂.cast_le h) | m n h (all f) := (f.cast_le (add_le_add_right h 1)).all @[simp] lemma cast_le_rfl {n} (h : n ≤ n) (φ : L.bounded_formula α n) : φ.cast_le h = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq, ih1, ih2], }, { simp [fin.cast_le_of_eq, ih3], }, end @[simp] lemma cast_le_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) (φ : L.bounded_formula α k) : (φ.cast_le km).cast_le mn = φ.cast_le (km.trans mn) := begin revert m n, induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3; intros m n km mn, { refl }, { simp }, { simp only [cast_le, eq_self_iff_true, heq_iff_eq, true_and], rw [← function.comp.assoc, relabel_comp_relabel], simp }, { simp [ih1, ih2] }, { simp only [cast_le, ih3] } end @[simp] lemma cast_le_comp_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) : (bounded_formula.cast_le mn ∘ bounded_formula.cast_le km : L.bounded_formula α k → L.bounded_formula α n) = bounded_formula.cast_le (km.trans mn) := funext (cast_le_cast_le km mn) /-- Restricts a bounded formula to only use a particular set of free variables. -/ def restrict_free_var [decidable_eq α] : Π {n : ℕ} (φ : L.bounded_formula α n) (f : φ.free_var_finset → β), L.bounded_formula β n | n falsum f := falsum | n (equal t₁ t₂) f := equal (t₁.restrict_var_left (f ∘ set.inclusion (subset_union_left _ _))) (t₂.restrict_var_left (f ∘ set.inclusion (subset_union_right _ _))) | n (rel R ts) f := rel R (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) | n (imp φ₁ φ₂) f := (φ₁.restrict_free_var (f ∘ set.inclusion (subset_union_left _ _))).imp (φ₂.restrict_free_var (f ∘ set.inclusion (subset_union_right _ _))) | n (all φ) f := (φ.restrict_free_var f).all /-- Places universal quantifiers on all extra variables of a bounded formula. -/ def alls : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.all.alls /-- Places existential quantifiers on all extra variables of a bounded formula. -/ def exs : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.ex.exs /-- Maps bounded formulas along a map of terms and a map of relations. -/ def map_term_rel {g : ℕ → ℕ} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin (g n))) (fr : ∀ n, L.relations n → L'.relations n) (h : ∀ n, L'.bounded_formula β (g (n + 1)) → L'.bounded_formula β (g n + 1)) : ∀ {n}, L.bounded_formula α n → L'.bounded_formula β (g n) | n falsum := falsum | n (equal t₁ t₂) := equal (ft _ t₁) (ft _ t₂) | n (rel R ts) := rel (fr _ R) (λ i, ft _ (ts i)) | n (imp φ₁ φ₂) := φ₁.map_term_rel.imp φ₂.map_term_rel | n (all φ) := (h n φ.map_term_rel).all /-- Raises all of the `fin`-indexed variables of a formula greater than or equal to `m` by `n'`. -/ def lift_at : ∀ {n : ℕ} (n' m : ℕ), L.bounded_formula α n → L.bounded_formula α (n + n') := λ n n' m φ, φ.map_term_rel (λ k t, t.lift_at n' m) (λ _, id) (λ _, cast_le (by rw [add_assoc, add_comm 1, add_assoc])) @[simp] lemma map_term_rel_map_term_rel {L'' : language} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n → L'.relations n) (ft' : ∀ n, L'.term (β ⊕ fin n) → L''.term (γ ⊕ fin n)) (fr' : ∀ n, L'.relations n → L''.relations n) {n} (φ : L.bounded_formula α n) : (φ.map_term_rel ft fr (λ _, id)).map_term_rel ft' fr' (λ _, id) = φ.map_term_rel (λ _, (ft' _) ∘ (ft _)) (λ _, (fr' _) ∘ (fr _)) (λ _, id) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end @[simp] lemma map_term_rel_id_id_id {n} (φ : L.bounded_formula α n) : φ.map_term_rel (λ _, id) (λ _, id) (λ _, id) = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end /-- An equivalence of bounded formulas given by an equivalence of terms and an equivalence of relations. -/ @[simps] def map_term_rel_equiv (ft : ∀ n, L.term (α ⊕ fin n) ≃ L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n ≃ L'.relations n) {n} : L.bounded_formula α n ≃ L'.bounded_formula β n := ⟨map_term_rel (λ n, ft n) (λ n, fr n) (λ _, id), map_term_rel (λ n, (ft n).symm) (λ n, (fr n).symm) (λ _, id), λ φ, by simp, λ φ, by simp⟩ /-- A function to help relabel the variables in bounded formulas. -/ def relabel_aux (g : α → β ⊕ fin n) (k : ℕ) : α ⊕ fin k → β ⊕ fin (n + k) := sum.map id fin_sum_fin_equiv ∘ equiv.sum_assoc _ _ _ ∘ sum.map g id @[simp] lemma sum_elim_comp_relabel_aux {m : ℕ} {g : α → (β ⊕ fin n)} {v : β → M} {xs : fin (n + m) → M} : sum.elim v xs ∘ relabel_aux g m = sum.elim (sum.elim v (xs ∘ cast_add m) ∘ g) (xs ∘ nat_add n) := begin ext x, cases x, { simp only [bounded_formula.relabel_aux, function.comp_app, sum.map_inl, sum.elim_inl], cases g x with l r; simp }, { simp [bounded_formula.relabel_aux] } end @[simp] lemma relabel_aux_sum_inl (k : ℕ) : relabel_aux (sum.inl : α → α ⊕ fin n) k = sum.map id (nat_add n) := begin ext x, cases x; { simp [relabel_aux] }, end /-- Relabels a bounded formula's variables along a particular function. -/ def relabel (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : L.bounded_formula β (n + k) := φ.map_term_rel (λ _ t, t.relabel (relabel_aux g _)) (λ _, id) (λ _, cast_le (ge_of_eq (add_assoc _ _ _))) @[simp] lemma relabel_falsum (g : α → (β ⊕ fin n)) {k} : (falsum : L.bounded_formula α k).relabel g = falsum := rfl @[simp] lemma relabel_bot (g : α → (β ⊕ fin n)) {k} : (⊥ : L.bounded_formula α k).relabel g = ⊥ := rfl @[simp] lemma relabel_imp (g : α → (β ⊕ fin n)) {k} (φ ψ : L.bounded_formula α k) : (φ.imp ψ).relabel g = (φ.relabel g).imp (ψ.relabel g) := rfl @[simp] lemma relabel_not (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : φ.not.relabel g = (φ.relabel g).not := by simp [bounded_formula.not] @[simp] lemma relabel_all (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.all.relabel g = (φ.relabel g).all := begin rw [relabel, map_term_rel, relabel], simp, end @[simp] lemma relabel_ex (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.ex.relabel g = (φ.relabel g).ex := by simp [bounded_formula.ex] @[simp] lemma relabel_sum_inl (φ : L.bounded_formula α n) : (φ.relabel sum.inl : L.bounded_formula α (0 + n)) = φ.cast_le (ge_of_eq (zero_add n)) := begin simp only [relabel, relabel_aux_sum_inl], induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [map_term_rel, ih1, ih2], }, { simp [map_term_rel, ih3, cast_le], }, end /-- Substitutes the variables in a given formula with terms. -/ @[simp] def subst {n : ℕ} (φ : L.bounded_formula α n) (f : α → L.term β) : L.bounded_formula β n := φ.map_term_rel (λ _ t, t.subst (sum.elim (term.relabel sum.inl ∘ f) (var ∘ sum.inr))) (λ _, id) (λ _, id) /-- A bijection sending formulas with constants to formulas with extra variables. -/ def constants_vars_equiv : L[[γ]].bounded_formula α n ≃ L.bounded_formula (γ ⊕ α) n := map_term_rel_equiv (λ _, term.constants_vars_equiv_left) (λ _, equiv.sum_empty _ _) /-- Turns the extra variables of a bounded formula into free variables. -/ @[simp] def to_formula : ∀ {n : ℕ}, L.bounded_formula α n → L.formula (α ⊕ fin n) | n falsum := falsum | n (equal t₁ t₂) := t₁.equal t₂ | n (rel R ts) := R.formula ts | n (imp φ₁ φ₂) := φ₁.to_formula.imp φ₂.to_formula | n (all φ) := (φ.to_formula.relabel (sum.elim (sum.inl ∘ sum.inl) (sum.map sum.inr id ∘ fin_sum_fin_equiv.symm))).all variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ} variables {v : α → M} {xs : fin l → M} /-- An atomic formula is either equality or a relation symbol applied to terms. Note that `⊥` and `⊤` are not considered atomic in this convention. -/ inductive is_atomic : L.bounded_formula α n → Prop | equal (t₁ t₂ : L.term (α ⊕ fin n)) : is_atomic (bd_equal t₁ t₂) | rel {l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : is_atomic (R.bounded_formula ts) lemma not_all_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_atomic := λ con, by cases con lemma not_ex_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_atomic := λ con, by cases con lemma is_atomic.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_atomic) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.lift_at {k m : ℕ} (h : is_atomic φ) : (φ.lift_at k m).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.cast_le {h : l ≤ n} (hφ : is_atomic φ) : (φ.cast_le h).is_atomic := is_atomic.rec_on hφ (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) /-- A quantifier-free formula is a formula defined without quantifiers. These are all equivalent to boolean combinations of atomic formulas. -/ inductive is_qf : L.bounded_formula α n → Prop | falsum : is_qf falsum | of_is_atomic {φ} (h : is_atomic φ) : is_qf φ | imp {φ₁ φ₂} (h₁ : is_qf φ₁) (h₂ : is_qf φ₂) : is_qf (φ₁.imp φ₂) lemma is_atomic.is_qf {φ : L.bounded_formula α n} : is_atomic φ → is_qf φ := is_qf.of_is_atomic lemma is_qf_bot : is_qf (⊥ : L.bounded_formula α n) := is_qf.falsum lemma is_qf.not {φ : L.bounded_formula α n} (h : is_qf φ) : is_qf φ.not := h.imp is_qf_bot lemma is_qf.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_qf) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_qf := is_qf.rec_on h is_qf_bot (λ _ h, (h.relabel f).is_qf) (λ _ _ _ _ h1 h2, h1.imp h2) lemma is_qf.lift_at {k m : ℕ} (h : is_qf φ) : (φ.lift_at k m).is_qf := is_qf.rec_on h is_qf_bot (λ _ ih, ih.lift_at.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma is_qf.cast_le {h : l ≤ n} (hφ : is_qf φ) : (φ.cast_le h).is_qf := is_qf.rec_on hφ is_qf_bot (λ _ ih, ih.cast_le.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma not_all_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_qf := λ con, begin cases con with _ con, exact (φ.not_all_is_atomic con), end lemma not_ex_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_qf := λ con, begin cases con with _ con _ _ con, { exact (φ.not_ex_is_atomic con) }, { exact not_all_is_qf _ con } end /-- Indicates that a bounded formula is in prenex normal form - that is, it consists of quantifiers applied to a quantifier-free formula. -/ inductive is_prenex : ∀ {n}, L.bounded_formula α n → Prop | of_is_qf {n} {φ : L.bounded_formula α n} (h : is_qf φ) : is_prenex φ | all {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.all | ex {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.ex lemma is_qf.is_prenex {φ : L.bounded_formula α n} : is_qf φ → is_prenex φ := is_prenex.of_is_qf lemma is_atomic.is_prenex {φ : L.bounded_formula α n} (h : is_atomic φ) : is_prenex φ := h.is_qf.is_prenex lemma is_prenex.induction_on_all_not {P : ∀ {n}, L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_prenex φ) (hq : ∀ {m} {ψ : L.bounded_formula α m}, ψ.is_qf → P ψ) (ha : ∀ {m} {ψ : L.bounded_formula α (m + 1)}, P ψ → P ψ.all) (hn : ∀ {m} {ψ : L.bounded_formula α m}, P ψ → P ψ.not) : P φ := is_prenex.rec_on h (λ _ _, hq) (λ _ _ _, ha) (λ _ _ _ ih, hn (ha (hn ih))) lemma is_prenex.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_prenex) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_prenex := is_prenex.rec_on h (λ _ _ h, (h.relabel f).is_prenex) (λ _ _ _ h, by simp [h.all]) (λ _ _ _ h, by simp [h.ex]) lemma is_prenex.cast_le (hφ : is_prenex φ) : ∀ {n} {h : l ≤ n}, (φ.cast_le h).is_prenex := is_prenex.rec_on hφ (λ _ _ ih _ _, ih.cast_le.is_prenex) (λ _ _ _ ih _ _, ih.all) (λ _ _ _ ih _ _, ih.ex) lemma is_prenex.lift_at {k m : ℕ} (h : is_prenex φ) : (φ.lift_at k m).is_prenex := is_prenex.rec_on h (λ _ _ ih, ih.lift_at.is_prenex) (λ _ _ _ ih, ih.cast_le.all) (λ _ _ _ ih, ih.cast_le.ex) /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` is quantifier-free and `ψ` is in prenex normal form, then `φ.to_prenex_imp_right ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp_right : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n φ (bounded_formula.ex ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).ex | n φ (all ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).all | n φ ψ := φ.imp ψ lemma is_qf.to_prenex_imp_right {φ : L.bounded_formula α n} : Π {ψ : L.bounded_formula α n}, is_qf ψ → (φ.to_prenex_imp_right ψ = φ.imp ψ) | _ is_qf.falsum := rfl | _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ (is_qf.imp is_qf.falsum _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp_right {φ ψ : L.bounded_formula α n} (hφ : is_qf φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp_right ψ) := begin induction hψ with _ _ hψ _ _ _ ih1 _ _ _ ih2, { rw hψ.to_prenex_imp_right, exact (hφ.imp hψ).is_prenex }, { exact (ih1 hφ.lift_at).all }, { exact (ih2 hφ.lift_at).ex } end /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` and `ψ` are in prenex normal form, then `φ.to_prenex_imp ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n (bounded_formula.ex φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).all | n (all φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).ex | _ φ ψ := φ.to_prenex_imp_right ψ lemma is_qf.to_prenex_imp : Π {φ ψ : L.bounded_formula α n}, φ.is_qf → φ.to_prenex_imp ψ = φ.to_prenex_imp_right ψ | _ _ is_qf.falsum := rfl | _ _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ _ (is_qf.imp is_qf.falsum _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp {φ ψ : L.bounded_formula α n} (hφ : is_prenex φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp ψ) := begin induction hφ with _ _ hφ _ _ _ ih1 _ _ _ ih2, { rw hφ.to_prenex_imp, exact is_prenex_to_prenex_imp_right hφ hψ }, { exact (ih1 hψ.lift_at).ex }, { exact (ih2 hψ.lift_at).all } end /-- For any bounded formula `φ`, `φ.to_prenex` is a semantically-equivalent formula in prenex normal form. -/ def to_prenex : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n | _ falsum := ⊥ | _ (equal t₁ t₂) := t₁.bd_equal t₂ | _ (rel R ts) := rel R ts | _ (imp f₁ f₂) := f₁.to_prenex.to_prenex_imp f₂.to_prenex | _ (all f) := f.to_prenex.all lemma to_prenex_is_prenex (φ : L.bounded_formula α n) : φ.to_prenex.is_prenex := bounded_formula.rec_on φ (λ _, is_qf_bot.is_prenex) (λ _ _ _, (is_atomic.equal _ _).is_prenex) (λ _ _ _ _, (is_atomic.rel _ _).is_prenex) (λ _ _ _ h1 h2, is_prenex_to_prenex_imp h1 h2) (λ _ _, is_prenex.all) end bounded_formula namespace Lhom open bounded_formula /-- Maps a bounded formula's symbols along a language map. -/ @[simp] def on_bounded_formula (g : L →ᴸ L') : ∀ {k : ℕ}, L.bounded_formula α k → L'.bounded_formula α k | k falsum := falsum | k (equal t₁ t₂) := (g.on_term t₁).bd_equal (g.on_term t₂) | k (rel R ts) := (g.on_relation R).bounded_formula (g.on_term ∘ ts) | k (imp f₁ f₂) := (on_bounded_formula f₁).imp (on_bounded_formula f₂) | k (all f) := (on_bounded_formula f).all @[simp] lemma id_on_bounded_formula : ((Lhom.id L).on_bounded_formula : L.bounded_formula α n → L.bounded_formula α n) = id := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { rw [on_bounded_formula, Lhom.id_on_term, id.def, id.def, id.def, bd_equal] }, { rw [on_bounded_formula, Lhom.id_on_term], refl, }, { rw [on_bounded_formula, ih1, ih2, id.def, id.def, id.def] }, { rw [on_bounded_formula, ih3, id.def, id.def] } end @[simp] lemma comp_on_bounded_formula {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_bounded_formula : L.bounded_formula α n → L''.bounded_formula α n) = φ.on_bounded_formula ∘ ψ.on_bounded_formula := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [on_bounded_formula, comp_on_term, function.comp_app], refl, }, { simp only [on_bounded_formula, comp_on_relation, comp_on_term, function.comp_app], refl }, { simp only [on_bounded_formula, function.comp_app, ih1, ih2, eq_self_iff_true, and_self], }, { simp only [ih3, on_bounded_formula, function.comp_app] } end /-- Maps a formula's symbols along a language map. -/ def on_formula (g : L →ᴸ L') : L.formula α → L'.formula α := g.on_bounded_formula /-- Maps a sentence's symbols along a language map. -/ def on_sentence (g : L →ᴸ L') : L.sentence → L'.sentence := g.on_formula /-- Maps a theory's symbols along a language map. -/ def on_Theory (g : L →ᴸ L') (T : L.Theory) : L'.Theory := g.on_sentence '' T @[simp] lemma mem_on_Theory {g : L →ᴸ L'} {T : L.Theory} {φ : L'.sentence} : φ ∈ g.on_Theory T ↔ ∃ φ₀, φ₀ ∈ T ∧ g.on_sentence φ₀ = φ := set.mem_image _ _ _ end Lhom namespace Lequiv /-- Maps a bounded formula's symbols along a language equivalence. -/ @[simps] def on_bounded_formula (φ : L ≃ᴸ L') : L.bounded_formula α n ≃ L'.bounded_formula α n := { to_fun := φ.to_Lhom.on_bounded_formula, inv_fun := φ.inv_Lhom.on_bounded_formula, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.left_inv, Lhom.id_on_bounded_formula], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.right_inv, Lhom.id_on_bounded_formula] } lemma on_bounded_formula_symm (φ : L ≃ᴸ L') : (φ.on_bounded_formula.symm : L'.bounded_formula α n ≃ L.bounded_formula α n) = φ.symm.on_bounded_formula := rfl /-- Maps a formula's symbols along a language equivalence. -/ def on_formula (φ : L ≃ᴸ L') : L.formula α ≃ L'.formula α := φ.on_bounded_formula @[simp] lemma on_formula_apply (φ : L ≃ᴸ L') : (φ.on_formula : L.formula α → L'.formula α) = φ.to_Lhom.on_formula := rfl @[simp] lemma on_formula_symm (φ : L ≃ᴸ L') : (φ.on_formula.symm : L'.formula α ≃ L.formula α) = φ.symm.on_formula := rfl /-- Maps a sentence's symbols along a language equivalence. -/ @[simps] def on_sentence (φ : L ≃ᴸ L') : L.sentence ≃ L'.sentence := φ.on_formula end Lequiv localized "infix (name := term.bd_equal) ` =' `:88 := first_order.language.term.bd_equal" in first_order -- input \~- or \simeq localized "infixr (name := bounded_formula.imp) ` ⟹ `:62 := first_order.language.bounded_formula.imp" in first_order -- input \==> localized "prefix (name := bounded_formula.all) `∀'`:110 := first_order.language.bounded_formula.all" in first_order localized "prefix (name := bounded_formula.not) `∼`:max := first_order.language.bounded_formula.not" in first_order -- input \~, the ASCII character ~ has too low precedence localized "infix (name := bounded_formula.iff) ` ⇔ `:61 := first_order.language.bounded_formula.iff" in first_order -- input \<=> localized "prefix (name := bounded_formula.ex) `∃'`:110 := first_order.language.bounded_formula.ex" in first_order -- input \ex namespace formula /-- Relabels a formula's variables along a particular function. -/ def relabel (g : α → β) : L.formula α → L.formula β := @bounded_formula.relabel _ _ _ 0 (sum.inl ∘ g) 0 /-- The graph of a function as a first-order formula. -/ def graph (f : L.functions n) : L.formula (fin (n + 1)) := equal (var 0) (func f (λ i, var i.succ)) /-- The negation of a formula. -/ protected def not (φ : L.formula α) : L.formula α := φ.not /-- The implication between formulas, as a formula. -/ protected def imp : L.formula α → L.formula α → L.formula α := bounded_formula.imp /-- The biimplication between formulas, as a formula. -/ protected def iff (φ ψ : L.formula α) : L.formula α := φ.iff ψ lemma is_atomic_graph (f : L.functions n) : (graph f).is_atomic := bounded_formula.is_atomic.equal _ _ end formula namespace relations variable (r : L.relations 2) /-- The sentence indicating that a basic relation symbol is reflexive. -/ protected def reflexive : L.sentence := ∀' r.bounded_formula₂ &0 &0 /-- The sentence indicating that a basic relation symbol is irreflexive. -/ protected def irreflexive : L.sentence := ∀' ∼ (r.bounded_formula₂ &0 &0) /-- The sentence indicating that a basic relation symbol is symmetric. -/ protected def symmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &0) /-- The sentence indicating that a basic relation symbol is antisymmetric. -/ protected def antisymmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ (r.bounded_formula₂ &1 &0 ⟹ term.bd_equal &0 &1)) /-- The sentence indicating that a basic relation symbol is transitive. -/ protected def transitive : L.sentence := ∀' ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &2 ⟹ r.bounded_formula₂ &0 &2) /-- The sentence indicating that a basic relation symbol is total. -/ protected def total : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⊔ r.bounded_formula₂ &1 &0) end relations section cardinality variable (L) /-- A sentence indicating that a structure has `n` distinct elements. -/ protected def sentence.card_ge (n) : L.sentence := (((((list.fin_range n).product (list.fin_range n)).filter (λ ij : _ × _, ij.1 ≠ ij.2)).map (λ (ij : _ × _), ∼ ((& ij.1).bd_equal (& ij.2)))).foldr (⊓) ⊤).exs /-- A theory indicating that a structure is infinite. -/ def infinite_theory : L.Theory := set.range (sentence.card_ge L) /-- A theory that indicates a structure is nonempty. -/ def nonempty_theory : L.Theory := {sentence.card_ge L 1} /-- A theory indicating that each of a set of constants is distinct. -/ def distinct_constants_theory (s : set α) : L[[α]].Theory := (λ ab : α × α, (((L.con ab.1).term.equal (L.con ab.2).term).not)) '' (s ×ˢ s ∩ (set.diagonal α)ᶜ) variables {L} {α} open set lemma monotone_distinct_constants_theory : monotone (L.distinct_constants_theory : set α → L[[α]].Theory) := λ s t st, (image_subset _ (inter_subset_inter_left _ (prod_mono st st))) lemma directed_distinct_constants_theory : directed (⊆) (L.distinct_constants_theory : set α → L[[α]].Theory) := monotone.directed_le monotone_distinct_constants_theory lemma distinct_constants_theory_eq_Union (s : set α) : L.distinct_constants_theory s = ⋃ (t : finset s), L.distinct_constants_theory (t.map (function.embedding.subtype (λ x, x ∈ s))) := begin classical, simp only [distinct_constants_theory], rw [← image_Union, ← Union_inter], refine congr rfl (congr (congr rfl _) rfl), ext ⟨i, j⟩, simp only [prod_mk_mem_set_prod_eq, finset.coe_map, function.embedding.coe_subtype, mem_Union, mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], refine ⟨λ h, ⟨{⟨i, h.1⟩, ⟨j, h.2⟩}, ⟨h.1, _⟩, ⟨h.2, _⟩⟩, _⟩, { simp }, { simp }, { rintros ⟨t, ⟨is, _⟩, ⟨js, _⟩⟩, exact ⟨is, js⟩ } end end cardinality end language end first_order
fa35fb42b5457b3640a4640c0ad1e54a5ac18def
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level16.lean
daa22b4d3e6d913e9781b7fea5bd5f76db2278cc
[ "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
678
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- #Calculating ## Level 15: `calc` keyword The following exercise is a little more challenging. You can use the theorems listed underneath. -/ variables a b c d : ℝ /- Lemma : no-side-bar For all natural numbers $a$, we have $$a + \operatorname{succ}(0) = \operatorname{succ}(a).$$ -/ lemma example16 (a b : ℝ) : (a + b) * (a - b) = a^2 - b^2 := begin [maths_in_lean_game] sorry end /- ```#check pow_two a #check mul_sub a b c #check add_mul a b c #check add_sub a b c #check sub_sub a b c #check add_zero a``` -/ end calculating -- hide
7f5527865dcb0530e4b0654007a1d8b6445755cd
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/spectrum_of_a_ring/structure_presheaf.lean
ab7ba8537dbcd9803598e110df8ca05551e8647d
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
2,479
lean
import ring_theory.localization import to_mathlib.localization.localization_alt import to_mathlib.localization.localization_of import spectrum_of_a_ring.properties import sheaves.presheaf_of_rings_on_basis import sheaves.sheaf_of_rings_on_standard_basis import sheaves.locally_ringed_space import spectrum_of_a_ring.spec import spectrum_of_a_ring.zariski_topology import spectrum_of_a_ring.standard_basis universe u local attribute [instance] classical.prop_decidable variables {R : Type u} [comm_ring R] open topological_space open classical open localization open localization_alt -- Define S(U) so that R[1/f] ≃ R[1/S(D(f))]. open Spec def S (U : opens (Spec R)) : set R := { r : R | U.1 ⊆ D'(r) } instance S.is_submonoid (U : opens (Spec R)) : is_submonoid (S U) := { one_mem := λ ⟨P, PI⟩ HP, ((ideal.ne_top_iff_one P).1 PI.1), mul_mem := λ f g Hf Hg, begin show U.1 ⊆ Spec.D'(f*g), exact (Spec.D'.product_eq_inter f g).symm ▸ set.subset_inter Hf Hg, end, } lemma S.rev_mono {U V : opens (Spec R)} (HVU : V ⊆ U) : S U ⊆ S V := λ x Hx, set.subset.trans HVU Hx lemma S.f_mem (f : R) : f ∈ S (Spec.DO R (f)) := set.subset.refl _ lemma S.inter_subset_Sinter (U V : opens (Spec R)) : (S U) ∩ (S V) ⊆ S (U ∩ V) := begin rintros x ⟨HxU, HxV⟩, change U ⊆ Spec.DO R (x) at HxU, change V ⊆ Spec.DO R (x) at HxV, have H := set.inter_subset_inter HxU HxV, rw set.inter_self at H, exact H, end -- Structure presheaf on Spec(R) defined on the basis by the rule ℱ(U) = R[1/S(U)]. variable (R) def structure_presheaf_on_basis : presheaf_of_rings_on_basis (Spec R) (D_fs_basis R) := { F := λ U BU, localization R (S U), res := λ U V BU BV HVU, begin have H := S.rev_mono HVU, apply quotient.lift (λ (x : R × (S U)), ⟦(x.1, (⟨x.2.1, H x.2.2⟩ : S V))⟧), { rintros ⟨a1, b1, Hb1⟩ ⟨a2, b2, Hb2⟩ ⟨t, Ht, Habt⟩; simp, use [t, H Ht, Habt], }, end, Hid := λ U BU, funext $ λ x, quotient.induction_on x $ λ a, by simp, Hcomp := λ U V W BU BV BW HWV HVU, funext $ λ x, quotient.induction_on x $ λ a, by simp, Fring := λ U BU, by apply_instance, res_is_ring_hom := λ U V BU BV HVU, { map_one := rfl, map_add := λ x y, quotient.induction_on₂ x y $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, rfl, map_mul := λ x y, quotient.induction_on₂ x y $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, rfl, }, }
103a3a76b53d9e7533cef4a37811498a8843affd
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/equiv/transfer_instance.lean
02e794229d7c944c729864cfa735eb572e54cef5
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
6,651
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.equiv.basic import algebra.field import algebra.group.type_tags /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. ## Tags equiv, group, ring, field -/ universes u v variables {α : Type u} {β : Type v} namespace equiv section instances variables (e : α ≃ β) /-- Transfer `has_zero` across an `equiv` -/ protected def has_zero [has_zero β] : has_zero α := ⟨e.symm 0⟩ lemma zero_def [has_zero β] : @has_zero.zero _ (equiv.has_zero e) = e.symm 0 := rfl /-- Transfer `has_one` across an `equiv` -/ protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl /-- Transfer `has_mul` across an `equiv` -/ protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl /-- Transfer `has_add` across an `equiv` -/ protected def has_add [has_add β] : has_add α := ⟨λ x y, e.symm (e x + e y)⟩ lemma add_def [has_add β] (x y : α) : @has_add.add _ (equiv.has_add e) x y = e.symm (e x + e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl /-- Transfer `has_neg` across an `equiv` -/ protected def has_neg [has_neg β] : has_neg α := ⟨λ x, e.symm (-e x)⟩ lemma neg_def [has_neg β] (x : α) : @has_neg.neg _ (equiv.has_neg e) x = e.symm (-e x) := rfl /-- Transfer `semigroup` across an `equiv` -/ protected def semigroup [semigroup β] : semigroup α := { mul_assoc := by simp [mul_def, mul_assoc], ..equiv.has_mul e } /-- Transfer `comm_semigroup` across an `equiv` -/ protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := { mul_comm := by simp [mul_def, mul_comm], ..equiv.semigroup e } /-- Transfer `monoid` across an `equiv` -/ protected def monoid [monoid β] : monoid α := { one_mul := by simp [mul_def, one_def], mul_one := by simp [mul_def, one_def], ..equiv.semigroup e, ..equiv.has_one e } /-- Transfer `comm_monoid` across an `equiv` -/ protected def comm_monoid [comm_monoid β] : comm_monoid α := { ..equiv.comm_semigroup e, ..equiv.monoid e } /-- Transfer `group` across an `equiv` -/ protected def group [group β] : group α := { mul_left_inv := by simp [mul_def, inv_def, one_def], ..equiv.monoid e, ..equiv.has_inv e } /-- Transfer `comm_group` across an `equiv` -/ protected def comm_group [comm_group β] : comm_group α := { ..equiv.group e, ..equiv.comm_semigroup e } /-- Transfer `add_semigroup` across an `equiv` -/ protected def add_semigroup [add_semigroup β] : add_semigroup α := @additive.add_semigroup _ (@equiv.semigroup _ _ e multiplicative.semigroup) /-- Transfer `add_comm_semigroup` across an `equiv` -/ protected def add_comm_semigroup [add_comm_semigroup β] : add_comm_semigroup α := @additive.add_comm_semigroup _ (@equiv.comm_semigroup _ _ e multiplicative.comm_semigroup) /-- Transfer `add_monoid` across an `equiv` -/ protected def add_monoid [add_monoid β] : add_monoid α := @additive.add_monoid _ (@equiv.monoid _ _ e multiplicative.monoid) /-- Transfer `add_comm_monoid` across an `equiv` -/ protected def add_comm_monoid [add_comm_monoid β] : add_comm_monoid α := @additive.add_comm_monoid _ (@equiv.comm_monoid _ _ e multiplicative.comm_monoid) /-- Transfer `add_group` across an `equiv` -/ protected def add_group [add_group β] : add_group α := @additive.add_group _ (@equiv.group _ _ e multiplicative.group) /-- Transfer `add_comm_group` across an `equiv` -/ protected def add_comm_group [add_comm_group β] : add_comm_group α := @additive.add_comm_group _ (@equiv.comm_group _ _ e multiplicative.comm_group) /-- Transfer `semiring` across an `equiv` -/ protected def semiring [semiring β] : semiring α := { right_distrib := by simp [mul_def, add_def, add_mul], left_distrib := by simp [mul_def, add_def, mul_add], zero_mul := by simp [mul_def, zero_def], mul_zero := by simp [mul_def, zero_def], ..equiv.has_zero e, ..equiv.has_mul e, ..equiv.has_add e, ..equiv.monoid e, ..equiv.add_comm_monoid e } /-- Transfer `comm_semiring` across an `equiv` -/ protected def comm_semiring [comm_semiring β] : comm_semiring α := { ..equiv.semiring e, ..equiv.comm_monoid e } /-- Transfer `ring` across an `equiv` -/ protected def ring [ring β] : ring α := { ..equiv.semiring e, ..equiv.add_comm_group e } /-- Transfer `comm_ring` across an `equiv` -/ protected def comm_ring [comm_ring β] : comm_ring α := { ..equiv.comm_monoid e, ..equiv.ring e } /-- Transfer `zero_ne_one_class` across an `equiv` -/ protected def zero_ne_one_class [zero_ne_one_class β] : zero_ne_one_class α := { zero_ne_one := by simp [zero_def, one_def], ..equiv.has_zero e, ..equiv.has_one e } /-- Transfer `nonzero_comm_ring` across an `equiv` -/ protected def nonzero_comm_ring [nonzero_comm_ring β] : nonzero_comm_ring α := { ..equiv.zero_ne_one_class e, ..equiv.comm_ring e } /-- Transfer `domain` across an `equiv` -/ protected def domain [domain β] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := by simp [mul_def, zero_def, equiv.eq_symm_apply], ..equiv.has_zero e, ..equiv.zero_ne_one_class e, ..equiv.has_mul e, ..equiv.ring e } /-- Transfer `integral_domain` across an `equiv` -/ protected def integral_domain [integral_domain β] : integral_domain α := { ..equiv.domain e, ..equiv.nonzero_comm_ring e } /-- Transfer `division_ring` across an `equiv` -/ protected def division_ring [division_ring β] : division_ring α := { inv_mul_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact inv_mul_cancel, mul_inv_cancel := λ _, by simp [mul_def, inv_def, zero_def, one_def, (equiv.symm_apply_eq _).symm]; exact mul_inv_cancel, inv_zero := by simp [zero_def, inv_def], ..equiv.has_zero e, ..equiv.has_one e, ..equiv.domain e, ..equiv.has_inv e } /-- Transfer `field` across an `equiv` -/ protected def field [field β] : field α := { ..equiv.integral_domain e, ..equiv.division_ring e } end instances end equiv
e674fdbb7155adc7cd29a54bb292983d8c1e9c20
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/UnificationHint.lean
7e5760a7bdecd9c6f925833e3e4d143a352e6e59
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,409
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.DiscrTree import Lean.Meta.LevelDefEq import Lean.Meta.SynthInstance namespace Lean.Meta structure UnificationHintEntry where keys : Array DiscrTree.Key val : Name deriving Inhabited structure UnificationHints where discrTree : DiscrTree Name := DiscrTree.empty deriving Inhabited instance : ToFormat UnificationHints where format h := fmt h.discrTree def UnificationHints.add (hints : UnificationHints) (e : UnificationHintEntry) : UnificationHints := { hints with discrTree := hints.discrTree.insertCore e.keys e.val } builtin_initialize unificationHintExtension : SimpleScopedEnvExtension UnificationHintEntry UnificationHints ← registerSimpleScopedEnvExtension { name := `unifHints addEntry := UnificationHints.add initial := {} } structure UnificationConstraint where lhs : Expr rhs : Expr structure UnificationHint where pattern : UnificationConstraint constraints : List UnificationConstraint private partial def decodeUnificationHint (e : Expr) : ExceptT MessageData Id UnificationHint := do decode e #[] where decodeConstraint (e : Expr) : ExceptT MessageData Id UnificationConstraint := match e.eq? with | some (_, lhs, rhs) => return UnificationConstraint.mk lhs rhs | none => throw m!"invalid unification hint constraint, unexpected term{indentExpr e}" decode (e : Expr) (cs : Array UnificationConstraint) : ExceptT MessageData Id UnificationHint := do match e with | Expr.forallE _ d b _ => do let c ← decodeConstraint d if b.hasLooseBVars then throw m!"invalid unification hint constraint, unexpected dependency{indentExpr e}" decode b (cs.push c) | _ => do let p ← decodeConstraint e return { pattern := p, constraints := cs.toList } private partial def validateHint (declName : Name) (hint : UnificationHint) : MetaM Unit := do hint.constraints.forM fun c => do unless (← isDefEq c.lhs c.rhs) do throwError! "invalid unification hint, failed to unify constraint left-hand-side{indentExpr c.lhs}\nwith right-hand-side{indentExpr c.rhs}" unless (← isDefEq hint.pattern.lhs hint.pattern.rhs) do throwError! "invalid unification hint, failed to unify pattern left-hand-side{indentExpr hint.pattern.lhs}\nwith right-hand-side{indentExpr hint.pattern.rhs}" def addUnificationHint (declName : Name) (kind : AttributeKind) : MetaM Unit := withNewMCtxDepth do let info ← getConstInfo declName match info.value? with | none => throwError! "invalid unification hint, it must be a definition" | some val => let (_, _, body) ← lambdaMetaTelescope val match decodeUnificationHint body with | Except.error msg => throwError msg | Except.ok hint => let keys ← DiscrTree.mkPath hint.pattern.lhs validateHint declName hint unificationHintExtension.add { keys := keys, val := declName } kind trace[Meta.debug]! "addUnificationHint: {unificationHintExtension.getState (← getEnv)}" builtin_initialize registerBuiltinAttribute { name := `unificationHint descr := "unification hint" add := fun declName stx kind => do Attribute.Builtin.ensureNoArgs stx discard <| addUnificationHint declName kind |>.run } def tryUnificationHints (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.hint]! "{t} =?= {s}" unless (← read).config.unificationHints do return false if t.isMVar then return false let hints := unificationHintExtension.getState (← getEnv) let candidates ← hints.discrTree.getMatch t for candidate in candidates do if (← tryCandidate candidate) then return true return false where isDefEqPattern p e := withReducible <| Meta.isExprDefEqAux p e tryCandidate candidate : MetaM Bool := traceCtx `Meta.isDefEq.hint <| commitWhen do trace[Meta.isDefEq.hint]! "trying hint {candidate} at {t} =?= {s}" let cinfo ← getConstInfo candidate let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar let val := cinfo.instantiateValueLevelParams us let (xs, bis, body) ← lambdaMetaTelescope val let hint? ← withConfig (fun cfg => { cfg with unificationHints := false }) do match decodeUnificationHint body with | Except.error _ => return none | Except.ok hint => if (← isDefEqPattern hint.pattern.lhs t <&&> isDefEqPattern hint.pattern.rhs s) then return some hint else return none match hint? with | none => return false | some hint => trace[Meta.isDefEq.hint]! "{candidate} succeeded, applying constraints" for c in hint.constraints do unless (← Meta.isExprDefEqAux c.lhs c.rhs) do return false for x in xs, bi in bis do if bi == BinderInfo.instImplicit then match (← trySynthInstance (← inferType x)) with | LOption.some val => unless (← isDefEq x val) do return false | _ => return false return true builtin_initialize registerTraceClass `Meta.isDefEq.hint end Lean.Meta
19448ddda27bebf26679c879d6cba959002f5f5a
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/algebra/homomorphism.hlean
cf94ae103e2ded5e73dc73b4246f5f819a21bb84
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
6,351
hlean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Homomorphisms between structures. -/ import algebra.ring function open eq function is_trunc namespace algebra /- additive structures -/ variables {A B C : Type} definition is_add_hom [class] [has_add A] [has_add B] (f : A → B) : Type := ∀ a₁ a₂, f (a₁ + a₂) = f a₁ + f a₂ definition respect_add [has_add A] [has_add B] (f : A → B) [H : is_add_hom f] (a₁ a₂ : A) : f (a₁ + a₂) = f a₁ + f a₂ := H a₁ a₂ definition is_prop_is_add_hom [instance] [has_add A] [has_add B] [is_set B] (f : A → B) : is_prop (is_add_hom f) := by unfold is_add_hom; apply _ definition is_add_hom_id (A : Type) [has_add A] : is_add_hom (@id A) := take a₁ a₂, rfl definition is_add_hom_compose [has_add A] [has_add B] [has_add C] (f : B → C) (g : A → B) [is_add_hom f] [is_add_hom g] : is_add_hom (f ∘ g) := take a₁ a₂, begin esimp, rewrite [respect_add g, respect_add f] end section add_group_A_B variables [add_group A] [add_group B] definition respect_zero (f : A → B) [is_add_hom f] : f (0 : A) = 0 := have f 0 + f 0 = f 0 + 0, by rewrite [-respect_add f, +add_zero], eq_of_add_eq_add_left this definition respect_neg (f : A → B) [is_add_hom f] (a : A) : f (- a) = - f a := have f (- a) + f a = 0, by rewrite [-respect_add f, add.left_inv, respect_zero f], eq_neg_of_add_eq_zero this definition respect_sub (f : A → B) [is_add_hom f] (a₁ a₂ : A) : f (a₁ - a₂) = f a₁ - f a₂ := by rewrite [*sub_eq_add_neg, *(respect_add f), (respect_neg f)] definition is_embedding_of_is_add_hom [add_group B] (f : A → B) [is_add_hom f] (H : ∀ x, f x = 0 → x = 0) : is_embedding f := is_embedding_of_is_injective (take x₁ x₂, suppose f x₁ = f x₂, have f (x₁ - x₂) = 0, by rewrite [respect_sub f, this, sub_self], have x₁ - x₂ = 0, from H _ this, eq_of_sub_eq_zero this) definition eq_zero_of_is_add_hom {f : A → B} [is_add_hom f] [is_embedding f] {a : A} (fa0 : f a = 0) : a = 0 := have f a = f 0, by rewrite [fa0, respect_zero f], show a = 0, from is_injective_of_is_embedding this theorem eq_zero_of_eq_zero_of_is_embedding {f : A → B} [is_add_hom f] [is_embedding f] {a : A} (h : f a = 0) : a = 0 := have f a = f 0, by rewrite [h, respect_zero], show a = 0, from is_injective_of_is_embedding this end add_group_A_B /- multiplicative structures -/ definition is_mul_hom [class] [has_mul A] [has_mul B] (f : A → B) : Type := ∀ a₁ a₂, f (a₁ * a₂) = f a₁ * f a₂ definition respect_mul [has_mul A] [has_mul B] (f : A → B) [H : is_mul_hom f] (a₁ a₂ : A) : f (a₁ * a₂) = f a₁ * f a₂ := H a₁ a₂ definition is_prop_is_mul_hom [instance] [has_mul A] [has_mul B] [is_set B] (f : A → B) : is_prop (is_mul_hom f) := begin unfold is_mul_hom, apply _ end definition is_mul_hom_id (A : Type) [has_mul A] : is_mul_hom (@id A) := take a₁ a₂, rfl definition is_mul_hom_compose [has_mul A] [has_mul B] [has_mul C] (f : B → C) (g : A → B) [is_mul_hom f] [is_mul_hom g] : is_mul_hom (f ∘ g) := take a₁ a₂, begin esimp, rewrite [respect_mul g, respect_mul f] end section group_A_B variables [group A] [group B] definition respect_one (f : A → B) [is_mul_hom f] : f (1 : A) = 1 := have f 1 * f 1 = f 1 * 1, by rewrite [-respect_mul f, *mul_one], eq_of_mul_eq_mul_left' this definition respect_inv (f : A → B) [is_mul_hom f] (a : A) : f (a⁻¹) = (f a)⁻¹ := have f (a⁻¹) * f a = 1, by rewrite [-respect_mul f, mul.left_inv, respect_one f], eq_inv_of_mul_eq_one this definition is_embedding_of_is_mul_hom (f : A → B) [is_mul_hom f] (H : ∀ x, f x = 1 → x = 1) : is_embedding f := is_embedding_of_is_injective (take x₁ x₂, suppose f x₁ = f x₂, have f (x₁ * x₂⁻¹) = 1, by rewrite [respect_mul f, respect_inv f, this, mul.right_inv], have x₁ * x₂⁻¹ = 1, from H _ this, eq_of_mul_inv_eq_one this) definition eq_one_of_is_mul_hom {f : A → B} [is_mul_hom f] [is_embedding f] {a : A} (fa1 : f a = 1) : a = 1 := have f a = f 1, by rewrite [fa1, respect_one f], show a = 1, from is_injective_of_is_embedding this end group_A_B /- rings -/ definition is_ring_hom [class] {R₁ R₂ : Type} [semiring R₁] [semiring R₂] (f : R₁ → R₂) := is_add_hom f × is_mul_hom f × f 1 = 1 definition is_ring_hom.mk {R₁ R₂ : Type} [semiring R₁] [semiring R₂] (f : R₁ → R₂) (h₁ : is_add_hom f) (h₂ : is_mul_hom f) (h₃ : f 1 = 1) : is_ring_hom f := pair h₁ (pair h₂ h₃) definition is_add_hom_of_is_ring_hom [instance] {R₁ R₂ : Type} [semiring R₁] [semiring R₂] (f : R₁ → R₂) [H : is_ring_hom f] : is_add_hom f := prod.pr1 H definition is_mul_hom_of_is_ring_hom [instance] {R₁ R₂ : Type} [semiring R₁] [semiring R₂] (f : R₁ → R₂) [H : is_ring_hom f] : is_mul_hom f := prod.pr1 (prod.pr2 H) definition is_ring_hom.respect_one {R₁ R₂ : Type} [semiring R₁] [semiring R₂] (f : R₁ → R₂) [H : is_ring_hom f] : f 1 = 1 := prod.pr2 (prod.pr2 H) definition is_prop_is_ring_hom [instance] {R₁ R₂ : Type} [semiring R₁] [semiring R₂] (f : R₁ → R₂) : is_prop (is_ring_hom f) := have h₁ : is_prop (is_add_hom f), from _, have h₂ : is_prop (is_mul_hom f), from _, have h₃ : is_prop (f 1 = 1), from _, begin unfold is_ring_hom, apply _ end section semiring variables {R₁ R₂ R₃ : Type} [semiring R₁] [semiring R₂] [semiring R₃] variables (g : R₂ → R₃) (f : R₁ → R₂) [is_ring_hom g] [is_ring_hom f] definition is_ring_hom_id : is_ring_hom (@id R₁) := is_ring_hom.mk id (λ a₁ a₂, rfl) (λ a₁ a₂, rfl) rfl definition is_ring_hom_comp : is_ring_hom (g ∘ f) := is_ring_hom.mk _ (take a₁ a₂, begin esimp, rewrite [respect_add f, respect_add g] end) (take r a, by esimp; rewrite [respect_mul f, respect_mul g]) (by esimp; rewrite *is_ring_hom.respect_one) definition respect_mul_add_mul (a b c d : R₁) : f (a * b + c * d) = f a * f b + f c * f d := by rewrite [respect_add f, +(respect_mul f)] end semiring end algebra
697a1bad96ce089fa67027615badcd177642492d
4ec0e92c725fad3fd2871a0ab050a7da1c719444
/src/mywork/lecture_13.lean
69c5e2c8fca733bb9abdb7764672e7b04e03b94b
[]
no_license
mitchelltaylor06/cs2120f21
cc2c2b61a7e45c07faa849fcb8a66eb948753a25
efb71a748d7c76e24834d03b8f01c3ae084c1756
refs/heads/main
1,693,841,444,092
1,633,713,850,000
1,633,713,850,000
399,946,415
0
0
null
null
null
null
UTF-8
Lean
false
false
3,903
lean
/- UPDATE: Test distributed after class on Monday. Monday will be a review day. The test is due back Wednesday before class. In class Wednesday we will have at least a short quiz to sanity check what you will have submitted for the test. We reserve the right to do follow-on in-person testing if the results indicate a possible problem. -/ /- REVIEW: Last time we focused on the question, how do we construct a proof of ∃ x, P x. To do so, you apply the introduction rule for exists. It's called exists.intro in Lean. You apply it to two arguments: a specific value, w, in place of x, and a proof that that particular w satisfies the predicate, P, i.e., that there is a proof of the proposition, P w. In other words, you can think of a proof of ∃ x, P x, as a pair, ⟨w, pf ⟩, where w is a witness and pf is a proof of P w. -/ /- Today we'll delve deeper into the mysteries of exists elimination, or how you can *use* a proof of ∃ x, P x. Here's the idea: If you have a proof, ex, of of ∃ (x : X), P x, you can apply exists.elim to ex, and (after a few more simple maneuvers) have yourself a specific value, (w : X), and a proof that w satisfies P, i.e., (pf : P w). The idea is that you can then uses the values in your subsequent proof steps. Why does this rule make sense? Consider a very simple example. If I tell you there exists some green ball, you can say, "well, call it b," and give that we know it's green, we also know that it satisfies the isGreen _ predicate, so we can also assume we have a proof of (isGreen b). In this example, b is a witness to the fact that some object satisfies the predicate. The proof then shows for sure that that is so. -/ example : ∃ (b : bool), b && tt = ff := begin apply exists.intro ff, trivial, end example : (exists (b : bool), b && tt = ff) → (∃ (b : bool), true) := begin assume h, cases h with w pf, apply exists.intro w, trivial, end /- Let's set up some assumptions so that we can explore their consequences when it comes to existentially quantified propositions. -/ /- Beachballs! What could be more fun -/ axioms (Ball : Type) -- There are balls (Green : Ball → Prop) -- a Ball can be Green (Red : Ball → Prop) -- a Ball can be Red (b1 b2 : Ball) -- b1 and b2 are balls (b1r : Red b1) -- b1 is red (b1g : Green b1) -- b1 is green (b2r : Red b2) -- b2 is red example : (∃ (b : Ball), Red b ∧ Green b) → (∃ (b : Ball), Red b) := begin assume h, cases h with w pf, apply exists.intro w, have rw : Red w := and.elim_left pf, exact rw, end example : (∃ (b : Ball), Red b ∨ Green b) → (∃ (b : Ball), Green b ∨ Red b) := begin assume h, cases h with w pf, apply exists.intro w, cases pf, apply or.inr, exact pf, apply or.inl, exact pf, end example : (∃ (b : Ball), Red b ∨ Green b) → (∃ (b : Ball), Red b) := begin end example : (∃ (b : Ball), Red b) → (∃ (b : Ball), Red b ∨ Green b) := begin assume h, cases h with w pf, apply exists.intro w, apply or.inl, exact pf, end /- Social Networks -/ axioms (Person : Type) (Nice : Person → Prop) (Likes : Person → Person → Prop) example : (∃ (p1 : Person), ∀ (p2 : Person), Likes p2 p1) → (∀ (e : Person), ∃ (s : Person), Likes e s) := begin assume h, assume e, cases h with p pf, apply exists.intro p, apply pf e, end /- Write formal expressions for each of the following English language sentences. -/ -- Everyone likes him or herself -- Someone doesn't like him or herself -- There is someone likes someone else -- No one likes anyone who dislikes them -- Everyone likes anyone who is nice -- No one likes anyone who is not nice /- If everyone who's nice likes someone, then there is someone whom everyone who is nice likes. -/
35889ed856268190d4513462d8e3b00eca0346cf
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/intromacro.lean
f7e5ccf1fe6f54f5644f98de685034589b1ecd72
[ "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
559
lean
structure S := (x y z : Nat := 0) def f1 : Nat × Nat → S → Nat := by { intro (x, y); intro ⟨a, b, c⟩; exact x+y+a } theorem ex1 : f1 (10, 20) { x := 10 } = 40 := rfl def f2 : Nat × Nat → S → Nat := by { intro (a, b) { y := y, .. }; exact a+b+y } #eval f2 (10, 20) { y := 5 } theorem ex2 : f2 (10, 20) { y := 5 } = 35 := rfl def f3 : Nat × Nat → S → S → Nat := by { intro (a, b) { y := y, .. } s; exact a+b+y+s.x } #eval f3 (10, 20) { y := 5 } { x := 1 } theorem ex3 : f3 (10, 20) { y := 5 } { x := 1 } = 36 := rfl
7c9176c4411dd42052d3f72de3785140d9cf2c1e
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/omega/int/dnf.lean
f74df8d722e9e9f74659f72171349a3ba806c9b5
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
6,294
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek DNF transformation. -/ import tactic.omega.clause import tactic.omega.int.form namespace omega namespace int open_locale omega.int /-- push_neg p returns the result of normalizing ¬ p by pushing the outermost negation all the way down, until it reaches either a negation or an atom -/ @[simp] def push_neg : preform → preform | (p ∨* q) := (push_neg p) ∧* (push_neg q) | (p ∧* q) := (push_neg p) ∨* (push_neg q) | (¬*p) := p | p := ¬* p lemma push_neg_equiv : ∀ {p : preform}, preform.equiv (push_neg p) (¬* p) := begin preform.induce `[intros v; try {refl}], { simp only [classical.not_not, push_neg, preform.holds] }, { simp only [preform.holds, push_neg, not_or_distrib, ihp v, ihq v] }, { simp only [preform.holds, push_neg, classical.not_and_distrib, ihp v, ihq v] } end /-- NNF transformation -/ def nnf : preform → preform | (¬* p) := push_neg (nnf p) | (p ∨* q) := (nnf p) ∨* (nnf q) | (p ∧* q) := (nnf p) ∧* (nnf q) | a := a def is_nnf : preform → Prop | (t =* s) := true | (t ≤* s) := true | ¬*(t =* s) := true | ¬*(t ≤* s) := true | (p ∨* q) := is_nnf p ∧ is_nnf q | (p ∧* q) := is_nnf p ∧ is_nnf q | _ := false lemma is_nnf_push_neg : ∀ p : preform, is_nnf p → is_nnf (push_neg p) := begin preform.induce `[intro h1; try {trivial}], { cases p; try {cases h1}; trivial }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption } end /-- Argument is free of negations -/ def neg_free : preform → Prop | (t =* s) := true | (t ≤* s) := true | (p ∨* q) := neg_free p ∧ neg_free q | (p ∧* q) := neg_free p ∧ neg_free q | _ := false lemma is_nnf_nnf : ∀ p : preform, is_nnf (nnf p) := begin preform.induce `[try {trivial}], { apply is_nnf_push_neg _ ih }, { constructor; assumption }, { constructor; assumption } end lemma nnf_equiv : ∀ {p : preform}, preform.equiv (nnf p) p := begin preform.induce `[intros v; try {refl}; simp only [nnf]], { rw push_neg_equiv, apply not_iff_not_of_iff, apply ih }, { apply pred_mono_2' (ihp v) (ihq v) }, { apply pred_mono_2' (ihp v) (ihq v) } end /-- Eliminate all negations from preform -/ @[simp] def neg_elim : preform → preform | (¬* (t =* s)) := (t.add_one ≤* s) ∨* (s.add_one ≤* t) | (¬* (t ≤* s)) := s.add_one ≤* t | (p ∨* q) := (neg_elim p) ∨* (neg_elim q) | (p ∧* q) := (neg_elim p) ∧* (neg_elim q) | p := p lemma neg_free_neg_elim : ∀ p : preform, is_nnf p → neg_free (neg_elim p) := begin preform.induce `[intro h1, try {simp only [neg_free, neg_elim]}, try {trivial}], { cases p; try {cases h1}; try {trivial}, constructor; trivial }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption } end lemma le_and_le_iff_eq {α : Type} [partial_order α] {a b : α} : (a ≤ b ∧ b ≤ a) ↔ a = b := begin constructor; intro h1, { cases h1, apply le_antisymm; assumption }, { constructor; apply le_of_eq; rw h1 } end lemma implies_neg_elim : ∀ {p : preform}, preform.implies p (neg_elim p) := begin preform.induce `[intros v h, try {apply h}], { cases p with t s t s; try {apply h}, { simp only [le_and_le_iff_eq.symm, classical.not_and_distrib, not_le, preterm.val, preform.holds] at h, simp only [int.add_one_le_iff, preterm.add_one, preterm.val, preform.holds, neg_elim], rw or_comm, assumption }, { simp only [not_le, int.add_one_le_iff, preterm.add_one, not_le, preterm.val, preform.holds, neg_elim] at *, assumption} }, { simp only [neg_elim], cases h; [{left, apply ihp}, {right, apply ihq}]; assumption }, { apply and.imp (ihp _) (ihq _) h } end @[simp] def dnf_core : preform → list clause | (p ∨* q) := (dnf_core p) ++ (dnf_core q) | (p ∧* q) := (list.product (dnf_core p) (dnf_core q)).map (λ pq, clause.append pq.fst pq.snd) | (t =* s) := [([term.sub (canonize s) (canonize t)],[])] | (t ≤* s) := [([],[term.sub (canonize s) (canonize t)])] | (¬* _) := [] /-- DNF transformation -/ def dnf (p : preform) : list clause := dnf_core $ neg_elim $ nnf p lemma exists_clause_holds {v : nat → int} : ∀ {p : preform}, neg_free p → p.holds v → ∃ c ∈ (dnf_core p), clause.holds v c := begin preform.induce `[intros h1 h2], { apply list.exists_mem_cons_of, constructor, { simp only [preterm.val, preform.holds] at h2, rw [list.forall_mem_singleton], simp only [h2, omega.int.val_canonize, omega.term.val_sub, sub_self] }, { apply list.forall_mem_nil } }, { apply list.exists_mem_cons_of, constructor, { apply list.forall_mem_nil }, { simp only [preterm.val, preform.holds] at h2 , rw [list.forall_mem_singleton], simp only [val_canonize, preterm.val, term.val_sub], rw [le_sub, sub_zero], assumption } }, { cases h1 }, { cases h2 with h2 h2; [ {cases (ihp h1.left h2) with c h3}, {cases (ihq h1.right h2) with c h3}]; cases h3 with h3 h4; refine ⟨c, list.mem_append.elim_right _, h4⟩; [left,right]; assumption }, { rcases (ihp h1.left h2.left) with ⟨cp, hp1, hp2⟩, rcases (ihq h1.right h2.right) with ⟨cq, hq1, hq2⟩, refine ⟨clause.append cp cq, ⟨_, clause.holds_append hp2 hq2⟩⟩, simp only [dnf_core, list.mem_map], refine ⟨(cp,cq),⟨_,rfl⟩⟩, rw list.mem_product, constructor; assumption } end lemma clauses_sat_dnf_core {p : preform} : neg_free p → p.sat → clauses.sat (dnf_core p) := begin intros h1 h2, cases h2 with v h2, rcases (exists_clause_holds h1 h2) with ⟨c,h3,h4⟩, refine ⟨c,h3,v,h4⟩ end lemma unsat_of_clauses_unsat {p : preform} : clauses.unsat (dnf p) → p.unsat := begin intros h1 h2, apply h1, apply clauses_sat_dnf_core, apply neg_free_neg_elim _ (is_nnf_nnf _), apply preform.sat_of_implies_of_sat implies_neg_elim, have hrw := exists_congr (@nnf_equiv p), apply hrw.elim_right h2 end end int end omega
382d914c0dd412966909b24c7346f6a7972d54a2
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/hahn_series.lean
376950fafe1055eb89b3e96e34d3cd59757d8f00
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
61,430
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.well_founded_set import algebra.big_operators.finprod import ring_theory.valuation.basic import ring_theory.power_series.basic import data.finsupp.pwo import data.finset.mul_antidiagonal import algebra.order.group.with_top /-! # Hahn Series If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. With further structure on `R` and `Γ`, we can add further structure on `hahn_series Γ R`, with the most studied case being when `Γ` is a linearly ordered abelian group and `R` is a field, in which case `hahn_series Γ R` is a valued field, with value group `Γ`. These generalize Laurent series (with value group `ℤ`), and Laurent series are implemented that way in the file `ring_theory/laurent_series`. ## Main Definitions * If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. * If `R` is a (commutative) additive monoid or group, then so is `hahn_series Γ R`. * If `R` is a (comm_)(semi)ring, then so is `hahn_series Γ R`. * `hahn_series.add_val Γ R` defines an `add_valuation` on `hahn_series Γ R` when `Γ` is linearly ordered. * A `hahn_series.summable_family` is a family of Hahn series such that the union of their supports is well-founded and only finitely many are nonzero at any given coefficient. They have a formal sum, `hahn_series.summable_family.hsum`, which can be bundled as a `linear_map` as `hahn_series.summable_family.lsum`. Note that this is different from `summable` in the valuation topology, because there are topologically summable families that do not satisfy the axioms of `hahn_series.summable_family`, and formally summable families whose sums do not converge topologically. * Laurent series over `R` are implemented as `hahn_series ℤ R` in the file `ring_theory/laurent_series`. ## TODO * Build an API for the variable `X` (defined to be `single 1 1 : hahn_series Γ R`) in analogy to `X : R[X]` and `X : power_series R` ## References - [J. van der Hoeven, *Operators on Generalized Power Series*][van_der_hoeven] -/ open finset function open_locale big_operators classical pointwise polynomial noncomputable theory /-- If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/ @[ext] structure hahn_series (Γ : Type*) (R : Type*) [partial_order Γ] [has_zero R] := (coeff : Γ → R) (is_pwo_support' : (support coeff).is_pwo) variables {Γ : Type*} {R : Type*} namespace hahn_series section zero variables [partial_order Γ] [has_zero R] lemma coeff_injective : injective (coeff : hahn_series Γ R → (Γ → R)) := ext @[simp] lemma coeff_inj {x y : hahn_series Γ R} : x.coeff = y.coeff ↔ x = y := coeff_injective.eq_iff /-- The support of a Hahn series is just the set of indices whose coefficients are nonzero. Notably, it is well-founded. -/ def support (x : hahn_series Γ R) : set Γ := support x.coeff @[simp] lemma is_pwo_support (x : hahn_series Γ R) : x.support.is_pwo := x.is_pwo_support' @[simp] lemma is_wf_support (x : hahn_series Γ R) : x.support.is_wf := x.is_pwo_support.is_wf @[simp] lemma mem_support (x : hahn_series Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := iff.refl _ instance : has_zero (hahn_series Γ R) := ⟨{ coeff := 0, is_pwo_support' := by simp }⟩ instance : inhabited (hahn_series Γ R) := ⟨0⟩ instance [subsingleton R] : subsingleton (hahn_series Γ R) := ⟨λ a b, a.ext b (subsingleton.elim _ _)⟩ @[simp] lemma zero_coeff {a : Γ} : (0 : hahn_series Γ R).coeff a = 0 := rfl @[simp] lemma coeff_fun_eq_zero_iff {x : hahn_series Γ R} : x.coeff = 0 ↔ x = 0 := coeff_injective.eq_iff' rfl lemma ne_zero_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x ≠ 0 := mt (λ x0, (x0.symm ▸ zero_coeff : x.coeff g = 0)) h @[simp] lemma support_zero : support (0 : hahn_series Γ R) = ∅ := function.support_zero @[simp] lemma support_nonempty_iff {x : hahn_series Γ R} : x.support.nonempty ↔ x ≠ 0 := by rw [support, support_nonempty_iff, ne.def, coeff_fun_eq_zero_iff] @[simp] lemma support_eq_empty_iff {x : hahn_series Γ R} : x.support = ∅ ↔ x = 0 := support_eq_empty_iff.trans coeff_fun_eq_zero_iff /-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/ def single (a : Γ) : zero_hom R (hahn_series Γ R) := { to_fun := λ r, { coeff := pi.single a r, is_pwo_support' := (set.is_pwo_singleton a).mono pi.support_single_subset }, map_zero' := ext _ _ (pi.single_zero _) } variables {a b : Γ} {r : R} @[simp] theorem single_coeff_same (a : Γ) (r : R) : (single a r).coeff a = r := pi.single_eq_same a r @[simp] theorem single_coeff_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := pi.single_eq_of_ne h r theorem single_coeff : (single a r).coeff b = if (b = a) then r else 0 := by { split_ifs with h; simp [h] } @[simp] lemma support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} := pi.support_single_of_ne h lemma support_single_subset : support (single a r) ⊆ {a} := pi.support_single_subset lemma eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a := support_single_subset h @[simp] lemma single_eq_zero : (single a (0 : R)) = 0 := (single a).map_zero lemma single_injective (a : Γ) : function.injective (single a : R → hahn_series Γ R) := λ r s rs, by rw [← single_coeff_same a r, ← single_coeff_same a s, rs] lemma single_ne_zero (h : r ≠ 0) : single a r ≠ 0 := λ con, h (single_injective a (con.trans single_eq_zero.symm)) @[simp] lemma single_eq_zero_iff {a : Γ} {r : R} : single a r = 0 ↔ r = 0 := begin split, { contrapose!, exact single_ne_zero }, { simp {contextual := tt} } end instance [nonempty Γ] [nontrivial R] : nontrivial (hahn_series Γ R) := ⟨begin obtain ⟨r, s, rs⟩ := exists_pair_ne R, inhabit Γ, refine ⟨single (arbitrary Γ) r, single (arbitrary Γ) s, λ con, rs _⟩, rw [← single_coeff_same (arbitrary Γ) r, con, single_coeff_same], end⟩ section order variable [has_zero Γ] /-- The order of a nonzero Hahn series `x` is a minimal element of `Γ` where `x` has a nonzero coefficient, the order of 0 is 0. -/ def order (x : hahn_series Γ R) : Γ := if h : x = 0 then 0 else x.is_wf_support.min (support_nonempty_iff.2 h) @[simp] lemma order_zero : order (0 : hahn_series Γ R) = 0 := dif_pos rfl lemma order_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : order x = x.is_wf_support.min (support_nonempty_iff.2 hx) := dif_neg hx lemma coeff_order_ne_zero {x : hahn_series Γ R} (hx : x ≠ 0) : x.coeff x.order ≠ 0 := begin rw order_of_ne hx, exact x.is_wf_support.min_mem (support_nonempty_iff.2 hx) end lemma order_le_of_coeff_ne_zero {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x.order ≤ g := le_trans (le_of_eq (order_of_ne (ne_zero_of_coeff_ne_zero h))) (set.is_wf.min_le _ _ ((mem_support _ _).2 h)) @[simp] lemma order_single (h : r ≠ 0) : (single a r).order = a := (order_of_ne (single_ne_zero h)).trans (support_single_subset ((single a r).is_wf_support.min_mem (support_nonempty_iff.2 (single_ne_zero h)))) lemma coeff_eq_zero_of_lt_order {x : hahn_series Γ R} {i : Γ} (hi : i < x.order) : x.coeff i = 0 := begin rcases eq_or_ne x 0 with rfl|hx, { simp }, contrapose! hi, rw [←ne.def, ←mem_support] at hi, rw [order_of_ne hx], exact set.is_wf.not_lt_min _ _ hi end end order section domain variables {Γ' : Type*} [partial_order Γ'] /-- Extends the domain of a `hahn_series` by an `order_embedding`. -/ def emb_domain (f : Γ ↪o Γ') : hahn_series Γ R → hahn_series Γ' R := λ x, { coeff := λ (b : Γ'), if h : b ∈ f '' x.support then x.coeff (classical.some h) else 0, is_pwo_support' := (x.is_pwo_support.image_of_monotone f.monotone).mono (λ b hb, begin contrapose! hb, rw [function.mem_support, dif_neg hb, not_not], end) } @[simp] lemma emb_domain_coeff {f : Γ ↪o Γ'} {x : hahn_series Γ R} {a : Γ} : (emb_domain f x).coeff (f a) = x.coeff a := begin rw emb_domain, dsimp only, by_cases ha : a ∈ x.support, { rw dif_pos (set.mem_image_of_mem f ha), exact congr rfl (f.injective (classical.some_spec (set.mem_image_of_mem f ha)).2) }, { rw [dif_neg, not_not.1 (λ c, ha ((mem_support _ _).2 c))], contrapose! ha, obtain ⟨b, hb1, hb2⟩ := (set.mem_image _ _ _).1 ha, rwa f.injective hb2 at hb1 } end @[simp] lemma emb_domain_mk_coeff {f : Γ → Γ'} (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') {x : hahn_series Γ R} {a : Γ} : (emb_domain ⟨⟨f, hfi⟩, hf⟩ x).coeff (f a) = x.coeff a := emb_domain_coeff lemma emb_domain_notin_image_support {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'} (hb : b ∉ f '' x.support) : (emb_domain f x).coeff b = 0 := dif_neg hb lemma support_emb_domain_subset {f : Γ ↪o Γ'} {x : hahn_series Γ R} : support (emb_domain f x) ⊆ f '' x.support := begin intros g hg, contrapose! hg, rw [mem_support, emb_domain_notin_image_support hg, not_not], end lemma emb_domain_notin_range {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'} (hb : b ∉ set.range f) : (emb_domain f x).coeff b = 0 := emb_domain_notin_image_support (λ con, hb (set.image_subset_range _ _ con)) @[simp] lemma emb_domain_zero {f : Γ ↪o Γ'} : emb_domain f (0 : hahn_series Γ R) = 0 := by { ext, simp [emb_domain_notin_image_support] } @[simp] lemma emb_domain_single {f : Γ ↪o Γ'} {g : Γ} {r : R} : emb_domain f (single g r) = single (f g) r := begin ext g', by_cases h : g' = f g, { simp [h] }, rw [emb_domain_notin_image_support, single_coeff_of_ne h], by_cases hr : r = 0, { simp [hr] }, rwa [support_single_of_ne hr, set.image_singleton, set.mem_singleton_iff], end lemma emb_domain_injective {f : Γ ↪o Γ'} : function.injective (emb_domain f : hahn_series Γ R → hahn_series Γ' R) := λ x y xy, begin ext g, rw [ext_iff, function.funext_iff] at xy, have xyg := xy (f g), rwa [emb_domain_coeff, emb_domain_coeff] at xyg, end end domain end zero section addition variable [partial_order Γ] section add_monoid variable [add_monoid R] instance : has_add (hahn_series Γ R) := { add := λ x y, { coeff := x.coeff + y.coeff, is_pwo_support' := (x.is_pwo_support.union y.is_pwo_support).mono (function.support_add _ _) } } instance : add_monoid (hahn_series Γ R) := { zero := 0, add := (+), add_assoc := λ x y z, by { ext, apply add_assoc }, zero_add := λ x, by { ext, apply zero_add }, add_zero := λ x, by { ext, apply add_zero } } @[simp] lemma add_coeff' {x y : hahn_series Γ R} : (x + y).coeff = x.coeff + y.coeff := rfl lemma add_coeff {x y : hahn_series Γ R} {a : Γ} : (x + y).coeff a = x.coeff a + y.coeff a := rfl lemma support_add_subset {x y : hahn_series Γ R} : support (x + y) ⊆ support x ∪ support y := λ a ha, begin rw [mem_support, add_coeff] at ha, rw [set.mem_union, mem_support, mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero], end lemma min_order_le_order_add {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x y : hahn_series Γ R} (hxy : x + y ≠ 0) : min x.order y.order ≤ (x + y).order := begin by_cases hx : x = 0, { simp [hx], }, by_cases hy : y = 0, { simp [hy], }, rw [order_of_ne hx, order_of_ne hy, order_of_ne hxy], refine le_trans _ (set.is_wf.min_le_min_of_subset support_add_subset), { exact x.is_wf_support.union y.is_wf_support }, { exact set.nonempty.mono (set.subset_union_left _ _) (support_nonempty_iff.2 hx) }, rw set.is_wf.min_union, end /-- `single` as an additive monoid/group homomorphism -/ @[simps] def single.add_monoid_hom (a : Γ) : R →+ (hahn_series Γ R) := { map_add' := λ x y, by { ext b, by_cases h : b = a; simp [h] }, ..single a } /-- `coeff g` as an additive monoid/group homomorphism -/ @[simps] def coeff.add_monoid_hom (g : Γ) : (hahn_series Γ R) →+ R := { to_fun := λ f, f.coeff g, map_zero' := zero_coeff, map_add' := λ x y, add_coeff } section domain variables {Γ' : Type*} [partial_order Γ'] lemma emb_domain_add (f : Γ ↪o Γ') (x y : hahn_series Γ R) : emb_domain f (x + y) = emb_domain f x + emb_domain f y := begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨a, rfl⟩ := hg, simp }, { simp [emb_domain_notin_range, hg] } end end domain end add_monoid instance [add_comm_monoid R] : add_comm_monoid (hahn_series Γ R) := { add_comm := λ x y, by { ext, apply add_comm } .. hahn_series.add_monoid } section add_group variable [add_group R] instance : add_group (hahn_series Γ R) := { neg := λ x, { coeff := λ a, - x.coeff a, is_pwo_support' := by { rw function.support_neg, exact x.is_pwo_support }, }, add_left_neg := λ x, by { ext, apply add_left_neg }, .. hahn_series.add_monoid } @[simp] lemma neg_coeff' {x : hahn_series Γ R} : (- x).coeff = - x.coeff := rfl lemma neg_coeff {x : hahn_series Γ R} {a : Γ} : (- x).coeff a = - x.coeff a := rfl @[simp] lemma support_neg {x : hahn_series Γ R} : (- x).support = x.support := by { ext, simp } @[simp] lemma sub_coeff' {x y : hahn_series Γ R} : (x - y).coeff = x.coeff - y.coeff := by { ext, simp [sub_eq_add_neg] } lemma sub_coeff {x y : hahn_series Γ R} {a : Γ} : (x - y).coeff a = x.coeff a - y.coeff a := by simp end add_group instance [add_comm_group R] : add_comm_group (hahn_series Γ R) := { .. hahn_series.add_comm_monoid, .. hahn_series.add_group } end addition section distrib_mul_action variables [partial_order Γ] {V : Type*} [monoid R] [add_monoid V] [distrib_mul_action R V] instance : has_smul R (hahn_series Γ V) := ⟨λ r x, { coeff := r • x.coeff, is_pwo_support' := x.is_pwo_support.mono (function.support_smul_subset_right r x.coeff) }⟩ @[simp] lemma smul_coeff {r : R} {x : hahn_series Γ V} {a : Γ} : (r • x).coeff a = r • (x.coeff a) := rfl instance : distrib_mul_action R (hahn_series Γ V) := { smul := (•), one_smul := λ _, by { ext, simp }, smul_zero := λ _, by { ext, simp }, smul_add := λ _ _ _, by { ext, simp [smul_add] }, mul_smul := λ _ _ _, by { ext, simp [mul_smul] } } variables {S : Type*} [monoid S] [distrib_mul_action S V] instance [has_smul R S] [is_scalar_tower R S V] : is_scalar_tower R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp }⟩ instance [smul_comm_class R S V] : smul_comm_class R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp [smul_comm] }⟩ end distrib_mul_action section module variables [partial_order Γ] [semiring R] {V : Type*} [add_comm_monoid V] [module R V] instance : module R (hahn_series Γ V) := { zero_smul := λ _, by { ext, simp }, add_smul := λ _ _ _, by { ext, simp [add_smul] }, .. hahn_series.distrib_mul_action } /-- `single` as a linear map -/ @[simps] def single.linear_map (a : Γ) : R →ₗ[R] (hahn_series Γ R) := { map_smul' := λ r s, by { ext b, by_cases h : b = a; simp [h] }, ..single.add_monoid_hom a } /-- `coeff g` as a linear map -/ @[simps] def coeff.linear_map (g : Γ) : (hahn_series Γ R) →ₗ[R] R := { map_smul' := λ r s, rfl, ..coeff.add_monoid_hom g } section domain variables {Γ' : Type*} [partial_order Γ'] lemma emb_domain_smul (f : Γ ↪o Γ') (r : R) (x : hahn_series Γ R) : emb_domain f (r • x) = r • emb_domain f x := begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨a, rfl⟩ := hg, simp }, { simp [emb_domain_notin_range, hg] } end /-- Extending the domain of Hahn series is a linear map. -/ @[simps] def emb_domain_linear_map (f : Γ ↪o Γ') : hahn_series Γ R →ₗ[R] hahn_series Γ' R := { to_fun := emb_domain f, map_add' := emb_domain_add f, map_smul' := emb_domain_smul f } end domain end module section multiplication variable [ordered_cancel_add_comm_monoid Γ] instance [has_zero R] [has_one R] : has_one (hahn_series Γ R) := ⟨single 0 1⟩ @[simp] lemma one_coeff [has_zero R] [has_one R] {a : Γ} : (1 : hahn_series Γ R).coeff a = if a = 0 then 1 else 0 := single_coeff @[simp] lemma single_zero_one [has_zero R] [has_one R] : (single 0 (1 : R)) = 1 := rfl @[simp] lemma support_one [mul_zero_one_class R] [nontrivial R] : support (1 : hahn_series Γ R) = {0} := support_single_of_ne one_ne_zero @[simp] lemma order_one [mul_zero_one_class R] : order (1 : hahn_series Γ R) = 0 := begin cases subsingleton_or_nontrivial R with h h; haveI := h, { rw [subsingleton.elim (1 : hahn_series Γ R) 0, order_zero] }, { exact order_single one_ne_zero } end instance [non_unital_non_assoc_semiring R] : has_mul (hahn_series Γ R) := { mul := λ x y, { coeff := λ a, ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd, is_pwo_support' := begin have h : {a : Γ | ∑ (ij : Γ × Γ) in add_antidiagonal x.is_pwo_support y.is_pwo_support a, x.coeff ij.fst * y.coeff ij.snd ≠ 0} ⊆ {a : Γ | (add_antidiagonal x.is_pwo_support y.is_pwo_support a).nonempty}, { intros a ha, contrapose! ha, simp [not_nonempty_iff_eq_empty.1 ha] }, exact is_pwo_support_add_antidiagonal.mono h, end, }, } @[simp] lemma mul_coeff [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd := rfl lemma mul_coeff_right' [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_pwo) (hys : y.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support hs a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_right hys) _ (λ _ _, rfl), intros b hb, simp only [not_and, mem_sdiff, mem_add_antidiagonal, mem_support, not_imp_not] at hb, rw [hb.2 hb.1.1 hb.1.2.2, mul_zero], end lemma mul_coeff_left' [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_pwo) (hxs : x.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal hs y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_left hxs) _ (λ _ _, rfl), intros b hb, simp only [not_and', mem_sdiff, mem_add_antidiagonal, mem_support, not_ne_iff] at hb, rw [hb.2 ⟨hb.1.2.1, hb.1.2.2⟩, zero_mul], end instance [non_unital_non_assoc_semiring R] : distrib (hahn_series Γ R) := { left_distrib := λ x y z, begin ext a, have hwf := (y.is_pwo_support.union z.is_pwo_support), rw [mul_coeff_right' hwf, add_coeff, mul_coeff_right' hwf (set.subset_union_right _ _), mul_coeff_right' hwf (set.subset_union_left _ _)], { simp only [add_coeff, mul_add, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], } end, right_distrib := λ x y z, begin ext a, have hwf := (x.is_pwo_support.union y.is_pwo_support), rw [mul_coeff_left' hwf, add_coeff, mul_coeff_left' hwf (set.subset_union_right _ _), mul_coeff_left' hwf (set.subset_union_left _ _)], { simp only [add_coeff, add_mul, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], }, end, .. hahn_series.has_mul, .. hahn_series.has_add } lemma single_mul_coeff_add [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : ((single b r) * x).coeff (a + b) = r * x.coeff a := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, mul_zero], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro rfl h2 h1, rw add_comm at h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(b, a)}, (single b r).coeff ij.fst * x.coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨rfl, h2, h1⟩, rw add_comm at h1, refine ⟨rfl, add_right_cancel h1⟩ }, { rintro ⟨rfl, rfl⟩, exact ⟨rfl, by simp [hx], add_comm _ _⟩ } }, { simp } end lemma mul_single_coeff_add [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : (x * (single b r)).coeff (a + b) = x.coeff a * r := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, zero_mul], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h2 rfl h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(a,b)}, x.coeff ij.fst * (single b r).coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h2, rfl, h1⟩, refine ⟨add_right_cancel h1, rfl⟩ }, { rintro ⟨rfl, rfl⟩, simp [hx] } }, { simp } end @[simp] lemma mul_single_zero_coeff [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : (x * (single 0 r)).coeff a = x.coeff a * r := by rw [← add_zero a, mul_single_coeff_add, add_zero] lemma single_zero_mul_coeff [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : ((single 0 r) * x).coeff a = r * x.coeff a := by rw [← add_zero a, single_mul_coeff_add, add_zero] @[simp] lemma single_zero_mul_eq_smul [semiring R] {r : R} {x : hahn_series Γ R} : (single 0 r) * x = r • x := by { ext, exact single_zero_mul_coeff } theorem support_mul_subset_add_support [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} : support (x * y) ⊆ support x + support y := begin apply set.subset.trans (λ x hx, _) support_add_antidiagonal_subset_add, { exact x.is_pwo_support }, { exact y.is_pwo_support }, contrapose! hx, simp only [not_nonempty_iff_eq_empty, ne.def, set.mem_set_of_eq] at hx, simp [hx], end lemma mul_coeff_order_add_order {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [non_unital_non_assoc_semiring R] (x y : hahn_series Γ R) : (x * y).coeff (x.order + y.order) = x.coeff x.order * y.coeff y.order := begin by_cases hx : x = 0, { simp [hx], }, by_cases hy : y = 0, { simp [hy], }, rw [order_of_ne hx, order_of_ne hy, mul_coeff, finset.add_antidiagonal_min_add_min, finset.sum_singleton], end private lemma mul_assoc' [non_unital_semiring R] (x y z : hahn_series Γ R) : x * y * z = x * (y * z) := begin ext b, rw [mul_coeff_left' (x.is_pwo_support.add y.is_pwo_support) support_mul_subset_add_support, mul_coeff_right' (y.is_pwo_support.add z.is_pwo_support) support_mul_subset_add_support], simp only [mul_coeff, add_coeff, sum_mul, mul_sum, sum_sigma'], refine sum_bij_ne_zero (λ a has ha0, ⟨⟨a.2.1, a.2.2 + a.1.2⟩, ⟨a.2.2, a.1.2⟩⟩) _ _ _ _, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [and_true, set.image2_add, eq_self_iff_true, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq] at H1 H2 ⊢, obtain ⟨⟨H3, nz, rfl⟩, nx, ny, rfl⟩ := H1, exact ⟨⟨nx, set.add_mem_add ny nz, (add_assoc _ _ _).symm⟩, ny, nz⟩ }, { rintros ⟨⟨i1,j1⟩, k1,l1⟩ ⟨⟨i2,j2⟩, k2,l2⟩ H1 H2 H3 H4 H5, simp only [set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq] at H1 H3 H5, obtain ⟨⟨rfl, H⟩, rfl, rfl⟩ := H5, simp only [and_true, prod.mk.inj_iff, eq_self_iff_true, heq_iff_eq, ←H1.2.2.2, ←H3.2.2.2] }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [exists_prop, set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, sigma.exists, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq, prod.exists] at H1 H2 ⊢, obtain ⟨⟨nx, H, rfl⟩, ny, nz, rfl⟩ := H1, exact ⟨i + k, l, i, k, ⟨⟨set.add_mem_add nx ny, nz, add_assoc _ _ _⟩, nx, ny, rfl⟩, λ con, H2 ((mul_assoc _ _ _).symm.trans con), ⟨rfl, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp [mul_assoc], } end instance [non_unital_non_assoc_semiring R] : non_unital_non_assoc_semiring (hahn_series Γ R) := { zero := 0, add := (+), mul := (*), zero_mul := λ _, by { ext, simp }, mul_zero := λ _, by { ext, simp }, .. hahn_series.add_comm_monoid, .. hahn_series.distrib } instance [non_unital_semiring R] : non_unital_semiring (hahn_series Γ R) := { zero := 0, add := (+), mul := (*), mul_assoc := mul_assoc', .. hahn_series.non_unital_non_assoc_semiring } instance [non_assoc_semiring R] : non_assoc_semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), one_mul := λ x, by { ext, exact single_zero_mul_coeff.trans (one_mul _) }, mul_one := λ x, by { ext, exact mul_single_zero_coeff.trans (mul_one _) }, .. add_monoid_with_one.unary, .. hahn_series.non_unital_non_assoc_semiring } instance [semiring R] : semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), .. hahn_series.non_assoc_semiring, .. hahn_series.non_unital_semiring } instance [non_unital_comm_semiring R] : non_unital_comm_semiring (hahn_series Γ R) := { mul_comm := λ x y, begin ext, simp_rw [mul_coeff, mul_comm], refine sum_bij (λ a ha, a.swap) (λ a ha, _) (λ a ha, rfl) (λ _ _ _ _, prod.swap_inj.1) (λ a ha, ⟨a.swap, _, a.swap_swap.symm⟩); rwa swap_mem_add_antidiagonal, end, .. hahn_series.non_unital_semiring } instance [comm_semiring R] : comm_semiring (hahn_series Γ R) := { .. hahn_series.non_unital_comm_semiring, .. hahn_series.semiring } instance [non_unital_non_assoc_ring R] : non_unital_non_assoc_ring (hahn_series Γ R) := { .. hahn_series.non_unital_non_assoc_semiring, .. hahn_series.add_group } instance [non_unital_ring R] : non_unital_ring (hahn_series Γ R) := { .. hahn_series.non_unital_non_assoc_ring, .. hahn_series.non_unital_semiring } instance [non_assoc_ring R] : non_assoc_ring (hahn_series Γ R) := { .. hahn_series.non_unital_non_assoc_ring, .. hahn_series.non_assoc_semiring } instance [ring R] : ring (hahn_series Γ R) := { .. hahn_series.semiring, .. hahn_series.add_comm_group } instance [non_unital_comm_ring R] : non_unital_comm_ring (hahn_series Γ R) := { .. hahn_series.non_unital_comm_semiring, .. hahn_series.non_unital_ring } instance [comm_ring R] : comm_ring (hahn_series Γ R) := { .. hahn_series.comm_semiring, .. hahn_series.ring } instance {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [non_unital_non_assoc_semiring R] [no_zero_divisors R] : no_zero_divisors (hahn_series Γ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y xy, begin by_cases hx : x = 0, { left, exact hx }, right, contrapose! xy, rw [hahn_series.ext_iff, function.funext_iff, not_forall], refine ⟨x.order + y.order, _⟩, rw [mul_coeff_order_add_order x y, zero_coeff, mul_eq_zero], simp [coeff_order_ne_zero, hx, xy], end } instance {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [ring R] [is_domain R] : is_domain (hahn_series Γ R) := no_zero_divisors.to_is_domain _ @[simp] lemma order_mul {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [non_unital_non_assoc_semiring R] [no_zero_divisors R] {x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) : (x * y).order = x.order + y.order := begin apply le_antisymm, { apply order_le_of_coeff_ne_zero, rw [mul_coeff_order_add_order x y], exact mul_ne_zero (coeff_order_ne_zero hx) (coeff_order_ne_zero hy) }, { rw [order_of_ne hx, order_of_ne hy, order_of_ne (mul_ne_zero hx hy), ← set.is_wf.min_add], exact set.is_wf.min_le_min_of_subset (support_mul_subset_add_support) }, end @[simp] lemma order_pow {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [semiring R] [no_zero_divisors R] (x : hahn_series Γ R) (n : ℕ) : (x ^ n).order = n • x.order := begin induction n with h IH, { simp }, rcases eq_or_ne x 0 with rfl|hx, { simp }, rw [pow_succ', order_mul (pow_ne_zero _ hx) hx, succ_nsmul', IH] end section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring R] @[simp] lemma single_mul_single {a b : Γ} {r s : R} : single a r * single b s = single (a + b) (r * s) := begin ext x, by_cases h : x = a + b, { rw [h, mul_single_coeff_add], simp }, { rw [single_coeff_of_ne h, mul_coeff, sum_eq_zero], simp_rw mem_add_antidiagonal, rintro ⟨y, z⟩ ⟨hy, hz, rfl⟩, rw [eq_of_mem_support_single hy, eq_of_mem_support_single hz] at h, exact (h rfl).elim } end end non_unital_non_assoc_semiring section non_assoc_semiring variables [non_assoc_semiring R] /-- `C a` is the constant Hahn Series `a`. `C` is provided as a ring homomorphism. -/ @[simps] def C : R →+* (hahn_series Γ R) := { to_fun := single 0, map_zero' := single_eq_zero, map_one' := rfl, map_add' := λ x y, by { ext a, by_cases h : a = 0; simp [h] }, map_mul' := λ x y, by rw [single_mul_single, zero_add] } @[simp] lemma C_zero : C (0 : R) = (0 : hahn_series Γ R) := C.map_zero @[simp] lemma C_one : C (1 : R) = (1 : hahn_series Γ R) := C.map_one lemma C_injective : function.injective (C : R → hahn_series Γ R) := begin intros r s rs, rw [ext_iff, function.funext_iff] at rs, have h := rs 0, rwa [C_apply, single_coeff_same, C_apply, single_coeff_same] at h, end lemma C_ne_zero {r : R} (h : r ≠ 0) : (C r : hahn_series Γ R) ≠ 0 := begin contrapose! h, rw ← C_zero at h, exact C_injective h, end lemma order_C {r : R} : order (C r : hahn_series Γ R) = 0 := begin by_cases h : r = 0, { rw [h, C_zero, order_zero] }, { exact order_single h } end end non_assoc_semiring section semiring variables [semiring R] lemma C_mul_eq_smul {r : R} {x : hahn_series Γ R} : C r * x = r • x := single_zero_mul_eq_smul end semiring section domain variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ'] lemma emb_domain_mul [non_unital_non_assoc_semiring R] (f : Γ ↪o Γ') (hf : ∀ x y, f (x + y) = f x + f y) (x y : hahn_series Γ R) : emb_domain f (x * y) = emb_domain f x * emb_domain f y := begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨g, rfl⟩ := hg, simp only [mul_coeff, emb_domain_coeff], transitivity ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support g).map (function.embedding.prod_map f.to_embedding f.to_embedding), (emb_domain f x).coeff (ij.1) * (emb_domain f y).coeff (ij.2), { simp }, apply sum_subset, { rintro ⟨i, j⟩ hij, simp only [exists_prop, mem_map, prod.mk.inj_iff, mem_add_antidiagonal, function.embedding.coe_prod_map, mem_support, prod.exists] at hij, obtain ⟨i, j, ⟨hx, hy, rfl⟩, rfl, rfl⟩ := hij, simp [hx, hy, hf], }, { rintro ⟨_, _⟩ h1 h2, contrapose! h2, obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).1, obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).2, simp only [exists_prop, mem_map, prod.mk.inj_iff, mem_add_antidiagonal, function.embedding.coe_prod_map, mem_support, prod.exists], simp only [mem_add_antidiagonal, emb_domain_coeff, mem_support, ←hf, order_embedding.eq_iff_eq] at h1, exact ⟨i, j, h1, rfl⟩ } }, { rw [emb_domain_notin_range hg, eq_comm], contrapose! hg, obtain ⟨_, _, hi, hj, rfl⟩ := support_mul_subset_add_support ((mem_support _ _).2 hg), obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset hi, obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset hj, refine ⟨i + j, hf i j⟩, } end lemma emb_domain_one [non_assoc_semiring R] (f : Γ ↪o Γ') (hf : f 0 = 0): emb_domain f (1 : hahn_series Γ R) = (1 : hahn_series Γ' R) := emb_domain_single.trans $ hf.symm ▸ rfl /-- Extending the domain of Hahn series is a ring homomorphism. -/ @[simps] def emb_domain_ring_hom [non_assoc_semiring R] (f : Γ →+ Γ') (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') : hahn_series Γ R →+* hahn_series Γ' R := { to_fun := emb_domain ⟨⟨f, hfi⟩, hf⟩, map_one' := emb_domain_one _ f.map_zero, map_mul' := emb_domain_mul _ f.map_add, map_zero' := emb_domain_zero, map_add' := emb_domain_add _} lemma emb_domain_ring_hom_C [non_assoc_semiring R] {f : Γ →+ Γ'} {hfi : function.injective f} {hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g'} {r : R} : emb_domain_ring_hom f hfi hf (C r) = C r := emb_domain_single.trans (by simp) end domain section algebra variables [comm_semiring R] {A : Type*} [semiring A] [algebra R A] instance : algebra R (hahn_series Γ A) := { to_ring_hom := C.comp (algebra_map R A), smul_def' := λ r x, by { ext, simp }, commutes' := λ r x, by { ext, simp only [smul_coeff, single_zero_mul_eq_smul, ring_hom.coe_comp, ring_hom.to_fun_eq_coe, C_apply, function.comp_app, algebra_map_smul, mul_single_zero_coeff], rw [← algebra.commutes, algebra.smul_def], }, } theorem C_eq_algebra_map : C = (algebra_map R (hahn_series Γ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (hahn_series Γ A) r = C (algebra_map R A r) := rfl instance [nontrivial Γ] [nontrivial R] : nontrivial (subalgebra R (hahn_series Γ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], obtain ⟨a, ha⟩ := exists_ne (0 : Γ), refine ⟨single a 1, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, function.funext_iff, not_forall], refine ⟨a, _⟩, rw [single_coeff_same, algebra_map_apply, C_apply, single_coeff_of_ne ha], exact zero_ne_one end⟩⟩ section domain variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ'] /-- Extending the domain of Hahn series is an algebra homomorphism. -/ @[simps] def emb_domain_alg_hom (f : Γ →+ Γ') (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') : hahn_series Γ A →ₐ[R] hahn_series Γ' A := { commutes' := λ r, emb_domain_ring_hom_C, .. emb_domain_ring_hom f hfi hf } end domain end algebra end multiplication section semiring variables [semiring R] /-- The ring `hahn_series ℕ R` is isomorphic to `power_series R`. -/ @[simps] def to_power_series : hahn_series ℕ R ≃+* power_series R := { to_fun := λ f, power_series.mk f.coeff, inv_fun := λ f, ⟨λ n, power_series.coeff R n f, (nat.lt_wf.is_wf _).is_pwo⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [power_series.coeff_mul, power_series.coeff_mk, mul_coeff, is_pwo_support], classical, refine sum_filter_ne_zero.symm.trans ((sum_congr _ $ λ _ _, rfl).trans sum_filter_ne_zero), ext m, simp only [nat.mem_antidiagonal, mem_add_antidiagonal, and.congr_left_iff, mem_filter, mem_support], rintro h, rw [and_iff_right (left_ne_zero_of_mul h), and_iff_right (right_ne_zero_of_mul h)], end } lemma coeff_to_power_series {f : hahn_series ℕ R} {n : ℕ} : power_series.coeff R n f.to_power_series = f.coeff n := power_series.coeff_mk _ _ lemma coeff_to_power_series_symm {f : power_series R} {n : ℕ} : (hahn_series.to_power_series.symm f).coeff n = power_series.coeff R n f := rfl variables (Γ R) [strict_ordered_semiring Γ] /-- Casts a power series as a Hahn series with coefficients from an `strict_ordered_semiring`. -/ def of_power_series : (power_series R) →+* hahn_series Γ R := (hahn_series.emb_domain_ring_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective (λ _ _, nat.cast_le)).comp (ring_equiv.to_ring_hom to_power_series.symm) variables {Γ} {R} lemma of_power_series_injective : function.injective (of_power_series Γ R) := emb_domain_injective.comp to_power_series.symm.injective @[simp] lemma of_power_series_apply (x : power_series R) : of_power_series Γ R x = hahn_series.emb_domain ⟨⟨(coe : ℕ → Γ), nat.strict_mono_cast.injective⟩, λ a b, begin simp only [function.embedding.coe_fn_mk], exact nat.cast_le, end⟩ (to_power_series.symm x) := rfl lemma of_power_series_apply_coeff (x : power_series R) (n : ℕ) : (of_power_series Γ R x).coeff n = power_series.coeff R n x := by simp @[simp] lemma of_power_series_C (r : R) : of_power_series Γ R (power_series.C R r) = hahn_series.C r := begin ext n, simp only [C, single_coeff, of_power_series_apply, ring_hom.coe_mk], split_ifs with hn hn, { subst hn, convert @emb_domain_coeff _ _ _ _ _ _ _ _ 0; simp }, { rw emb_domain_notin_image_support, simp only [not_exists, set.mem_image, to_power_series_symm_apply_coeff, mem_support, power_series.coeff_C], intro, simp [ne.symm hn] {contextual := tt} } end @[simp] lemma of_power_series_X : of_power_series Γ R power_series.X = single 1 1 := begin ext n, simp only [single_coeff, of_power_series_apply, ring_hom.coe_mk], split_ifs with hn hn, { rw hn, convert @emb_domain_coeff _ _ _ _ _ _ _ _ 1; simp }, { rw emb_domain_notin_image_support, simp only [not_exists, set.mem_image, to_power_series_symm_apply_coeff, mem_support, power_series.coeff_X], intro, simp [ne.symm hn] {contextual := tt} } end @[simp] lemma of_power_series_X_pow {R} [comm_semiring R] (n : ℕ) : of_power_series Γ R (power_series.X ^ n) = single (n : Γ) 1 := begin rw ring_hom.map_pow, induction n with n ih, { simp, refl }, rw [pow_succ, ih, of_power_series_X, mul_comm, single_mul_single, one_mul, nat.cast_succ] end -- Lemmas about converting hahn_series over fintype to and from mv_power_series /-- The ring `hahn_series (σ →₀ ℕ) R` is isomorphic to `mv_power_series σ R` for a `fintype` `σ`. We take the index set of the hahn series to be `finsupp` rather than `pi`, even though we assume `fintype σ` as this is more natural for alignment with `mv_power_series`. After importing `algebra.order.pi` the ring `hahn_series (σ → ℕ) R` could be constructed instead. -/ @[simps] def to_mv_power_series {σ : Type*} [fintype σ] : hahn_series (σ →₀ ℕ) R ≃+* mv_power_series σ R := { to_fun := λ f, f.coeff, inv_fun := λ f, ⟨(f : (σ →₀ ℕ) → R), finsupp.is_pwo _⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [mv_power_series.coeff_mul], classical, change (f * g).coeff n = _, simp_rw [mul_coeff], refine sum_filter_ne_zero.symm.trans ((sum_congr _ (λ _ _, rfl)).trans sum_filter_ne_zero), ext m, simp only [and.congr_left_iff, mem_add_antidiagonal, mem_filter, mem_support, finsupp.mem_antidiagonal], rintro h, rw [and_iff_right (left_ne_zero_of_mul h), and_iff_right (right_ne_zero_of_mul h)], end } variables {σ : Type*} [fintype σ] lemma coeff_to_mv_power_series {f : hahn_series (σ →₀ ℕ) R} {n : σ →₀ ℕ} : mv_power_series.coeff R n f.to_mv_power_series = f.coeff n := rfl lemma coeff_to_mv_power_series_symm {f : mv_power_series σ R} {n : σ →₀ ℕ} : (hahn_series.to_mv_power_series.symm f).coeff n = mv_power_series.coeff R n f := rfl end semiring section algebra variables (R) [comm_semiring R] {A : Type*} [semiring A] [algebra R A] /-- The `R`-algebra `hahn_series ℕ A` is isomorphic to `power_series A`. -/ @[simps] def to_power_series_alg : (hahn_series ℕ A) ≃ₐ[R] power_series A := { commutes' := λ r, begin ext n, simp only [algebra_map_apply, power_series.algebra_map_apply, ring_equiv.to_fun_eq_coe, C_apply, coeff_to_power_series], cases n, { simp only [power_series.coeff_zero_eq_constant_coeff, single_coeff_same], refl }, { simp only [n.succ_ne_zero, ne.def, not_false_iff, single_coeff_of_ne], rw [power_series.coeff_C, if_neg n.succ_ne_zero] } end, .. to_power_series } variables (Γ R) [strict_ordered_semiring Γ] /-- Casting a power series as a Hahn series with coefficients from an `strict_ordered_semiring` is an algebra homomorphism. -/ @[simps] def of_power_series_alg : (power_series A) →ₐ[R] hahn_series Γ A := (hahn_series.emb_domain_alg_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective (λ _ _, nat.cast_le)).comp (alg_equiv.to_alg_hom (to_power_series_alg R).symm) instance power_series_algebra {S : Type*} [comm_semiring S] [algebra S (power_series R)] : algebra S (hahn_series Γ R) := ring_hom.to_algebra $ (of_power_series Γ R).comp (algebra_map S (power_series R)) variables {R} {S : Type*} [comm_semiring S] [algebra S (power_series R)] lemma algebra_map_apply' (x : S) : algebra_map S (hahn_series Γ R) x = of_power_series Γ R (algebra_map S (power_series R) x) := rfl @[simp] lemma _root_.polynomial.algebra_map_hahn_series_apply (f : R[X]) : algebra_map R[X] (hahn_series Γ R) f = of_power_series Γ R f := rfl lemma _root_.polynomial.algebra_map_hahn_series_injective : function.injective (algebra_map R[X] (hahn_series Γ R)) := of_power_series_injective.comp (polynomial.coe_injective R) end algebra section valuation variables (Γ R) [linear_ordered_cancel_add_comm_monoid Γ] [ring R] [is_domain R] /-- The additive valuation on `hahn_series Γ R`, returning the smallest index at which a Hahn Series has a nonzero coefficient, or `⊤` for the 0 series. -/ def add_val : add_valuation (hahn_series Γ R) (with_top Γ) := add_valuation.of (λ x, if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order) (if_pos rfl) ((if_neg one_ne_zero).trans (by simp [order_of_ne])) (λ x y, begin by_cases hx : x = 0, { by_cases hy : y = 0; { simp [hx, hy] } }, { by_cases hy : y = 0, { simp [hx, hy] }, { simp only [hx, hy, support_nonempty_iff, if_neg, not_false_iff, is_wf_support], by_cases hxy : x + y = 0, { simp [hxy] }, rw [if_neg hxy, ← with_top.coe_min, with_top.coe_le_coe], exact min_order_le_order_add hxy } }, end) (λ x y, begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_top.coe_add, with_top.coe_eq_coe, order_mul hx hy], end) variables {Γ} {R} lemma add_val_apply {x : hahn_series Γ R} : add_val Γ R x = if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order := add_valuation.of_apply _ @[simp] lemma add_val_apply_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : add_val Γ R x = x.order := if_neg hx lemma add_val_le_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : add_val Γ R x ≤ g := begin rw [add_val_apply_of_ne (ne_zero_of_coeff_ne_zero h), with_top.coe_le_coe], exact order_le_of_coeff_ne_zero h end end valuation lemma is_pwo_Union_support_powers [linear_ordered_cancel_add_comm_monoid Γ] [ring R] [is_domain R] {x : hahn_series Γ R} (hx : 0 < add_val Γ R x) : (⋃ n : ℕ, (x ^ n).support).is_pwo := begin apply (x.is_wf_support.is_pwo.add_submonoid_closure (λ g hg, _)).mono _, { exact with_top.coe_le_coe.1 (le_trans (le_of_lt hx) (add_val_le_of_coeff_ne_zero hg)) }, refine set.Union_subset (λ n, _), induction n with n ih; intros g hn, { simp only [exists_prop, and_true, set.mem_singleton_iff, set.set_of_eq_eq_singleton, mem_support, ite_eq_right_iff, ne.def, not_false_iff, one_ne_zero, pow_zero, not_forall, one_coeff] at hn, rw [hn, set_like.mem_coe], exact add_submonoid.zero_mem _ }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn, exact set_like.mem_coe.2 (add_submonoid.add_mem _ (add_submonoid.subset_closure hi) (ih hj)) } end section variables (Γ) (R) [partial_order Γ] [add_comm_monoid R] /-- An infinite family of Hahn series which has a formal coefficient-wise sum. The requirements for this are that the union of the supports of the series is well-founded, and that only finitely many series are nonzero at any given coefficient. -/ structure summable_family (α : Type*) := (to_fun : α → hahn_series Γ R) (is_pwo_Union_support' : set.is_pwo (⋃ (a : α), (to_fun a).support)) (finite_co_support' : ∀ (g : Γ), ({a | (to_fun a).coeff g ≠ 0}).finite) end namespace summable_family section add_comm_monoid variables [partial_order Γ] [add_comm_monoid R] {α : Type*} instance : has_coe_to_fun (summable_family Γ R α) (λ _, α → hahn_series Γ R):= ⟨to_fun⟩ lemma is_pwo_Union_support (s : summable_family Γ R α) : set.is_pwo (⋃ (a : α), (s a).support) := s.is_pwo_Union_support' lemma finite_co_support (s : summable_family Γ R α) (g : Γ) : (function.support (λ a, (s a).coeff g)).finite := s.finite_co_support' g lemma coe_injective : @function.injective (summable_family Γ R α) (α → hahn_series Γ R) coe_fn | ⟨f1, hU1, hf1⟩ ⟨f2, hU2, hf2⟩ h := begin change f1 = f2 at h, subst h, end @[ext] lemma ext {s t : summable_family Γ R α} (h : ∀ (a : α), s a = t a) : s = t := coe_injective $ funext h instance : has_add (summable_family Γ R α) := ⟨λ x y, { to_fun := x + y, is_pwo_Union_support' := (x.is_pwo_Union_support.union y.is_pwo_Union_support).mono (begin rw ← set.Union_union_distrib, exact set.Union_mono (λ a, support_add_subset) end), finite_co_support' := λ g, ((x.finite_co_support g).union (y.finite_co_support g)).subset begin intros a ha, change (x a).coeff g + (y a).coeff g ≠ 0 at ha, rw [set.mem_union, function.mem_support, function.mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero] end }⟩ instance : has_zero (summable_family Γ R α) := ⟨⟨0, by simp, by simp⟩⟩ instance : inhabited (summable_family Γ R α) := ⟨0⟩ @[simp] lemma coe_add {s t : summable_family Γ R α} : ⇑(s + t) = s + t := rfl lemma add_apply {s t : summable_family Γ R α} {a : α} : (s + t) a = s a + t a := rfl @[simp] lemma coe_zero : ((0 : summable_family Γ R α) : α → hahn_series Γ R) = 0 := rfl lemma zero_apply {a : α} : (0 : summable_family Γ R α) a = 0 := rfl instance : add_comm_monoid (summable_family Γ R α) := { add := (+), zero := 0, zero_add := λ s, by { ext, apply zero_add }, add_zero := λ s, by { ext, apply add_zero }, add_comm := λ s t, by { ext, apply add_comm }, add_assoc := λ r s t, by { ext, apply add_assoc } } /-- The infinite sum of a `summable_family` of Hahn series. -/ def hsum (s : summable_family Γ R α) : hahn_series Γ R := { coeff := λ g, ∑ᶠ i, (s i).coeff g, is_pwo_support' := s.is_pwo_Union_support.mono (λ g, begin contrapose, rw [set.mem_Union, not_exists, function.mem_support, not_not], simp_rw [mem_support, not_not], intro h, rw [finsum_congr h, finsum_zero], end) } @[simp] lemma hsum_coeff {s : summable_family Γ R α} {g : Γ} : s.hsum.coeff g = ∑ᶠ i, (s i).coeff g := rfl lemma support_hsum_subset {s : summable_family Γ R α} : s.hsum.support ⊆ ⋃ (a : α), (s a).support := λ g hg, begin rw [mem_support, hsum_coeff, finsum_eq_sum _ (s.finite_co_support _)] at hg, obtain ⟨a, h1, h2⟩ := exists_ne_zero_of_sum_ne_zero hg, rw [set.mem_Union], exact ⟨a, h2⟩, end @[simp] lemma hsum_add {s t : summable_family Γ R α} : (s + t).hsum = s.hsum + t.hsum := begin ext g, simp only [hsum_coeff, add_coeff, add_apply], exact finsum_add_distrib (s.finite_co_support _) (t.finite_co_support _) end end add_comm_monoid section add_comm_group variables [partial_order Γ] [add_comm_group R] {α : Type*} {s t : summable_family Γ R α} {a : α} instance : add_comm_group (summable_family Γ R α) := { neg := λ s, { to_fun := λ a, - s a, is_pwo_Union_support' := by { simp_rw [support_neg], exact s.is_pwo_Union_support' }, finite_co_support' := λ g, by { simp only [neg_coeff', pi.neg_apply, ne.def, neg_eq_zero], exact s.finite_co_support g } }, add_left_neg := λ a, by { ext, apply add_left_neg }, .. summable_family.add_comm_monoid } @[simp] lemma coe_neg : ⇑(-s) = - s := rfl lemma neg_apply : (-s) a = - (s a) := rfl @[simp] lemma coe_sub : ⇑(s - t) = s - t := rfl lemma sub_apply : (s - t) a = s a - t a := rfl end add_comm_group section semiring variables [ordered_cancel_add_comm_monoid Γ] [semiring R] {α : Type*} instance : has_smul (hahn_series Γ R) (summable_family Γ R α) := { smul := λ x s, { to_fun := λ a, x * (s a), is_pwo_Union_support' := begin apply (x.is_pwo_support.add s.is_pwo_Union_support).mono, refine set.subset.trans (set.Union_mono (λ a, support_mul_subset_add_support)) _, intro g, simp only [set.mem_Union, exists_imp_distrib], exact λ a ha, (set.add_subset_add (set.subset.refl _) (set.subset_Union _ a)) ha, end, finite_co_support' := λ g, begin refine ((add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g).finite_to_set.bUnion' (λ ij hij, _)).subset (λ a ha, _), { exact λ ij hij, function.support (λ a, (s a).coeff ij.2) }, { apply s.finite_co_support }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support ha, simp only [exists_prop, set.mem_Union, mem_add_antidiagonal, mul_coeff, mem_support, is_pwo_support, prod.exists], exact ⟨i, j, mem_coe.2 (mem_add_antidiagonal.2 ⟨hi, set.mem_Union.2 ⟨a, hj⟩, rfl⟩), hj⟩ } end } } @[simp] lemma smul_apply {x : hahn_series Γ R} {s : summable_family Γ R α} {a : α} : (x • s) a = x * (s a) := rfl instance : module (hahn_series Γ R) (summable_family Γ R α) := { smul := (•), smul_zero := λ x, ext (λ a, mul_zero _), zero_smul := λ x, ext (λ a, zero_mul _), one_smul := λ x, ext (λ a, one_mul _), add_smul := λ x y s, ext (λ a, add_mul _ _ _), smul_add := λ x s t, ext (λ a, mul_add _ _ _), mul_smul := λ x y s, ext (λ a, mul_assoc _ _ _) } @[simp] lemma hsum_smul {x : hahn_series Γ R} {s : summable_family Γ R α} : (x • s).hsum = x * s.hsum := begin ext g, simp only [mul_coeff, hsum_coeff, smul_apply], have h : ∀ i, (s i).support ⊆ ⋃ j, (s j).support := set.subset_Union _, refine (eq.trans (finsum_congr (λ a, _)) (finsum_sum_comm (add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g) (λ i ij, x.coeff (prod.fst ij) * (s i).coeff ij.snd) _)).trans _, { refine sum_subset (add_antidiagonal_mono_right (set.subset_Union _ a)) _, rintro ⟨i, j⟩ hU ha, rw mem_add_antidiagonal at *, rw [not_not.1 (λ con, ha ⟨hU.1, con, hU.2.2⟩), mul_zero] }, { rintro ⟨i, j⟩ hij, refine (s.finite_co_support j).subset _, simp_rw [function.support_subset_iff', function.mem_support, not_not], intros a ha, rw [ha, mul_zero] }, { refine (sum_congr rfl _).trans (sum_subset (add_antidiagonal_mono_right _) _).symm, { rintro ⟨i, j⟩ hij, rw mul_finsum, apply s.finite_co_support, }, { intros x hx, simp only [set.mem_Union, ne.def, mem_support], contrapose! hx, simp [hx] }, { rintro ⟨i, j⟩ hU ha, rw mem_add_antidiagonal at *, rw [← hsum_coeff, not_not.1 (λ con, ha ⟨hU.1, con, hU.2.2⟩), mul_zero] } } end /-- The summation of a `summable_family` as a `linear_map`. -/ @[simps] def lsum : (summable_family Γ R α) →ₗ[hahn_series Γ R] (hahn_series Γ R) := { to_fun := hsum, map_add' := λ _ _, hsum_add, map_smul' := λ _ _, hsum_smul } @[simp] lemma hsum_sub {R : Type*} [ring R] {s t : summable_family Γ R α} : (s - t).hsum = s.hsum - t.hsum := by rw [← lsum_apply, linear_map.map_sub, lsum_apply, lsum_apply] end semiring section of_finsupp variables [partial_order Γ] [add_comm_monoid R] {α : Type*} /-- A family with only finitely many nonzero elements is summable. -/ def of_finsupp (f : α →₀ (hahn_series Γ R)) : summable_family Γ R α := { to_fun := f, is_pwo_Union_support' := begin apply (f.support.is_pwo_bUnion.2 $ λ a ha, (f a).is_pwo_support).mono, refine set.Union_subset_iff.2 (λ a g hg, _), have haf : a ∈ f.support, { rw [finsupp.mem_support_iff, ← support_nonempty_iff], exact ⟨g, hg⟩ }, exact set.mem_bUnion haf hg end, finite_co_support' := λ g, begin refine f.support.finite_to_set.subset (λ a ha, _), simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def, function.mem_support], contrapose! ha, simp [ha] end } @[simp] lemma coe_of_finsupp {f : α →₀ (hahn_series Γ R)} : ⇑(summable_family.of_finsupp f) = f := rfl @[simp] lemma hsum_of_finsupp {f : α →₀ (hahn_series Γ R)} : (of_finsupp f).hsum = f.sum (λ a, id) := begin ext g, simp only [hsum_coeff, coe_of_finsupp, finsupp.sum, ne.def], simp_rw [← coeff.add_monoid_hom_apply, id.def], rw [add_monoid_hom.map_sum, finsum_eq_sum_of_support_subset], intros x h, simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def], contrapose! h, simp [h] end end of_finsupp section emb_domain variables [partial_order Γ] [add_comm_monoid R] {α β : Type*} /-- A summable family can be reindexed by an embedding without changing its sum. -/ def emb_domain (s : summable_family Γ R α) (f : α ↪ β) : summable_family Γ R β := { to_fun := λ b, if h : b ∈ set.range f then s (classical.some h) else 0, is_pwo_Union_support' := begin refine s.is_pwo_Union_support.mono (set.Union_subset (λ b g h, _)), by_cases hb : b ∈ set.range f, { rw dif_pos hb at h, exact set.mem_Union.2 ⟨classical.some hb, h⟩ }, { contrapose! h, simp [hb] } end, finite_co_support' := λ g, ((s.finite_co_support g).image f).subset begin intros b h, by_cases hb : b ∈ set.range f, { simp only [ne.def, set.mem_set_of_eq, dif_pos hb] at h, exact ⟨classical.some hb, h, classical.some_spec hb⟩ }, { contrapose! h, simp only [ne.def, set.mem_set_of_eq, dif_neg hb, not_not, zero_coeff] } end } variables (s : summable_family Γ R α) (f : α ↪ β) {a : α} {b : β} lemma emb_domain_apply : s.emb_domain f b = if h : b ∈ set.range f then s (classical.some h) else 0 := rfl @[simp] lemma emb_domain_image : s.emb_domain f (f a) = s a := begin rw [emb_domain_apply, dif_pos (set.mem_range_self a)], exact congr rfl (f.injective (classical.some_spec (set.mem_range_self a))) end @[simp] lemma emb_domain_notin_range (h : b ∉ set.range f) : s.emb_domain f b = 0 := by rw [emb_domain_apply, dif_neg h] @[simp] lemma hsum_emb_domain : (s.emb_domain f).hsum = s.hsum := begin ext g, simp only [hsum_coeff, emb_domain_apply, apply_dite hahn_series.coeff, dite_apply, zero_coeff], exact finsum_emb_domain f (λ a, (s a).coeff g) end end emb_domain section powers variables [linear_ordered_cancel_add_comm_monoid Γ] [comm_ring R] [is_domain R] /-- The powers of an element of positive valuation form a summable family. -/ def powers (x : hahn_series Γ R) (hx : 0 < add_val Γ R x) : summable_family Γ R ℕ := { to_fun := λ n, x ^ n, is_pwo_Union_support' := is_pwo_Union_support_powers hx, finite_co_support' := λ g, begin have hpwo := (is_pwo_Union_support_powers hx), by_cases hg : g ∈ ⋃ n : ℕ, {g | (x ^ n).coeff g ≠ 0 }, swap, { exact set.finite_empty.subset (λ n hn, hg (set.mem_Union.2 ⟨n, hn⟩)) }, apply hpwo.is_wf.induction hg, intros y ys hy, refine ((((add_antidiagonal x.is_pwo_support hpwo y).finite_to_set.bUnion (λ ij hij, hy ij.snd _ _)).image nat.succ).union (set.finite_singleton 0)).subset _, { exact (mem_add_antidiagonal.1 (mem_coe.1 hij)).2.1 }, { obtain ⟨hi, hj, rfl⟩ := mem_add_antidiagonal.1 (mem_coe.1 hij), rw [← zero_add ij.snd, ← add_assoc, add_zero], exact add_lt_add_right (with_top.coe_lt_coe.1 (lt_of_lt_of_le hx (add_val_le_of_coeff_ne_zero hi))) _, }, { rintro (_ | n) hn, { exact set.mem_union_right _ (set.mem_singleton 0) }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn, refine set.mem_union_left _ ⟨n, set.mem_Union.2 ⟨⟨i, j⟩, set.mem_Union.2 ⟨_, hj⟩⟩, rfl⟩, simp only [and_true, set.mem_Union, mem_add_antidiagonal, mem_coe, eq_self_iff_true, ne.def, mem_support, set.mem_set_of_eq], exact ⟨hi, n, hj⟩ } } end } variables {x : hahn_series Γ R} (hx : 0 < add_val Γ R x) @[simp] lemma coe_powers : ⇑(powers x hx) = pow x := rfl lemma emb_domain_succ_smul_powers : (x • powers x hx).emb_domain ⟨nat.succ, nat.succ_injective⟩ = powers x hx - of_finsupp (finsupp.single 0 1) := begin apply summable_family.ext (λ n, _), cases n, { rw [emb_domain_notin_range, sub_apply, coe_powers, pow_zero, coe_of_finsupp, finsupp.single_eq_same, sub_self], rw [set.mem_range, not_exists], exact nat.succ_ne_zero }, { refine eq.trans (emb_domain_image _ ⟨nat.succ, nat.succ_injective⟩) _, simp only [pow_succ, coe_powers, coe_sub, smul_apply, coe_of_finsupp, pi.sub_apply], rw [finsupp.single_eq_of_ne (n.succ_ne_zero).symm, sub_zero] } end lemma one_sub_self_mul_hsum_powers : (1 - x) * (powers x hx).hsum = 1 := begin rw [← hsum_smul, sub_smul, one_smul, hsum_sub, ← hsum_emb_domain (x • powers x hx) ⟨nat.succ, nat.succ_injective⟩, emb_domain_succ_smul_powers], simp, end end powers end summable_family section inversion variables [linear_ordered_add_comm_group Γ] section is_domain variables [comm_ring R] [is_domain R] lemma unit_aux (x : hahn_series Γ R) {r : R} (hr : r * x.coeff x.order = 1) : 0 < add_val Γ R (1 - C r * (single (- x.order) 1) * x) := begin have h10 : (1 : R) ≠ 0 := one_ne_zero, have x0 : x ≠ 0 := ne_zero_of_coeff_ne_zero (right_ne_zero_of_mul_eq_one hr), refine lt_of_le_of_ne ((add_val Γ R).map_le_sub (ge_of_eq (add_val Γ R).map_one) _) _, { simp only [add_valuation.map_mul], rw [add_val_apply_of_ne x0, add_val_apply_of_ne (single_ne_zero h10), add_val_apply_of_ne _, order_C, order_single h10, with_top.coe_zero, zero_add, ← with_top.coe_add, neg_add_self, with_top.coe_zero], { exact le_refl 0 }, { exact C_ne_zero (left_ne_zero_of_mul_eq_one hr) } }, { rw [add_val_apply, ← with_top.coe_zero], split_ifs, { apply with_top.coe_ne_top }, rw [ne.def, with_top.coe_eq_coe], intro con, apply coeff_order_ne_zero h, rw [← con, mul_assoc, sub_coeff, one_coeff, if_pos rfl, C_mul_eq_smul, smul_coeff, smul_eq_mul, ← add_neg_self x.order, single_mul_coeff_add, one_mul, hr, sub_self] } end lemma is_unit_iff {x : hahn_series Γ R} : is_unit x ↔ is_unit (x.coeff x.order) := begin split, { rintro ⟨⟨u, i, ui, iu⟩, rfl⟩, refine is_unit_of_mul_eq_one (u.coeff u.order) (i.coeff i.order) ((mul_coeff_order_add_order u i).symm.trans _), rw [ui, one_coeff, if_pos], rw [← order_mul (left_ne_zero_of_mul_eq_one ui) (right_ne_zero_of_mul_eq_one ui), ui, order_one] }, { rintro ⟨⟨u, i, ui, iu⟩, h⟩, rw [units.coe_mk] at h, rw h at iu, have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x iu), rw [sub_sub_cancel] at h, exact is_unit_of_mul_is_unit_right (is_unit_of_mul_eq_one _ _ h) }, end end is_domain instance [field R] : field (hahn_series Γ R) := { inv := λ x, if x0 : x = 0 then 0 else (C (x.coeff x.order)⁻¹ * (single (-x.order)) 1 * (summable_family.powers _ (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0)))).hsum), inv_zero := dif_pos rfl, mul_inv_cancel := λ x x0, begin refine (congr rfl (dif_neg x0)).trans _, have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0))), rw [sub_sub_cancel] at h, rw [← mul_assoc, mul_comm x, h], end, .. hahn_series.is_domain, .. hahn_series.comm_ring } end inversion end hahn_series
6d60ce21f9fcf1261c891b3dd0718468bfdd5c4e
367134ba5a65885e863bdc4507601606690974c1
/src/topology/metric_space/emetric_space.lean
88ee7901fff0d4796e49b5919ab99ca1f0207dad
[ "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
46,346
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import data.finset.intervals import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence import topology.paracompact import set_theory.ordinal /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ℝ≥0∞) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for emetric spaces -/ theorem uniform_continuous_on_iff [emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b}, a ∈ s → b ∈ s → edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem ball_prod_same [emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in emetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- An `emetric_space` is always a paracompact space. Formalization is based on [MR0236876]. -/ @[priority 100] -- See note [lower instance priority] instance : paracompact_space α := begin classical, /- We start with trivial observations about `1 / 2 ^ k`. Here and below we use `1 / 2 ^ k` in the comments and `2⁻¹ ^ k` in the code. -/ have pow_pos : ∀ k : ℕ, (0 : ℝ≥0∞) < 2⁻¹ ^ k, from λ k, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _, have hpow_le : ∀ {m n : ℕ}, m ≤ n → (2⁻¹ : ℝ≥0∞) ^ n ≤ 2⁻¹ ^ m, from λ m n h, ennreal.pow_le_pow_of_le_one (ennreal.inv_le_one.2 ennreal.one_lt_two.le) h, have h2pow : ∀ n : ℕ, 2 * (2⁻¹ : ℝ≥0∞) ^ (n + 1) = 2⁻¹ ^ n, by { intro n, simp [pow_succ, ← mul_assoc, ennreal.mul_inv_cancel] }, -- Consider an open covering `S : set (set α)` refine ⟨λ ι s ho hcov, _⟩, simp only [Union_eq_univ_iff] at hcov, -- choose a well founded order on `S` letI : linear_order ι := linear_order_of_STO' well_ordering_rel, have wf : well_founded ((<) : ι → ι → Prop) := @is_well_order.wf ι well_ordering_rel _, -- Let `ind x` be the minimal index `s : S` such that `x ∈ s`. set ind : α → ι := λ x, wf.min {i : ι | x ∈ s i} (hcov x), have mem_ind : ∀ x, x ∈ s (ind x), from λ x, wf.min_mem _ (hcov x), have nmem_of_lt_ind : ∀ {x i}, i < (ind x) → x ∉ s i, from λ x i hlt hxi, wf.not_lt_min _ (hcov x) hxi hlt, /- The refinement `D : ℕ → ι → set α` is defined recursively. For each `n` and `i`, `D n i` is the union of balls `ball x (1 / 2 ^ n)` over all points `x` such that * `ind x = i`; * `x` does not belong to any `D m j`, `m < n`; * `ball x (3 / 2 ^ n) ⊆ s i`; We define this sequence using `nat.strong_rec_on'`, then restate it as `Dn` and `memD`. -/ set D : ℕ → ι → set α := λ n, nat.strong_rec_on' n (λ n D' i, ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D' m ‹_› j), ball x (2⁻¹ ^ n)), have Dn : ∀ n i, D n i = ⋃ (x : α) (hxs : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), ball x (2⁻¹ ^ n), from λ n s, by { simp only [D], rw nat.strong_rec_on_beta' }, have memD : ∀ {n i y}, y ∈ D n i ↔ ∃ x (hi : ind x = i) (hb : ball x (3 * 2⁻¹ ^ n) ⊆ s i) (hlt : ∀ (m < n) (j : ι), x ∉ D m j), edist y x < 2⁻¹ ^ n, { intros n i y, rw [Dn n i], simp only [mem_Union, mem_ball] }, -- The sets `D n i` cover the whole space. Indeed, for each `x` we can choose `n` such that -- `ball x (3 / 2 ^ n) ⊆ s (ind x)`, then either `x ∈ D n i`, or `x ∈ D m i` for some `m < n`. have Dcov : ∀ x, ∃ n i, x ∈ D n i, { intro x, obtain ⟨n, hn⟩ : ∃ n : ℕ, ball x (3 * 2⁻¹ ^ n) ⊆ s (ind x), { -- This proof takes 5 lines because we can't import `specific_limits` here rcases is_open_iff.1 (ho $ ind x) x (mem_ind x) with ⟨ε, ε0, hε⟩, have : 0 < ε / 3 := ennreal.div_pos_iff.2 ⟨ε0.lt.ne', ennreal.coe_ne_top⟩, rcases ennreal.exists_inv_two_pow_lt this.ne' with ⟨n, hn⟩, refine ⟨n, subset.trans (ball_subset_ball _) hε⟩, simpa only [div_eq_mul_inv, mul_comm] using (ennreal.mul_lt_of_lt_div hn).le }, by_contra h, push_neg at h, apply h n (ind x), exact memD.2 ⟨x, rfl, hn, λ _ _ _, h _ _, mem_ball_self (pow_pos _)⟩ }, -- Each `D n i` is a union of open balls, hence it is an open set have Dopen : ∀ n i, is_open (D n i), { intros n i, rw Dn, iterate 4 { refine is_open_Union (λ _, _) }, exact is_open_ball }, -- the covering `D n i` is a refinement of the original covering: `D n i ⊆ s i` have HDS : ∀ n i, D n i ⊆ s i, { intros n s x, rw memD, rintro ⟨y, rfl, hsub, -, hyx⟩, refine hsub (lt_of_lt_of_le hyx _), calc 2⁻¹ ^ n = 1 * 2⁻¹ ^ n : (one_mul _).symm ... ≤ 3 * 2⁻¹ ^ n : ennreal.mul_le_mul _ le_rfl, -- TODO: use `norm_num` have : ((1 : ℕ) : ℝ≥0∞) ≤ (3 : ℕ), from ennreal.coe_nat_le_coe_nat.2 (by norm_num1), exact_mod_cast this }, -- Let us show the rest of the properties. Since the definition expects a family indexed -- by a single parameter, we use `ℕ × ι` as the domain. refine ⟨ℕ × ι, λ ni, D ni.1 ni.2, λ _, Dopen _ _, _, _, λ ni, ⟨ni.2, HDS _ _⟩⟩, -- The sets `D n i` cover the whole space as we proved earlier { refine Union_eq_univ_iff.2 (λ x, _), rcases Dcov x with ⟨n, i, h⟩, exact ⟨⟨n, i⟩, h⟩ }, { /- Let us prove that the covering `D n i` is locally finite. Take a point `x` and choose `n`, `i` so that `x ∈ D n i`. Since `D n i` is an open set, we can choose `k` so that `B = ball x (1 / 2 ^ (n + k + 1)) ⊆ D n i`. -/ intro x, rcases Dcov x with ⟨n, i, hn⟩, have : D n i ∈ 𝓝 x, from mem_nhds_sets (Dopen _ _) hn, rcases (nhds_basis_uniformity uniformity_basis_edist_inv_two_pow).mem_iff.1 this with ⟨k, -, hsub : ball x (2⁻¹ ^ k) ⊆ D n i⟩, set B := ball x (2⁻¹ ^ (n + k + 1)), refine ⟨B, ball_mem_nhds _ (pow_pos _), _⟩, -- The sets `D m i`, `m > n + k`, are disjoint with `B` have Hgt : ∀ (m ≥ n + k + 1) (i : ι), disjoint (D m i) B, { rintros m hm i y ⟨hym, hyx⟩, rcases memD.1 hym with ⟨z, rfl, hzi, H, hz⟩, have : z ∉ ball x (2⁻¹ ^ k), from λ hz, H n (by linarith) i (hsub hz), apply this, calc edist z x ≤ edist y z + edist y x : edist_triangle_left _ _ _ ... < (2⁻¹ ^ m) + (2⁻¹ ^ (n + k + 1)) : ennreal.add_lt_add hz hyx ... ≤ (2⁻¹ ^ (k + 1)) + (2⁻¹ ^ (k + 1)) : add_le_add (hpow_le $ by linarith) (hpow_le $ by linarith) ... = (2⁻¹ ^ k) : by rw [← two_mul, h2pow] }, -- For each `m ≤ n + k` there is at most one `j` such that `D m j ∩ B` is nonempty. have Hle : ∀ m ≤ n + k, set.subsingleton {j | (D m j ∩ B).nonempty}, { rintros m hm j₁ ⟨y, hyD, hyB⟩ j₂ ⟨z, hzD, hzB⟩, by_contra h, wlog h : j₁ < j₂ := ne.lt_or_lt h using [j₁ j₂ y z, j₂ j₁ z y], rcases memD.1 hyD with ⟨y', rfl, hsuby, -, hdisty⟩, rcases memD.1 hzD with ⟨z', rfl, -, -, hdistz⟩, suffices : edist z' y' < 3 * 2⁻¹ ^ m, from nmem_of_lt_ind h (hsuby this), calc edist z' y' ≤ edist z' x + edist x y' : edist_triangle _ _ _ ... ≤ (edist z z' + edist z x) + (edist y x + edist y y') : add_le_add (edist_triangle_left _ _ _) (edist_triangle_left _ _ _) ... < (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) + (2⁻¹ ^ (n + k + 1) + 2⁻¹ ^ m) : by apply_rules [ennreal.add_lt_add] ... = 2 * (2⁻¹ ^ m + 2⁻¹ ^ (n + k + 1)) : by simp only [two_mul, add_comm] ... ≤ 2 * (2⁻¹ ^ m + 2⁻¹ ^ (m + 1)) : ennreal.mul_le_mul le_rfl $ add_le_add le_rfl $ hpow_le (add_le_add hm le_rfl) ... = 3 * 2⁻¹ ^ m : by rw [mul_add, h2pow, bit1, add_mul, one_mul] }, -- Finally, we glue `Hgt` and `Hle` have : (⋃ (m ≤ n + k) (i ∈ {i : ι | (D m i ∩ B).nonempty}), {(m, i)}).finite, from (finite_le_nat _).bUnion (λ i hi, (Hle i hi).finite.bUnion (λ _ _, finite_singleton _)), refine this.subset (λ I hI, _), simp only [mem_Union], refine ⟨I.1, _, I.2, hI, prod.mk.eta.symm⟩, exact not_lt.1 (λ hlt, Hgt I.1 hlt I.2 hI.some_spec) } end @[priority 100] -- see Note [lower instance priority] instance normal_of_emetric : normal_space α := normal_of_paracompact_t2 /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ℝ≥0∞), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ℝ≥0∞), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, finite.countable], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ℝ≥0∞) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : hs.is_closed.closure_eq, exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := uniform_space.second_countable_of_separable uniformity_has_countable_basis end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [pos_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
3f190ff30ae2c615d1b2335f5876cd197951bd20
80746c6dba6a866de5431094bf9f8f841b043d77
/src/category_theory/isomorphism.lean
052399b15d2160f8b6d1da77c32c256a04ceb369
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
6,182
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.functor universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y Z : C} namespace iso @[simp] lemma hom_inv_id_assoc (α : X ≅ Y) (f : X ⟶ Z) : α.hom ≫ α.inv ≫ f = f := by rw [←category.assoc, α.hom_inv_id, category.id_comp] @[simp] lemma inv_hom_id_assoc (α : X ≅ Y) (f : Y ⟶ Z) : α.inv ≫ α.hom ≫ f = f := by rw [←category.assoc, α.inv_hom_id, category.id_comp] @[extensionality] lemma ext (α β : X ≅ Y) (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[refl] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } @[simp] lemma refl_hom (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl @[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).hom = α.hom ≫ β.hom := rfl @[simp] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl @[simp] lemma refl_symm (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm end iso /-- `is_iso` typeclass expressing that a morphism is invertible. This contains the data of the inverse, but is a subsingleton type. -/ class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id' : f ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ f = 𝟙 Y . obviously) def inv (f : X ⟶ Y) [is_iso f] := is_iso.inv f namespace is_iso @[simp] def hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ category_theory.inv f = 𝟙 X := is_iso.hom_inv_id' f @[simp] def inv_hom_id (f : X ⟶ Y) [is_iso f] : category_theory.inv f ≫ f = 𝟙 Y := is_iso.inv_hom_id' f instance (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X } instance of_iso (f : X ≅ Y) : is_iso f.hom := { inv := f.inv } instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv := { inv := f.hom } end is_iso def as_iso (f : X ⟶ Y) [is_iso f] : X ≅ Y := { hom := f, inv := inv f } @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl instance (f : X ⟶ Y) : subsingleton (is_iso f) := ⟨λ a b, suffices a.inv = b.inv, by cases a; cases b; congr; exact this, show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv, by congr' 1; ext; refl⟩ namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [𝒟 : category.{v₂} D] include 𝒟 def on_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma on_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.on_iso i).hom = F.map i.hom := rfl @[simp] lemma on_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.on_iso i).inv = F.map i.inv := rfl instance (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := { inv := F.map (inv f), hom_inv_id' := by rw [← F.map_comp, is_iso.hom_inv_id, map_id], inv_hom_id' := by rw [← F.map_comp, is_iso.inv_hom_id, map_id] } end functor instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := begin -- This is an interesting test case for better rewrite automation. intros, rw [←category.id_comp C g, ←category.id_comp C h], rw [← is_iso.inv_hom_id f], rw [category.assoc, w, category.assoc], end } instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := begin intros, rw [←category.comp_id C g, ←category.comp_id C h], rw [← is_iso.hom_inv_id f], rw [←category.assoc, w, ←category.assoc] end } def Aut (X : C) := X ≅ X attribute [extensionality Aut] iso.ext instance {X : C} : group (Aut X) := by refine { one := iso.refl X, inv := iso.symm, mul := iso.trans, .. } ; obviously end category_theory
912a22add54418fcb017c3e7c2dd85e109c48762
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/util/signature_decl.lean
e87dd918a7e135c8d1b2211d2ce99ad3b1a10635
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
14,968
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .default import .meta.default /-- signature information -/ meta structure signature_info := (to_name : name) (mk_name : name) (univ_params : list name) (params : list (name × level × binder_info)) (ops : list (name × nat × list nat)) namespace signature_info open exceptional meta def num_params (info : signature_info) : nat := info.params.length meta def param_names (info : signature_info) : list name := info.params.map prod.fst meta def param_snd (info : signature_info) : list (level × binder_info) := info.params.map prod.snd meta def param_levels (info : signature_info) : list level := info.param_snd.map prod.fst meta def param_meta_levels (info : signature_info) : list level := info.param_levels.map $ λ l, l.metaify info.univ_params meta def param_binders (info : signature_info) : list binder_info := info.param_snd.map prod.snd meta def op_names (info : signature_info) : list name := info.ops.map prod.fst meta def op_sorts (info : signature_info) : list (nat × list nat) := info.ops.map prod.snd meta def sig_name (info : signature_info) : name := info.to_name.add_sub_str "sig" meta def hom_name (info : signature_info) : name := info.to_name.add_sub_str "hom" meta def expr_name (info : signature_info) : name := info.to_name.add_sub_str "expr" meta def trans_name (info : signature_info) : name := info.to_name.add_sub_str "trans" section parse open exceptional open interactive open lean lean.parser meta def parse_level : list name → list name → level → level × list name × list name | us ms (level.zero) := (level.zero, us, ms) | us ms (level.succ l) := let (l, us, ms) := parse_level us ms l in (level.succ l, us, ms) | us ms (level.max l₁ l₂) := let (l₁, us, ms) := parse_level us ms l₁ in let (l₂, us, ms) := parse_level us ms l₂ in (level.max l₁ l₂, us, ms) | us ms (level.imax l₁ l₂) := let (l₁, us, ms) := parse_level us ms l₁ in let (l₂, us, ms) := parse_level us ms l₂ in (level.imax l₁ l₂, us, ms) | us ms (level.param n) := let i := us.index_of n in if i = us.length then (level.param $ mk_sub_name `u us.length, n :: us, ms) else (level.param $ mk_sub_name `u (us.length - i - 1), us, ms) | us ms (level.mvar n) := let i := ms.index_of n in if i = ms.length then (level.mvar $ mk_sub_name `m ms.length, us, n :: ms) else (level.mvar $ mk_sub_name `m (ms.length - i - 1), us, ms) meta def parse_params : list pexpr → list name × list name → list (name × level × binder_info) → exceptional (list (name × level × binder_info) × list name × list name) | [] us ps := success $ (ps, us) | (e :: es) us ps := parse_params es us ps >>= λ ⟨ps, us⟩, match e with | (expr.local_const _ n b (expr.sort l)) := let (l, us) := parse_level us.1 us.2 l in success ((n, l, b) :: ps, us) | _ := fail "invalid signature parameter" end meta def parse_op (ns : list name) : parser (name × nat × list nat) := do { nm ← ident, tk ":", ps ← sep_by (tk "→" <|> tk "->") ident, guard (ps.length > 0), let vs := ps.reverse.map (λ p, list.index_of p ns), guard (∀ v ∈ vs, v < ns.length), tk ")", pure (nm, vs.head, vs.tail) } meta def parse : parser signature_info := do { nm ← ident, ps ← parse_binders, (ps, us, ms) ← parse_params ps ([],[]) [], tk ":=", tk "(", fs ← sep_by (tk "(") (parse_op $ ps.map prod.fst), pure { to_name := nm , mk_name := `mk , univ_params := mk_sub_names `u us.length ++ mk_sub_names `m ms.length , params := ps , ops := fs } } meta def get_param (info : signature_info) (n : nat) : exceptional (name × level × binder_info) := match info.params.nth n with | some p := success p | none := fail "parameter index too large" end meta def format_sig (info : signature_info) : exceptional format := let s0 : list format := [ "structure" , format.cbrace (format.join $ list.intersperse format.space $ info.univ_params.map to_fmt) , to_fmt info.sig_name ] in let s1 : list format := info.params.map (λ ⟨n, l, b⟩, b.to_fmt (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s2 : list format := let lvl : level := level.normalize $ level.list_max (level.one :: (info.params.map (λ ⟨_,l,_⟩, l))) in [ ":" , "Sort (" ++ to_fmt lvl ++ ")" , ":=" , to_fmt info.mk_name , "::" ] in info.ops.mmap (λ ⟨n,c,d⟩, prod.fst <$> info.get_param c >>= λ c, d.mfoldl (λ f n, prod.fst <$> info.get_param n >>= λ n, success $ to_fmt n ++ " → " ++ f ) (to_fmt c) >>= λ fn, success $ format.paren $ format.join $ list.intersperse format.space [to_fmt n, ":", fn] ) >>= λ s3, success $ format.interspace (s0 ++ s1 ++ s2 ++ s3) meta def format_hom (info : signature_info) : exceptional format := let us : list name := mk_sub_names `u info.univ_params.length in let vs : list name := mk_sub_names `v info.univ_params.length in let ul : list (name × level) := info.univ_params.zip (us.map level.param) in let vl : list (name × level) := info.univ_params.zip (vs.map level.param) in let up : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `α k, level.subst.app ul l) ) in let vp : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `β k, level.subst.app vl l) ) in let s0 : list format := [ "structure" , format.cbrace (format.interspace $ (us ++ vs).map to_fmt) , to_fmt info.hom_name ] in let s1 : list format := up.map (λ ⟨n, l⟩, format.cbrace (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s2 : list format := vp.map (λ ⟨n, l⟩, format.cbrace (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s3 : list format := let usig : format := "@" ++ to_fmt info.sig_name ++ "." ++ format.cbrace (format.interspace $ us.map to_fmt) in let vsig : format := "@" ++ to_fmt info.sig_name ++ "." ++ format.cbrace (format.interspace $ vs.map to_fmt) in let lvl : level := level.normalize $ level.list_max (level.one :: (up ++ vp).map (λ ⟨_,l⟩, l)) in [ format.paren $ format.interspace $ "sig_1 :" :: usig :: to_fmt <$> prod.fst <$> up , format.paren $ format.interspace $ "sig_2 :" :: vsig :: to_fmt <$> prod.fst <$> vp , "extends multi_function_" ++ to_fmt info.num_params , format.interspace ((up ++ vp).map (λ ⟨n, _⟩, to_fmt n)) , ":" , "Sort (" ++ to_fmt lvl ++ ")" , ":=" ] in let s4 : list format := info.ops.map (λ ⟨n, c, d⟩, let xs : list name := mk_sub_names `x d.length in let rarg : list format := xs.map to_fmt in let larg : list format := (d.reverse.zip rarg).map $ λ ⟨i, x⟩, format.paren ("fn_" ++ to_fmt i ++ " " ++ x) in let rapp : format := format.interspace (("sig_1." ++ to_fmt n) :: rarg) in let rapp : format := "fn_" ++ to_fmt c ++ " " ++ format.paren rapp in let lapp : format := format.interspace (("sig_2." ++ to_fmt n) :: larg) in if d.length = 0 then format.paren $ to_fmt n ++ " : " ++ lapp ++ " = " ++ rapp else format.paren $ to_fmt n ++ " : ∀ " ++ (format.interspace rarg) ++ ", " ++ lapp ++ " = " ++ rapp ) in success $ format.interspace (s0 ++ s1 ++ s2 ++ s3 ++ s4) meta def format_hom_eq (info : signature_info) : exceptional format := let us : list name := mk_sub_names `u info.univ_params.length in let vs : list name := mk_sub_names `v info.univ_params.length in let ul : list (name × level) := info.univ_params.zip (us.map level.param) in let vl : list (name × level) := info.univ_params.zip (vs.map level.param) in let up : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `α k, level.subst.app ul l) ) in let vp : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `β k, level.subst.app vl l) ) in let s0 : list format := [ "theorem" , format.cbrace (format.interspace $ (us ++ vs).map to_fmt) , to_fmt (info.hom_name ++ `eq) ] in let s1 : list format := (up ++ vp).map (λ ⟨n, l⟩, format.cbrace (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s2 : list format := [ format.cbrace $ format.interspace [ "s_1 :" , "@" ++ to_fmt info.sig_name , format.interspace (up.map $ λ ⟨n, _⟩, to_fmt n) ] , format.cbrace $ format.interspace [ "s_2 :" , "@" ++ to_fmt info.sig_name , format.interspace (vp.map $ λ ⟨n, _⟩, to_fmt n) ] , ":" , "∀ " ++ (format.dcbrace $ "f g : " ++ to_fmt info.hom_name ++ " s_1 s_2") ++ "," , "f.to_multi_function_" ++ to_fmt info.num_params , "=" , "g.to_multi_function_" ++ to_fmt info.num_params , "→ f = g" ] in let s3 : list format := [ "|" , "⟨" ++ (format.join $ list.intersperse "," (list.repeat "_" (info.ops.length + 1))) ++ "⟩" , "⟨" ++ (format.join $ list.intersperse "," (list.repeat "_" (info.ops.length + 1))) ++ "⟩" , "rfl := rfl" ] in success $ format.interspace (s0 ++ s1 ++ s2 ++ s3) meta def format_hom_id (info : signature_info) : exceptional format := let us : list name := mk_sub_names `u info.univ_params.length in let ul : list (name × level) := info.univ_params.zip (us.map level.param) in let up : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `α k, level.subst.app ul l) ) in let s0 : list format := [ "definition" , format.cbrace (format.interspace $ us.map to_fmt) , to_fmt info.hom_name ++ "_id" ] in let s1 : list format := up.map (λ ⟨n, l⟩, format.cbrace (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s2 : list format := [ format.paren $ format.interspace [ "s :" , "@" ++ to_fmt info.sig_name , format.interspace (up.map $ λ ⟨n, _⟩, to_fmt n) ] , ":" , to_fmt info.hom_name , "s" , "s" , ":=" ] in let s3 : list format := [ "{" , "to_multi_function_" ++ to_fmt info.num_params , ":=" , "multi_function_" ++ to_fmt info.num_params ++ ".id" ] ++ info.ops.map (λ ⟨n,_⟩, ", " ++ to_fmt n ++ " := by intros; reflexivity" ) ++ ["}"] in success $ format.interspace (s0 ++ s1 ++ s2 ++ s3) meta def format_hom_comp (info : signature_info) : exceptional format := let us : list name := mk_sub_names `u info.univ_params.length in let vs : list name := mk_sub_names `v info.univ_params.length in let ws : list name := mk_sub_names `w info.univ_params.length in let ul : list (name × level) := info.univ_params.zip (us.map level.param) in let vl : list (name × level) := info.univ_params.zip (vs.map level.param) in let wl : list (name × level) := info.univ_params.zip (ws.map level.param) in let up : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `α k, level.subst.app ul l) ) in let vp : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `β k, level.subst.app vl l) ) in let wp : list (name × level) := info.param_meta_levels.enum.map (λ ⟨k, l⟩, (mk_sub_name `γ k, level.subst.app wl l) ) in let s0 : list format := [ "definition" , format.cbrace (format.interspace $ (us ++ vs ++ ws).map to_fmt) , to_fmt info.hom_name ++ "_comp" ] in let s1 : list format := (up ++ vp ++ wp).map (λ ⟨n, l⟩, format.cbrace (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s2 : list format := [ format.cbrace $ format.interspace [ "s_1 :" , "@" ++ to_fmt info.sig_name , format.interspace (up.map $ λ ⟨n, _⟩, to_fmt n) ] , format.cbrace $ format.interspace [ "s_2 :" , "@" ++ to_fmt info.sig_name , format.interspace (vp.map $ λ ⟨n, _⟩, to_fmt n) ] , format.cbrace $ format.interspace [ "s_3 :" , "@" ++ to_fmt info.sig_name , format.interspace (wp.map $ λ ⟨n, _⟩, to_fmt n) ] , format.paren $ "f : " ++ to_fmt info.hom_name ++ " s_2 s_3" , format.paren $ "g : " ++ to_fmt info.hom_name ++ " s_1 s_2" , ":" , to_fmt info.hom_name ++ " s_1 s_3" , ":=" ] in let s3 : list format := [ "{" , "to_multi_function_" ++ to_fmt info.num_params , ":=" , "multi_function_" ++ to_fmt info.num_params ++ ".comp" , "f.to_multi_function_" ++ to_fmt info.num_params , "g.to_multi_function_" ++ to_fmt info.num_params ] ++ info.ops.map (λ ⟨n,_,_⟩, ", " ++ to_fmt n ++ " := by intros; rw [f." ++ to_fmt n ++ ", g." ++ to_fmt n ++ "]" ) ++ ["}"] in success $ format.interspace (s0 ++ s1 ++ s2 ++ s3) meta def format_expr (info : signature_info) : exceptional format := let us : list name := mk_sub_names `u info.num_params in let ts : list name := mk_sub_names `α info.num_params in let s0 : list format := [ "inductive" , format.cbrace (format.interspace $ us.map to_fmt) , to_fmt info.expr_name ] in let s1 : list format := (list.zip us ts).map (λ ⟨u, n⟩, format.paren (to_fmt n ++ " : Sort " ++ to_fmt u) ) in let s2 : list format := let lvl : level := level.normalize $ level.list_max (level.one :: (info.params.map (λ ⟨_,l,_⟩, l))) in [ ":" , "nat → Sort (max 1 " ++ format.interspace (us.map to_fmt) ++ ")" ] in let s3 : list format := ts.enum.map (λ ⟨k, n⟩, format.interspace ["| const_" ++ to_fmt k, ":", to_fmt n, "→", to_fmt info.expr_name, to_fmt k] ) in let s4 : list format := info.ops.map (λ ⟨n, c, d⟩, let t : format := to_fmt $ info.expr_name in let f : format := d.foldl (λ f i, t ++ " " ++ to_fmt i ++ " → " ++ f) (t ++ " " ++ to_fmt c) in format.interspace ["|", to_fmt n, ":", f] ) in success $ format.interspace (s0 ++ s1 ++ s2 ++ s3 ++ s4) meta def format_expr_eval (info : signature_info) : exceptional format := let s0 : list format := [ "definition" , format.cbrace $ format.interspace (info.univ_params.map to_fmt) , to_fmt (info.expr_name ++ `eval) ] in let s1 : list format := info.params.map (λ ⟨n, l, _⟩, format.cbrace (to_fmt n ++ " : Sort (" ++ to_fmt l ++ ")") ) in let s2 : list format := [ format.paren ("s : @" ++ to_fmt info.sig_name ++ " " ++ format.interspace (info.params.map $ λ ⟨n,_⟩, to_fmt n)) , ":" , to_fmt info.expr_name ++ " " ++ format.interspace (info.params.map $ λ ⟨n,_⟩, to_fmt n) ] in success $ format.interspace (s0 ++ s1 ++ s2) meta def format_trans (info : signature_info) (attr : name) : exceptional format := let s0 : list format := [ "@[user_attribute]" , "meta" , "def" , to_fmt info.trans_name , ":" , "user_attribute" , ":=" , "{ name := `" ++ to_fmt attr , ", descr := \"" ++ to_fmt info.to_name ++ " translation attribute\"" , "}" ] in success $ format.interspace s0 end parse end signature_info section signature_command open lean lean.parser interactive @[user_command] meta def signature_command (_ : parse $ tk "signature") : parser unit := do { info ← signature_info.parse, emit (to_string $ info.format_sig), emit (to_string $ info.format_hom), emit (to_string $ info.format_hom_eq), emit (to_string $ info.format_hom_id), emit (to_string $ info.format_hom_comp), emit (to_string $ info.format_expr), full ← tactic.resolve_constant info.sig_name, emit (to_string $ info.format_trans $ full.get_prefix ++ info.trans_name.get_suffix), pure () } end signature_command
6ecfcf792a94f39df15226de2d1b4b3795eec0b4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/explode.lean
bf95a3b8385f7e99e1db10c825bbec6237775edd
[ "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
9,406
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Minchao Wu -/ import tactic.core /-! # `#explode` command Displays a proof term in a line by line format somewhat akin to a Fitch style proof or the Metamath proof style. -/ open expr tactic namespace tactic namespace explode @[derive inhabited] inductive status : Type | reg | intro | lam | sintro /-- A type to distinguish introduction or elimination rules represented as strings from theorems referred to by their names. -/ meta inductive thm : Type | expr (e : expr) | name (n : name) | string (s : string) /-- Turn a thm into a string. -/ meta def thm.to_string : thm → string | (thm.expr e) := e.to_string | (thm.name n) := n.to_string | (thm.string s) := s meta structure entry : Type := (expr : expr) (line : nat) (depth : nat) (status : status) (thm : thm) (deps : list nat) meta def pad_right (l : list string) : list string := let n := l.foldl (λ r (s:string), max r s.length) 0 in l.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s @[derive inhabited] meta structure entries : Type := mk' :: (s : expr_map entry) (l : list entry) meta def entries.find (es : entries) (e : expr) : option entry := es.s.find e meta def entries.size (es : entries) : ℕ := es.s.size meta def entries.add : entries → entry → entries | es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩ meta def entries.head (es : entries) : option entry := es.l.head' meta def format_aux : list string → list string → list string → list entry → tactic format | (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do fmt ← do { let margin := string.join (list.repeat " │" en.depth), let margin := match en.status with | status.sintro := " ├" ++ margin | status.intro := " │" ++ margin ++ " ┌" | status.reg := " │" ++ margin ++ "" | status.lam := " │" ++ margin ++ "" end, p ← infer_type en.expr >>= pp, let lhs := line ++ "│" ++ dep ++ "│ " ++ thm ++ margin ++ " ", return $ format.of_string lhs ++ (p.nest lhs.length).group ++ format.line }, (++ fmt) <$> format_aux lines deps thms es | _ _ _ _ := return format.nil meta instance : has_to_tactic_format entries := ⟨λ es : entries, let lines := pad_right $ es.l.map (λ en, to_string en.line), deps := pad_right $ es.l.map (λ en, string.intercalate "," (en.deps.map to_string)), thms := pad_right $ es.l.map (λ en, (entry.thm en).to_string) in format_aux lines deps thms es.l⟩ meta def append_dep (filter : expr → tactic unit) (es : entries) (e : expr) (deps : list nat) : tactic (list nat) := do { ei ← es.find e, filter ei.expr, return (ei.line :: deps) } <|> return deps meta def may_be_proof (e : expr) : tactic bool := do expr.sort u ← infer_type e >>= infer_type, return $ bnot u.nonzero end explode open explode meta mutual def explode.core, explode.args (filter : expr → tactic unit) with explode.core : expr → bool → nat → entries → tactic entries | e@(lam n bi d b) si depth es := do m ← mk_fresh_name, let l := local_const m n bi d, let b' := instantiate_var b l, if si then let en : entry := ⟨l, es.size, depth, status.sintro, thm.name n, []⟩ in do es' ← explode.core b' si depth (es.add en), return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string "∀I", [es.size, es'.size - 1]⟩ else do let en : entry := ⟨l, es.size, depth, status.intro, thm.name n, []⟩, es' ← explode.core b' si (depth + 1) (es.add en), -- in case of a "have" clause, the b' here has an annotation deps' ← explode.append_dep filter es' b'.erase_annotations [], deps' ← explode.append_dep filter es' l deps', return $ es'.add ⟨e, es'.size, depth, status.lam, thm.string "∀I", deps'⟩ | e@(elet n t a b) si depth es := explode.core (reduce_lets e) si depth es | e@(macro n l) si depth es := explode.core l.head si depth es | e si depth es := filter e >> match get_app_fn_args e with | (nm@(const n _), args) := explode.args e args depth es (thm.expr nm) [] | (fn, []) := do let en : entry := ⟨fn, es.size, depth, status.reg, thm.expr fn, []⟩, return (es.add en) | (fn, args) := do es' ← explode.core fn ff depth es, -- in case of a "have" clause, the fn here has an annotation deps ← explode.append_dep filter es' fn.erase_annotations [], explode.args e args depth es' (thm.string "∀E") deps end with explode.args : expr → list expr → nat → entries → thm → list nat → tactic entries | e (arg :: args) depth es thm deps := do es' ← explode.core arg ff depth es <|> return es, deps' ← explode.append_dep filter es' arg deps, explode.args e args depth es' thm deps' | e [] depth es thm deps := return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩) meta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries := let filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in tactic.explode.core filter e tt 0 (default _) meta def explode (n : name) : tactic unit := do const n _ ← resolve_name n | fail "cannot resolve name", d ← get_decl n, v ← match d with | (declaration.defn _ _ _ v _ _) := return v | (declaration.thm _ _ _ v) := return v.get | _ := fail "not a definition" end, t ← pp d.type, explode_expr v <* trace (to_fmt n ++ " : " ++ t) >>= trace open interactive lean lean.parser interaction_monad.result /-- `#explode decl_name` displays a proof term in a line-by-line format somewhat akin to a Fitch-style proof or the Metamath proof style. `#explode_widget decl_name` renders a widget that displays an `#explode` proof. `#explode iff_true_intro` produces ```lean iff_true_intro : ∀ {a : Prop}, a → (a ↔ true) 0│ │ a ├ Prop 1│ │ h ├ a 2│ │ hl │ ┌ a 3│ │ trivial │ │ true 4│2,3│ ∀I │ a → true 5│ │ hr │ ┌ true 6│5,1│ ∀I │ true → a 7│4,6│ iff.intro │ a ↔ true 8│1,7│ ∀I │ a → (a ↔ true) 9│0,8│ ∀I │ ∀ {a : Prop}, a → (a ↔ true) ``` In more detail: The output of `#explode` is a Fitch-style proof in a four-column diagram modeled after Metamath proof displays like [this](http://us.metamath.org/mpeuni/ru.html). The headers of the columns are "Step", "Hyp", "Ref", "Type" (or "Expression" in the case of Metamath): * Step: An increasing sequence of numbers to number each step in the proof, used in the Hyp field. * Hyp: The direct children of the current step. Most theorems are implications like `A -> B -> C`, and so on the step proving `C` the Hyp field will refer to the steps that prove `A` and `B`. * Ref: The name of the theorem being applied. This is well-defined in Metamath, but in Lean there are some special steps that may have long names because the structure of proof terms doesn't exactly match this mold. * If the theorem is `foo (x y : Z) : A x -> B y -> C x y`: * the Ref field will contain `foo`, * `x` and `y` will be suppressed, because term construction is not interesting, and * the Hyp field will reference steps proving `A x` and `B y`. This corresponds to a proof term like `@foo x y pA pB` where `pA` and `pB` are subproofs. * If the head of the proof term is a local constant or lambda, then in this case the Ref will say `∀E` for forall-elimination. This happens when you have for example `h : A -> B` and `ha : A` and prove `b` by `h ha`; we reinterpret this as if it said `∀E h ha` where `∀E` is (n-ary) modus ponens. * If the proof term is a lambda, we will also use `∀I` for forall-introduction, referencing the body of the lambda. The indentation level will increase, and a bracket will surround the proof of the body of the lambda, starting at a proof step labeled with the name of the lambda variable and its type, and ending with the `∀I` step. Metamath doesn't have steps like this, but the style is based on Fitch proofs in first-order logic. * Type: This contains the type of the proof term, the theorem being proven at the current step. This proof layout differs from `#print` in using lots of intermediate step displays so that you can follow along and don't have to see term construction steps because they are implicitly in the intermediate step displays. Also, it is common for a Lean theorem to begin with a sequence of lambdas introducing local constants of the theorem. In order to minimize the indentation level, the `∀I` steps at the end of the proof will be introduced in a group and the indentation will stay fixed. (The indentation brackets are only needed in order to delimit the scope of assumptions, and these assumptions have global scope anyway so detailed tracking is not necessary.) -/ @[user_command] meta def explode_cmd (_ : parse $ tk "#explode") : parser unit := do n ← ident, explode n . add_tactic_doc { name := "#explode / #explode_widget", category := doc_category.cmd, decl_names := [`tactic.explode_cmd, `tactic.explode_widget_cmd], inherit_description_from := `tactic.explode_cmd, tags := ["proof display", "widgets"] } end tactic
f6609074d2bfa5bc9ae040fbe35a4ae4581ac530
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/sum/basic.lean
a935d2eec34f2c7c217eebff2a3c0bb3ede32df8
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
17,484
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury G. Kudryashov -/ import logic.function.basic import tactic.basic /-! # Disjoint union of types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves basic results about the sum type `α ⊕ β`. `α ⊕ β` is the type made of a copy of `α` and a copy of `β`. It is also called *disjoint union*. ## Main declarations * `sum.get_left`: Retrieves the left content of `x : α ⊕ β` or returns `none` if it's coming from the right. * `sum.get_right`: Retrieves the right content of `x : α ⊕ β` or returns `none` if it's coming from the left. * `sum.is_left`: Returns whether `x : α ⊕ β` comes from the left component or not. * `sum.is_right`: Returns whether `x : α ⊕ β` comes from the right component or not. * `sum.map`: Maps `α ⊕ β` to `γ ⊕ δ` component-wise. * `sum.elim`: Nondependent eliminator/induction principle for `α ⊕ β`. * `sum.swap`: Maps `α ⊕ β` to `β ⊕ α` by swapping components. * `sum.lex`: Lexicographic order on `α ⊕ β` induced by a relation on `α` and a relation on `β`. ## Notes The definition of `sum` takes values in `Type*`. This effectively forbids `Prop`- valued sum types. To this effect, we have `psum`, which takes value in `Sort*` and carries a more complicated universe signature in consequence. The `Prop` version is `or`. -/ universes u v w x variables {α : Type u} {α' : Type w} {β : Type v} {β' : Type x} {γ δ : Type*} namespace sum attribute [derive decidable_eq] sum @[simp] lemma «forall» {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ ∀ b, p (inr b) := ⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩ @[simp] lemma «exists» {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) := ⟨λ h, match h with | ⟨inl a, h⟩ := or.inl ⟨a, h⟩ | ⟨inr b, h⟩ := or.inr ⟨b, h⟩ end, λ h, match h with | or.inl ⟨a, h⟩ := ⟨inl a, h⟩ | or.inr ⟨b, h⟩ := ⟨inr b, h⟩ end⟩ lemma inl_injective : function.injective (inl : α → α ⊕ β) := λ x y, inl.inj lemma inr_injective : function.injective (inr : β → α ⊕ β) := λ x y, inr.inj section get /-- Check if a sum is `inl` and if so, retrieve its contents. -/ @[simp] def get_left : α ⊕ β → option α | (inl a) := some a | (inr _) := none /-- Check if a sum is `inr` and if so, retrieve its contents. -/ @[simp] def get_right : α ⊕ β → option β | (inr b) := some b | (inl _) := none /-- Check if a sum is `inl`. -/ @[simp] def is_left : α ⊕ β → bool | (inl _) := tt | (inr _) := ff /-- Check if a sum is `inr`. -/ @[simp] def is_right : α ⊕ β → bool | (inl _) := ff | (inr _) := tt variables {x y : α ⊕ β} lemma get_left_eq_none_iff : x.get_left = none ↔ x.is_right := by cases x; simp only [get_left, is_right, coe_sort_tt, coe_sort_ff, eq_self_iff_true] lemma get_right_eq_none_iff : x.get_right = none ↔ x.is_left := by cases x; simp only [get_right, is_left, coe_sort_tt, coe_sort_ff, eq_self_iff_true] @[simp] lemma bnot_is_left (x : α ⊕ β) : bnot x.is_left = x.is_right := by cases x; refl @[simp] lemma is_left_eq_ff : x.is_left = ff ↔ x.is_right := by cases x; simp lemma not_is_left : ¬x.is_left ↔ x.is_right := by simp @[simp] lemma bnot_is_right (x : α ⊕ β) : bnot x.is_right = x.is_left := by cases x; refl @[simp] lemma is_right_eq_ff : x.is_right = ff ↔ x.is_left := by cases x; simp lemma not_is_right : ¬x.is_right ↔ x.is_left := by simp lemma is_left_iff : x.is_left ↔ ∃ y, x = sum.inl y := by cases x; simp lemma is_right_iff : x.is_right ↔ ∃ y, x = sum.inr y := by cases x; simp end get theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b := ⟨inl.inj, congr_arg _⟩ theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b := ⟨inr.inj, congr_arg _⟩ theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b. theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a. /-- Define a function on `α ⊕ β` by giving separate definitions on `α` and `β`. -/ protected def elim {α β γ : Sort*} (f : α → γ) (g : β → γ) : α ⊕ β → γ := λ x, sum.rec_on x f g @[simp] lemma elim_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : α) : sum.elim f g (inl x) = f x := rfl @[simp] lemma elim_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) (x : β) : sum.elim f g (inr x) = g x := rfl @[simp] lemma elim_comp_inl {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inl = f := rfl @[simp] lemma elim_comp_inr {α β γ : Sort*} (f : α → γ) (g : β → γ) : sum.elim f g ∘ inr = g := rfl @[simp] lemma elim_inl_inr {α β : Sort*} : @sum.elim α β _ inl inr = id := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) lemma comp_elim {α β γ δ : Sort*} (f : γ → δ) (g : α → γ) (h : β → γ): f ∘ sum.elim g h = sum.elim (f ∘ g) (f ∘ h) := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) @[simp] lemma elim_comp_inl_inr {α β γ : Sort*} (f : α ⊕ β → γ) : sum.elim (f ∘ inl) (f ∘ inr) = f := funext $ λ x, sum.cases_on x (λ _, rfl) (λ _, rfl) /-- Map `α ⊕ β` to `α' ⊕ β'` sending `α` to `α'` and `β` to `β'`. -/ protected def map (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β' := sum.elim (inl ∘ f) (inr ∘ g) @[simp] lemma map_inl (f : α → α') (g : β → β') (x : α) : (inl x).map f g = inl (f x) := rfl @[simp] lemma map_inr (f : α → α') (g : β → β') (x : β) : (inr x).map f g = inr (g x) := rfl @[simp] lemma map_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : ∀ x : α ⊕ β, (x.map f g).map f' g' = x.map (f' ∘ f) (g' ∘ g) | (inl a) := rfl | (inr b) := rfl @[simp] lemma map_comp_map {α'' β''} (f' : α' → α'') (g' : β' → β'') (f : α → α') (g : β → β') : (sum.map f' g') ∘ (sum.map f g) = sum.map (f' ∘ f) (g' ∘ g) := funext $ map_map f' g' f g @[simp] lemma map_id_id (α β) : sum.map (@id α) (@id β) = id := funext $ λ x, sum.rec_on x (λ _, rfl) (λ _, rfl) lemma elim_comp_map {α β γ δ ε : Sort*} {f₁ : α → β} {f₂ : β → ε} {g₁ : γ → δ} {g₂ : δ → ε} : sum.elim f₂ g₂ ∘ sum.map f₁ g₁ = sum.elim (f₂ ∘ f₁) (g₂ ∘ g₁) := by ext (_|_); refl @[simp] lemma is_left_map (f : α → β) (g : γ → δ) (x : α ⊕ γ) : is_left (x.map f g) = is_left x := by cases x; refl @[simp] lemma is_right_map (f : α → β) (g : γ → δ) (x : α ⊕ γ) : is_right (x.map f g) = is_right x := by cases x; refl @[simp] lemma get_left_map (f : α → β) (g : γ → δ) (x : α ⊕ γ) : (x.map f g).get_left = x.get_left.map f := by cases x; refl @[simp] lemma get_right_map (f : α → β) (g : γ → δ) (x : α ⊕ γ) : (x.map f g).get_right = x.get_right.map g := by cases x; refl open function (update update_eq_iff update_comp_eq_of_injective update_comp_eq_of_forall_ne) @[simp] lemma update_elim_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : α} {x : γ} : update (sum.elim f g) (inl i) x = sum.elim (update f i x) g := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_elim_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α → γ} {g : β → γ} {i : β} {x : γ} : update (sum.elim f g) (inr i) x = sum.elim f (update g i x) := update_eq_iff.2 ⟨by simp, by simp { contextual := tt }⟩ @[simp] lemma update_inl_comp_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inl = update (f ∘ inl) i x := update_comp_eq_of_injective _ inl_injective _ _ @[simp] lemma update_inl_apply_inl [decidable_eq α] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : α} {x : γ} : update f (inl i) x (inl j) = update (f ∘ inl) i x j := by rw ← update_inl_comp_inl @[simp] lemma update_inl_comp_inr [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {x : γ} : update f (inl i) x ∘ inr = f ∘ inr := update_comp_eq_of_forall_ne _ _ $ λ _, inr_ne_inl @[simp] lemma update_inl_apply_inr [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inl i) x (inr j) = f (inr j) := function.update_noteq inr_ne_inl _ _ @[simp] lemma update_inr_comp_inl [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inl = f ∘ inl := update_comp_eq_of_forall_ne _ _ $ λ _, inl_ne_inr @[simp] lemma update_inr_apply_inl [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : α} {j : β} {x : γ} : update f (inr j) x (inl i) = f (inl i) := function.update_noteq inl_ne_inr _ _ @[simp] lemma update_inr_comp_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i : β} {x : γ} : update f (inr i) x ∘ inr = update (f ∘ inr) i x := update_comp_eq_of_injective _ inr_injective _ _ @[simp] lemma update_inr_apply_inr [decidable_eq β] [decidable_eq (α ⊕ β)] {f : α ⊕ β → γ} {i j : β} {x : γ} : update f (inr i) x (inr j) = update (f ∘ inr) i x j := by rw ← update_inr_comp_inr /-- Swap the factors of a sum type -/ def swap : α ⊕ β → β ⊕ α := sum.elim inr inl @[simp] lemma swap_inl (x : α) : swap (inl x : α ⊕ β) = inr x := rfl @[simp] lemma swap_inr (x : β) : swap (inr x : α ⊕ β) = inl x := rfl @[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x := by cases x; refl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) := funext $ swap_swap @[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap := swap_swap @[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap := swap_swap @[simp] lemma is_left_swap (x : α ⊕ β) : x.swap.is_left = x.is_right := by cases x; refl @[simp] lemma is_right_swap (x : α ⊕ β) : x.swap.is_right = x.is_left := by cases x; refl @[simp] lemma get_left_swap (x : α ⊕ β) : x.swap.get_left = x.get_right := by cases x; refl @[simp] lemma get_right_swap (x : α ⊕ β) : x.swap.get_right = x.get_left := by cases x; refl section lift_rel /-- Lifts pointwise two relations between `α` and `γ` and between `β` and `δ` to a relation between `α ⊕ β` and `γ ⊕ δ`. -/ inductive lift_rel (r : α → γ → Prop) (s : β → δ → Prop) : α ⊕ β → γ ⊕ δ → Prop | inl {a c} : r a c → lift_rel (inl a) (inl c) | inr {b d} : s b d → lift_rel (inr b) (inr d) attribute [protected] lift_rel.inl lift_rel.inr variables {r r₁ r₂ : α → γ → Prop} {s s₁ s₂ : β → δ → Prop} {a : α} {b : β} {c : γ} {d : δ} {x : α ⊕ β} {y : γ ⊕ δ} @[simp] lemma lift_rel_inl_inl : lift_rel r s (inl a) (inl c) ↔ r a c := ⟨λ h, by { cases h, assumption }, lift_rel.inl⟩ @[simp] lemma not_lift_rel_inl_inr : ¬ lift_rel r s (inl a) (inr d) . @[simp] lemma not_lift_rel_inr_inl : ¬ lift_rel r s (inr b) (inl c) . @[simp] lemma lift_rel_inr_inr : lift_rel r s (inr b) (inr d) ↔ s b d := ⟨λ h, by { cases h, assumption }, lift_rel.inr⟩ instance [Π a c, decidable (r a c)] [Π b d, decidable (s b d)] : Π (ab : α ⊕ β) (cd : γ ⊕ δ), decidable (lift_rel r s ab cd) | (inl a) (inl c) := decidable_of_iff' _ lift_rel_inl_inl | (inl a) (inr d) := decidable.is_false not_lift_rel_inl_inr | (inr b) (inl c) := decidable.is_false not_lift_rel_inr_inl | (inr b) (inr d) := decidable_of_iff' _ lift_rel_inr_inr lemma lift_rel.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ a b, s₁ a b → s₂ a b) (h : lift_rel r₁ s₁ x y) : lift_rel r₂ s₂ x y := by { cases h, exacts [lift_rel.inl (hr _ _ ‹_›), lift_rel.inr (hs _ _ ‹_›)] } lemma lift_rel.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) (h : lift_rel r₁ s x y) : lift_rel r₂ s x y := h.mono hr $ λ _ _, id lemma lift_rel.mono_right (hs : ∀ a b, s₁ a b → s₂ a b) (h : lift_rel r s₁ x y) : lift_rel r s₂ x y := h.mono (λ _ _, id) hs protected lemma lift_rel.swap (h : lift_rel r s x y) : lift_rel s r x.swap y.swap := by { cases h, exacts [lift_rel.inr ‹_›, lift_rel.inl ‹_›] } @[simp] lemma lift_rel_swap_iff : lift_rel s r x.swap y.swap ↔ lift_rel r s x y := ⟨λ h, by { rw [←swap_swap x, ←swap_swap y], exact h.swap }, lift_rel.swap⟩ end lift_rel section lex /-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`, otherwise use the respective order on `α` or `β`. -/ inductive lex (r : α → α → Prop) (s : β → β → Prop) : α ⊕ β → α ⊕ β → Prop | inl {a₁ a₂} (h : r a₁ a₂) : lex (inl a₁) (inl a₂) | inr {b₁ b₂} (h : s b₁ b₂) : lex (inr b₁) (inr b₂) | sep (a b) : lex (inl a) (inr b) attribute [protected] sum.lex.inl sum.lex.inr attribute [simp] lex.sep variables {r r₁ r₂ : α → α → Prop} {s s₁ s₂ : β → β → Prop} {a a₁ a₂ : α} {b b₁ b₂ : β} {x y : α ⊕ β} @[simp] lemma lex_inl_inl : lex r s (inl a₁) (inl a₂) ↔ r a₁ a₂ := ⟨λ h, by { cases h, assumption }, lex.inl⟩ @[simp] lemma lex_inr_inr : lex r s (inr b₁) (inr b₂) ↔ s b₁ b₂ := ⟨λ h, by { cases h, assumption }, lex.inr⟩ @[simp] lemma lex_inr_inl : ¬ lex r s (inr b) (inl a) . instance [decidable_rel r] [decidable_rel s] : decidable_rel (lex r s) | (inl a) (inl c) := decidable_of_iff' _ lex_inl_inl | (inl a) (inr d) := decidable.is_true (lex.sep _ _) | (inr b) (inl c) := decidable.is_false lex_inr_inl | (inr b) (inr d) := decidable_of_iff' _ lex_inr_inr protected lemma lift_rel.lex {a b : α ⊕ β} (h : lift_rel r s a b) : lex r s a b := by { cases h, exacts [lex.inl ‹_›, lex.inr ‹_›] } lemma lift_rel_subrelation_lex : subrelation (lift_rel r s) (lex r s) := λ a b, lift_rel.lex lemma lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ a b, s₁ a b → s₂ a b) (h : lex r₁ s₁ x y) : lex r₂ s₂ x y := by { cases h, exacts [lex.inl (hr _ _ ‹_›), lex.inr (hs _ _ ‹_›), lex.sep _ _] } lemma lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) (h : lex r₁ s x y) : lex r₂ s x y := h.mono hr $ λ _ _, id lemma lex.mono_right (hs : ∀ a b, s₁ a b → s₂ a b) (h : lex r s₁ x y) : lex r s₂ x y := h.mono (λ _ _, id) hs lemma lex_acc_inl {a} (aca : acc r a) : acc (lex r s) (inl a) := begin induction aca with a H IH, constructor, intros y h, cases h with a' _ h', exact IH _ h' end lemma lex_acc_inr (aca : ∀ a, acc (lex r s) (inl a)) {b} (acb : acc s b) : acc (lex r s) (inr b) := begin induction acb with b H IH, constructor, intros y h, cases h with _ _ _ b' _ h' a, { exact IH _ h' }, { exact aca _ } end lemma lex_wf (ha : well_founded r) (hb : well_founded s) : well_founded (lex r s) := have aca : ∀ a, acc (lex r s) (inl a), from λ a, lex_acc_inl (ha.apply a), ⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩ end lex end sum open sum namespace function lemma injective.sum_elim {f : α → γ} {g : β → γ} (hf : injective f) (hg : injective g) (hfg : ∀ a b, f a ≠ g b) : injective (sum.elim f g) | (inl x) (inl y) h := congr_arg inl $ hf h | (inl x) (inr y) h := (hfg x y h).elim | (inr x) (inl y) h := (hfg y x h.symm).elim | (inr x) (inr y) h := congr_arg inr $ hg h lemma injective.sum_map {f : α → β} {g : α' → β'} (hf : injective f) (hg : injective g) : injective (sum.map f g) | (inl x) (inl y) h := congr_arg inl $ hf $ inl.inj h | (inr x) (inr y) h := congr_arg inr $ hg $ inr.inj h lemma surjective.sum_map {f : α → β} {g : α' → β'} (hf : surjective f) (hg : surjective g) : surjective (sum.map f g) | (inl y) := let ⟨x, hx⟩ := hf y in ⟨inl x, congr_arg inl hx⟩ | (inr y) := let ⟨x, hx⟩ := hg y in ⟨inr x, congr_arg inr hx⟩ end function namespace sum open function lemma elim_const_const (c : γ) : sum.elim (const _ c : α → γ) (const _ c : β → γ) = const _ c := by { ext x, cases x; refl } @[simp] lemma elim_lam_const_lam_const (c : γ) : sum.elim (λ (_ : α), c) (λ (_ : β), c) = λ _, c := sum.elim_const_const c lemma elim_update_left [decidable_eq α] [decidable_eq β] (f : α → γ) (g : β → γ) (i : α) (c : γ) : sum.elim (function.update f i c) g = function.update (sum.elim f g) (inl i) c := begin ext x, cases x, { by_cases h : x = i, { subst h, simp }, { simp [h] } }, { simp } end lemma elim_update_right [decidable_eq α] [decidable_eq β] (f : α → γ) (g : β → γ) (i : β) (c : γ) : sum.elim f (function.update g i c) = function.update (sum.elim f g) (inr i) c := begin ext x, cases x, { simp }, { by_cases h : x = i, { subst h, simp }, { simp [h] } } end end sum /-! ### Ternary sum Abbreviations for the maps from the summands to `α ⊕ β ⊕ γ`. This is useful for pattern-matching. -/ namespace sum3 /-- The map from the first summand into a ternary sum. -/ @[pattern, simp, reducible] def in₀ (a) : α ⊕ β ⊕ γ := inl a /-- The map from the second summand into a ternary sum. -/ @[pattern, simp, reducible] def in₁ (b) : α ⊕ β ⊕ γ := inr $ inl b /-- The map from the third summand into a ternary sum. -/ @[pattern, simp, reducible] def in₂ (c) : α ⊕ β ⊕ γ := inr $ inr c end sum3
bcde7f07f668d5e46675ed69177063e7dbc84cc8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/fin/default.lean
8962a1408212dd9b53ecd737092f19ba5fbb2bb8
[]
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
294
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.fin.basic import Mathlib.Lean3Lib.init.data.fin.ops namespace Mathlib
cc5e2129e0e14706c5a56b9214a98d446fbf31cb
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Data/Array/QSort.lean
cb4947e7a47ebe0df489f5e4627c103c0fa90bfa
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
1,703
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.Data.Array.Basic namespace Array -- TODO: remove the [Inhabited α] parameters as soon as we have the tactic framework for automating proof generation and using Array.fget -- TODO: remove `partial` using well-founded recursion @[inline] def qpartition {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (lo hi : Nat) : Nat × Array α := let mid := (lo + hi) / 2 let as := if lt (as.get! mid) (as.get! lo) then as.swap! lo mid else as let as := if lt (as.get! hi) (as.get! lo) then as.swap! lo hi else as let as := if lt (as.get! mid) (as.get! hi) then as.swap! mid hi else as let pivot := as.get! hi let rec loop (as : Array α) (i j : Nat) := if h : j < hi then if lt (as.get! j) pivot then let as := as.swap! i j loop as (i+1) (j+1) else loop as i (j+1) else let as := as.swap! i hi (i, as) loop as lo lo termination_by _ => hi - j @[inline] partial def qsort {α : Type} [Inhabited α] (as : Array α) (lt : α → α → Bool) (low := 0) (high := as.size - 1) : Array α := let rec @[specialize] sort (as : Array α) (low high : Nat) := if low < high then let p := qpartition as lt low high; -- TODO: fix `partial` support in the equation compiler, it breaks if we use `let (mid, as) := partition as lt low high` let mid := p.1 let as := p.2 if mid >= high then as else let as := sort as low mid sort as (mid+1) high else as sort as low high end Array
94421ffb57b274a497a6df2fe2214055c538f514
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/archimedean.lean
a1ef7e360f021d6a345f1a15cbd68cf9753ad67d
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,284
lean
/- Copyright (c) 2020 Heather Macbeth, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Patrick Massot -/ import algebra.order.archimedean import group_theory.subgroup.basic /-! # Archimedean groups This file proves a few facts about ordered groups which satisfy the `archimedean` property, that is: `class archimedean (α) [ordered_add_comm_monoid α] : Prop :=` `(arch : ∀ (x : α) {y}, 0 < y → ∃ n : ℕ, x ≤ n • y)` They are placed here in a separate file (rather than incorporated as a continuation of `algebra.order.archimedean`) because they rely on some imports from `group_theory` -- bundled subgroups in particular. The main result is `add_subgroup.cyclic_of_min`: a subgroup of a decidable archimedean abelian group is cyclic, if its set of positive elements has a minimal element. This result is used in this file to deduce `int.subgroup_cyclic`, proving that every subgroup of `ℤ` is cyclic. (There are several other methods one could use to prove this fact, including more purely algebraic methods, but none seem to exist in mathlib as of writing. The closest is `subgroup.is_cyclic`, but that has not been transferred to `add_subgroup`.) The result is also used in `topology.instances.real` as an ingredient in the classification of subgroups of `ℝ`. -/ variables {G : Type*} [linear_ordered_add_comm_group G] [archimedean G] open linear_ordered_add_comm_group /-- Given a subgroup `H` of a decidable linearly ordered archimedean abelian group `G`, if there exists a minimal element `a` of `H ∩ G_{>0}` then `H` is generated by `a`. -/ lemma add_subgroup.cyclic_of_min {H : add_subgroup G} {a : G} (ha : is_least {g : G | g ∈ H ∧ 0 < g} a) : H = add_subgroup.closure {a} := begin obtain ⟨⟨a_in, a_pos⟩, a_min⟩ := ha, refine le_antisymm _ (H.closure_le.mpr $ by simp [a_in]), intros g g_in, obtain ⟨k, nonneg, lt⟩ : ∃ k, 0 ≤ g - k • a ∧ g - k • a < a := exists_int_smul_near_of_pos' a_pos g, have h_zero : g - k • a = 0, { by_contra h, have h : a ≤ g - k • a, { refine a_min ⟨_, _⟩, { exact add_subgroup.sub_mem H g_in (add_subgroup.zsmul_mem H a_in k) }, { exact lt_of_le_of_ne nonneg (ne.symm h) } }, have h' : ¬ (a ≤ g - k • a) := not_le.mpr lt, contradiction }, simp [sub_eq_zero.mp h_zero, add_subgroup.mem_closure_singleton], end /-- Every subgroup of `ℤ` is cyclic. -/ lemma int.subgroup_cyclic (H : add_subgroup ℤ) : ∃ a, H = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero H with h h, { use 0, rw h, exact add_subgroup.closure_singleton_zero.symm }, let s := {g : ℤ | g ∈ H ∧ 0 < g}, have h_bdd : ∀ g ∈ s, (0 : ℤ) ≤ g := λ _ h, le_of_lt h.2, obtain ⟨g₀, g₀_in, g₀_ne⟩ := h, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℤ, g₁ ∈ H ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, H.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha, ha'⟩ := int.exists_least_of_bdd ⟨(0 : ℤ), h_bdd⟩ ⟨g₁, g₁_in, g₁_pos⟩, exact ⟨a, add_subgroup.cyclic_of_min ⟨ha, ha'⟩⟩, end
f045f2f23c91bd15cac07dfa3185bab1dd3409b9
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/e13.lean
a974dc4868174910fa80f14070a6a5d1bb0b33d8
[ "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
503
lean
prelude precedence `+`:65 namespace nat constant nat : Type.{1} constant add : nat → nat → nat infixl + := add end nat namespace int open nat (nat) constant int : Type.{1} constant add : int → int → int infixl + := add constant of_nat : nat → int namespace coercions attribute of_nat [coercion] end coercions end int open nat open int constants n m : nat check n+m -- coercion nat -> int is not available open int.coercions check n+m -- coercion nat -> int is available
eb8ed220f2c89021b3fa7ca777949203602b966c
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/analysis/analytic/composition.lean
9fa6135eefcfc3ad5e069f46748c3e48f21d1eb7
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
56,801
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, Johan Commelin -/ import analysis.analytic.basic import combinatorics.composition /-! # Composition of analytic functions in this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. * `formal_multilinear_series.comp_assoc` states that composition is associative on formal multilinear series. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. The associativity of composition on formal multilinear series is a nontrivial result: it does not follow from the associativity of composition of analytic functions, as there is no uniqueness for the formal multilinear series representing a function (and also, it holds even when the radius of convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering double sums in a careful way. The change of variables is a canonical (combinatorial) bijection `composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described in more details below in the paragraph on associativity. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] open filter list open_locale topological_space big_operators classical /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series /-! In this paragraph, we define the composition of formal multilinear series, by summing over all possible compositions of `n`. -/ /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → (fin (c.length) → F) := λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i)) lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : apply_composition p (composition.ones n) = λ v i, p 1 (λ _, v (i.cast_le (composition.length_le _))) := begin funext v i, apply p.congr (composition.ones_blocks_fun _ _), intros j hjn hj1, obtain rfl : j = 0, { linarith }, refine congr_arg v _, rw [fin.ext_iff, fin.cast_le_val, composition.ones_embedding], end /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ lemma apply_composition_update (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : p.apply_composition c (function.update v j z) = function.update (p.apply_composition c v) (c.index j) (p (c.blocks_fun (c.index j)) (function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) := begin ext k, by_cases h : k = c.index j, { rw h, let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j), simp only [function.update_same], change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _, let j' := c.inv_embedding j, suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z, by rw B, suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z, by { convert C, exact (c.embedding_comp_inv j).symm }, exact function.update_comp_eq_of_injective _ (c.embedding_inj _) _ _ }, { simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff], let r : fin (c.blocks_fun k) → fin n := c.embedding k, change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r), suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B, apply function.update_comp_eq_of_not_mem_range, rwa c.mem_range_embedding_iff' } end /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition_multilinear p c`. This function admits a version as a continuous multilinear map, called `q.comp_along_composition p c` below. -/ def comp_along_composition_multilinear {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : multilinear_map 𝕜 (λ i : fin n, E) G := { to_fun := λ v, q c.length (p.apply_composition c v), add := λ v i x y, by simp only [apply_composition_update, continuous_multilinear_map.map_add], smul := λ v i c x, by simp only [apply_composition_update, continuous_multilinear_map.map_smul] } /-- The norm of `q.comp_along_composition_multilinear p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_multilinear_bound {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : ∥q.comp_along_composition_multilinear p c v∥ ≤ ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) := calc ∥q.comp_along_composition_multilinear p c v∥ = ∥q c.length (p.apply_composition c v)∥ : rfl ... ≤ ∥q c.length∥ * ∏ i, ∥p.apply_composition c v i∥ : continuous_multilinear_map.le_op_norm _ _ ... ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ * ∏ j : fin (c.blocks_fun i), ∥(v ∘ (c.embedding i)) j∥ : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _), apply continuous_multilinear_map.le_op_norm, end ... = ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * ∏ i (j : fin (c.blocks_fun i)), ∥(v ∘ (c.embedding i)) j∥ : by rw [finset.prod_mul_distrib, mul_assoc] ... = ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) : by { rw [← finset.prod_equiv c.blocks_fin_equiv, ← finset.univ_sigma_univ, finset.prod_sigma], congr } /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. It is constructed from the analogous multilinear function `q.comp_along_composition_multilinear p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (q.comp_along_composition_multilinear p c).mk_continuous _ (q.comp_along_composition_multilinear_bound p c) @[simp] lemma comp_along_composition_apply {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : (q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_norm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ∥q.comp_along_composition p c∥ ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ := multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) _ lemma comp_along_composition_nnnorm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : nnnorm (q.comp_along_composition p c) ≤ nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i)) := by simpa only [← nnreal.coe_le_coe, coe_nnnorm, nnreal.coe_mul, coe_nnnorm, nnreal.coe_prod, coe_nnnorm] using q.comp_along_composition_norm p c /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots.-/ protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, ∑ c : composition n, q.comp_along_composition p c /-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero variables, but on different spaces, we can not state this directly, so we state it when applied to arbitrary vectors (which have to be the zero vector). -/ lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) (v' : fin 0 → F) : (q.comp p) 0 v = q 0 v' := begin let c : composition 0 := composition.ones 0, dsimp [formal_multilinear_series.comp], have : {c} = (finset.univ : finset (composition 0)), { apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] }, rw ← this, simp only [finset.sum_singleton, continuous_multilinear_map.sum_apply], change q c.length (p.apply_composition c v) = q 0 v', congr, ext i, simp only [composition.ones_length] at i, exact fin_zero_elim i end @[simp] lemma comp_coeff_zero' (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) : (q.comp p) 0 v = q 0 (λ i, 0) := q.comp_coeff_zero p v _ /-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be expressed as a direct equality -/ lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) : (q.comp p) 0 = q 0 := by { ext v, exact q.comp_coeff_zero p _ _ } /-! ### The identity formal power series We will now define the identity power series, and show that it is a neutral element for left and right composition. -/ section variables (𝕜 E) /-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1` where it is (the continuous multilinear version of) the identity. -/ def id : formal_multilinear_series 𝕜 E E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E) | _ := 0 /-- The first coefficient of `id 𝕜 E` is the identity. -/ @[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl /-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent way, as it will often appear in this form. -/ lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) : (id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ := begin let w : fin 1 → E := λ i, v ⟨i.1, h.symm ▸ i.2⟩, have : v ⟨0, h.symm ▸ zero_lt_one⟩ = w 0 := rfl, rw [this, ← id_apply_one 𝕜 E w], apply congr _ h, intros, obtain rfl : i = 0, { linarith }, exact this, end /-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/ @[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 := by { cases n, { refl }, cases n, { contradiction }, refl } end @[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p := begin ext1 n, dsimp [formal_multilinear_series.comp], rw finset.sum_eq_single (composition.ones n), show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n, { ext v, rw comp_along_composition_apply, apply p.congr (composition.ones_length n), intros, rw apply_composition_ones, refine congr_arg v _, rw [fin.ext_iff, fin.cast_le_val], }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0, { assume b _ hb, obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k := composition.ne_ones_iff.1 hb, obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k := nth_le_of_mem hk, let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩, have A : 1 < b.blocks_fun j := by convert lt_k, ext v, rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply], apply continuous_multilinear_map.map_coord_zero _ j, dsimp [apply_composition], rw id_apply_ne_one _ _ (ne_of_gt A), refl }, { simp } end theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p := begin ext1 n, by_cases hn : n = 0, { rw [hn, h], ext v, rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one], refl }, { dsimp [formal_multilinear_series.comp], have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn, rw finset.sum_eq_single (composition.single n n_pos), show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n, { ext v, rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)], dsimp [apply_composition], apply p.congr rfl, intros, rw [function.comp_app, composition.single_embedding] }, show ∀ (b : composition n), b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0, { assume b _ hb, have A : b.length ≠ 1, by simpa [composition.eq_single_iff] using hb, ext v, rw [comp_along_composition_apply, id_apply_ne_one _ _ A], refl }, { simp } } end /-! ### Summability properties of the composition of formal power series-/ /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < q.radius) (hp : 0 < p.radius) : ∃ (r : nnreal), 0 < r ∧ summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 : (Σ n, composition n) → nnreal) := begin /- This follows from the fact that the growth rate of `∥qₙ∥` and `∥pₙ∥` is at most geometric, giving a geometric bound on each `∥q.comp_along_composition p op∥`, together with the fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/ rcases ennreal.lt_iff_exists_nnreal_btwn.1 hq with ⟨rq, rq_pos, hrq⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hp with ⟨rp, rp_pos, hrp⟩, obtain ⟨Cq, hCq⟩ : ∃ (Cq : nnreal), ∀ n, nnnorm (q n) * rq^n ≤ Cq := q.bound_of_lt_radius hrq, obtain ⟨Cp, hCp⟩ : ∃ (Cp : nnreal), ∀ n, nnnorm (p n) * rp^n ≤ Cp := p.bound_of_lt_radius hrp, let r0 : nnreal := (4 * max Cp 1)⁻¹, set r := min rp 1 * min rq 1 * r0, have r_pos : 0 < r, { apply mul_pos' (mul_pos' _ _), { rw [nnreal.inv_pos], apply mul_pos', { norm_num }, { exact lt_of_lt_of_le zero_lt_one (le_max_right _ _) } }, { rw ennreal.coe_pos at rp_pos, simp [rp_pos, zero_lt_one] }, { rw ennreal.coe_pos at rq_pos, simp [rq_pos, zero_lt_one] } }, let a : ennreal := ((4 : nnreal) ⁻¹ : nnreal), have two_a : 2 * a < 1, { change ((2 : nnreal) : ennreal) * ((4 : nnreal) ⁻¹ : nnreal) < (1 : nnreal), rw [← ennreal.coe_mul, ennreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_mul], change (2 : ℝ) * (4 : ℝ)⁻¹ < 1, norm_num }, have I : ∀ (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1) ≤ (Cq : ennreal) * a ^ i.1, { rintros ⟨n, c⟩, rw [← ennreal.coe_pow, ← ennreal.coe_mul, ennreal.coe_le_coe], calc nnnorm (q.comp_along_composition p c) * r ^ n ≤ (nnnorm (q c.length) * (finset.univ : finset (fin (c.length))).prod (λ i, nnnorm (p (c.blocks_fun i)))) * r ^ n : mul_le_mul_of_nonneg_right (q.comp_along_composition_nnnorm p c) (bot_le) ... = (nnnorm (q c.length) * (min rq 1)^n) * ((finset.univ : finset (fin (c.length))).prod (λ i, nnnorm (p (c.blocks_fun i))) * (min rp 1) ^ n) * r0 ^ n : by { dsimp [r], ring_exp } ... ≤ (nnnorm (q c.length) * (min rq 1) ^ c.length) * ((finset.univ : finset (fin c.length)).prod (λ i, nnnorm (p (c.blocks_fun i)) * (min rp 1) ^ (c.blocks_fun i))) * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_refl, pow_le_pow_of_le_one, min_le_right, c.length_le], apply le_of_eq, rw finset.prod_mul_distrib, congr' 1, conv_lhs { rw [← c.sum_blocks_fun, ← finset.prod_pow_eq_pow_sum] }, end ... ≤ Cq * ((finset.univ : finset (fin c.length)).prod (λ i, Cp)) * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_trans _ (hCq c.length), le_refl, finset.prod_le_prod'], { assume i hi, refine le_trans (mul_le_mul (le_refl _) _ bot_le bot_le) (hCp (c.blocks_fun i)), exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _ }, { refine mul_le_mul (le_refl _) _ bot_le bot_le, exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _ } end ... ≤ Cq * (max Cp 1) ^ n * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_refl], simp only [finset.card_fin, finset.prod_const], refine le_trans (pow_le_pow_of_le_left bot_le (le_max_left Cp 1) c.length) _, apply pow_le_pow (le_max_right Cp 1) c.length_le, end ... = Cq * 4⁻¹ ^ n : begin dsimp [r0], have A : (4 : nnreal) ≠ 0, by norm_num, have B : max Cp 1 ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one (le_max_right Cp 1)), field_simp [A, B], ring_exp end }, refine ⟨r, r_pos, _⟩, rw [← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (∑' (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1)) ≤ (∑' (i : Σ (n : ℕ), composition n), (Cq : ennreal) * a ^ i.1) : ennreal.tsum_le_tsum I ... = (∑' (n : ℕ), (∑' (c : composition n), (Cq : ennreal) * a ^ n)) : ennreal.tsum_sigma' _ ... = (∑' (n : ℕ), ↑(fintype.card (composition n)) * (Cq : ennreal) * a ^ n) : begin congr' 1, ext1 n, rw [tsum_fintype, finset.sum_const, add_monoid.smul_eq_mul, finset.card_univ, mul_assoc] end ... ≤ (∑' (n : ℕ), (2 : ennreal) ^ n * (Cq : ennreal) * a ^ n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply ennreal.mul_le_mul (ennreal.mul_le_mul _ (le_refl _)) (le_refl _), rw composition_card, simp only [nat.cast_bit0, nat.cast_one, nat.cast_pow], apply ennreal.pow_le_pow _ (nat.sub_le n 1), have : (1 : nnreal) ≤ (2 : nnreal), by norm_num, rw ← ennreal.coe_le_coe at this, exact this end ... = (∑' (n : ℕ), (Cq : ennreal) * (2 * a) ^ n) : by { congr' 1, ext1 n, rw mul_pow, ring } ... = (Cq : ennreal) * (1 - 2 * a) ⁻¹ : by rw [ennreal.tsum_mul_left, ennreal.tsum_geometric] ... < ⊤ : by simp [lt_top_iff_ne_top, ennreal.mul_eq_top, two_a] end /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : nnreal) (hr : summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 : (Σ n, composition n) → nnreal)) : (r : ennreal) ≤ (q.comp p).radius := begin apply le_radius_of_bound _ (tsum (λ (i : Σ (n : ℕ), composition n), (nnnorm (comp_along_composition q p i.snd) * r ^ i.fst))), assume n, calc nnnorm (formal_multilinear_series.comp q p n) * r ^ n ≤ ∑' (c : composition n), nnnorm (comp_along_composition q p c) * r ^ n : begin rw [tsum_fintype, ← finset.sum_mul], exact mul_le_mul_of_nonneg_right (nnnorm_sum_le _ _) bot_le end ... ≤ ∑' (i : Σ (n : ℕ), composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst : begin let f : composition n → (Σ (n : ℕ), composition n) := λ c, ⟨n, c⟩, have : function.injective f, by tidy, convert nnreal.tsum_comp_le_tsum_of_inj hr this end end /-! ### Composing analytic functions Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series. See also `comp_partial_sum`. -/ def comp_partial_sum_source (N : ℕ) : finset (Σ n, (fin n) → ℕ) := finset.sigma (finset.range N) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _) @[simp] lemma mem_comp_partial_sum_source_iff (N : ℕ) (i : Σ n, (fin n) → ℕ) : i ∈ comp_partial_sum_source N ↔ i.1 < N ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N := by simp only [comp_partial_sum_source, finset.Ico.mem, fintype.mem_pi_finset, finset.mem_sigma, finset.mem_range] /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source N) : (Σ n, composition n) := begin rcases i with ⟨n, f⟩, rw mem_comp_partial_sum_source_iff at hi, refine ⟨finset.univ.sum f, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩, obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi', exact (hi.2 j).1 end @[simp] lemma comp_change_of_variables_length (N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) : composition.length (comp_change_of_variables N i hi).2 = i.1 := begin rcases i with ⟨k, blocks_fun⟩, dsimp [comp_change_of_variables], simp only [composition.length, map_of_fn, length_of_fn] end lemma comp_change_of_variables_blocks_fun (N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) (j : fin i.1) : (comp_change_of_variables N i hi).2.blocks_fun ⟨j.val, (comp_change_of_variables_length N hi).symm ▸ j.2⟩ = i.2 j := begin rcases i with ⟨n, f⟩, dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables], simp only [map_of_fn, nth_le_of_fn', function.comp_app], apply congr_arg, rw fin.ext_iff end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (N : ℕ) : set (Σ n, composition n) := {i | (i.2.length < N) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)} lemma comp_partial_sum_target_subset_image_comp_partial_sum_source (N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set N) : ∃ j (hj : j ∈ comp_partial_sum_source N), i = comp_change_of_variables N j hj := begin rcases i with ⟨n, c⟩, refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩, { simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi, simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true], exact λ a, c.one_le_blocks' _ }, { dsimp [comp_change_of_variables], rw composition.sigma_eq_iff_blocks_eq, simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'], conv_lhs { rw ← of_fn_nth_le c.blocks } } end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. See also `comp_partial_sum`. -/ def comp_partial_sum_target (N : ℕ) : finset (Σ n, composition n) := set.finite.to_finset $ set.finite_dependent_image (finset.finite_to_set _) (comp_partial_sum_target_subset_image_comp_partial_sum_source N) @[simp] lemma mem_comp_partial_sum_target_iff {N : ℕ} {a : Σ n, composition n} : a ∈ comp_partial_sum_target N ↔ a.2.length < N ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) := by simp [comp_partial_sum_target, comp_partial_sum_target_set] /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ lemma comp_partial_sum_target_tendsto_at_top : tendsto comp_partial_sum_target at_top at_top := begin apply monotone.tendsto_at_top_finset, { assume m n hmn a ha, have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn, tidy }, { rintros ⟨n, c⟩, simp only [mem_comp_partial_sum_target_iff], obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) := finset.bdd_above _, refine ⟨max n c.length + 1, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _), λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩, apply hn, simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] } end /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target N`. This is precisely the motivation for the definition of `comp_partial_sum_target N`. -/ lemma comp_partial_sum (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) = ∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z) := begin -- we expand the composition, using the multilinearity of `q` to expand along each coordinate. suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N), q n (λ (i : fin n), p (r i) (λ j, z)) = ∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z), by simpa only [formal_multilinear_series.partial_sum, continuous_multilinear_map.map_sum_finset] using H, -- rewrite the first sum as a big sum over a sigma type rw ← @finset.sum_sigma _ _ _ _ (finset.range N) (λ (n : ℕ), (fintype.pi_finset (λ (i : fin n), finset.Ico 1 N)) : _) (λ i, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z))), show ∑ i in comp_partial_sum_source N, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z)) = ∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z), -- show that the two sums correspond to each other by reindexing the variables. apply finset.sum_bij (comp_change_of_variables N), -- To conclude, we should show that the correspondance we have set up is indeed a bijection -- between the index sets of the two sums. -- 1 - show that the image belongs to `comp_partial_sum_target N` { rintros ⟨k, blocks_fun⟩ H, rw mem_comp_partial_sum_source_iff at H, simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left, map_of_fn, length_of_fn, true_and, comp_change_of_variables], assume j, simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] }, -- 2 - show that the composition gives the `comp_along_composition` application { rintros ⟨k, blocks_fun⟩ H, apply congr _ (comp_change_of_variables_length N H).symm, intros, rw ← comp_change_of_variables_blocks_fun N H, refl }, -- 3 - show that the map is injective { rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq, obtain rfl : k = k', { have := (comp_change_of_variables_length N H).symm, rwa [heq, comp_change_of_variables_length] at this, }, congr, funext i, calc blocks_fun i = (comp_change_of_variables N _ H).2.blocks_fun _ : (comp_change_of_variables_blocks_fun N H i).symm ... = (comp_change_of_variables N _ H').2.blocks_fun _ : begin apply composition.blocks_fun_congr; try { rw heq }, refl end ... = blocks_fun' i : comp_change_of_variables_blocks_fun N H' i }, -- 4 - show that the map is surjective { assume i hi, apply comp_partial_sum_target_subset_image_comp_partial_sum_source N i, simpa [comp_partial_sum_target] using hi } end end formal_multilinear_series open formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (q.comp p) x := begin /- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks of radius `rf` and `rg`. -/ rcases hg with ⟨rg, Hg⟩, rcases hf with ⟨rf, Hf⟩, /- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/ rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos, hr⟩, /- We will consider `y` which is smaller than `r` and `rf`, and also small enough that `f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let `min (r, rf, δ)` be this new radius.-/ have : continuous_at f x := Hf.analytic_at.continuous_at, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ennreal) (H : 0 < δ), ∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg, { have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos, rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩, exact ⟨δ, δpos, λ z hz, Hδ hz⟩ }, let rf' := min rf δ, have min_pos : 0 < min rf' r, by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self], /- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of radius `min (r, rf', δ)`. -/ refine ⟨min rf' r, _⟩, refine ⟨le_trans (min_le_right rf' r) (formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩, /- Let `y` satisfy `∥y∥ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of `q.comp p` applied to `y`. -/ -- First, check that `y` is small enough so that estimates for `f` and `g` apply. have y_mem : y ∈ emetric.ball (0 : E) rf := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy, have fy_mem : f (x + y) ∈ emetric.ball (f x) rg, { apply hδ, have : y ∈ emetric.ball (0 : E) δ := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy, simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] }, /- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is summable, to get its convergence it suffices to get the convergence along some increasing sequence of sets. We will use the sequence of sets `comp_partial_sum_target n`, along which the sum is exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence to save the day. -/ -- First step: the partial sum of `p` converges to `f (x + y)`. have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)), { have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x = ∑ a in finset.Ico 1 n, p a (λ b, y), { rw eventually_at_top, refine ⟨1, λ n hn, _⟩, symmetry, rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y), finset.sum_eq_sum_Ico_succ_bot hn] }, have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) := (Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds, exact tendsto.congr' L this }, -- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`. have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y))) at_top (𝓝 (g (f (x + y)))), { -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that -- composition passes to the limit under locally uniform convergence. have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x), { refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at, simp only [add_sub_cancel'_right, id.def], exact Hg.continuous_on.continuous_at (mem_nhds_sets (emetric.is_open_ball) fy_mem) }, have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg, by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem, rw [← nhds_within_eq_of_open B₂ emetric.is_open_ball] at A, convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A, simp only [add_sub_cancel'_right] }, -- Third step: the sum over all compositions in `comp_partial_sum_target n` converges to -- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct -- consequence of the second step have C : tendsto (λ n, ∑ i in comp_partial_sum_target n, q.comp_along_composition_multilinear p i.2 (λ j, y)) at_top (𝓝 (g (f (x + y)))), by simpa [comp_partial_sum] using B, -- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the -- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy -- thanks to the summability properties. have D : has_sum (λ i : (Σ n, composition n), q.comp_along_composition_multilinear p i.2 (λ j, y)) (g (f (x + y))), { have cau : cauchy_seq (λ (s : finset (Σ n, composition n)), ∑ i in s, q.comp_along_composition_multilinear p i.2 (λ j, y)), { apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _, simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow], rintros ⟨n, c⟩, calc ∥(comp_along_composition q p c) (λ (j : fin n), y)∥ ≤ ∥comp_along_composition q p c∥ * ∏ j : fin n, ∥y∥ : by apply continuous_multilinear_map.le_op_norm ... ≤ ∥comp_along_composition q p c∥ * (r : ℝ) ^ n : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [finset.prod_const, finset.card_fin], apply pow_le_pow_of_le_left (norm_nonneg _), rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy, have := (le_trans (le_of_lt hy) (min_le_right _ _)), rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this end }, exact tendsto_nhds_of_cauchy_seq_of_subseq cau at_top_ne_bot comp_partial_sum_target_tendsto_at_top C }, -- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of -- the sum over all compositions, by grouping together the compositions of the same -- integer `n`. The convergence of the whole sum therefore implies the converence of the sum -- of `q.comp p n` have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))), { apply D.sigma, assume n, dsimp [formal_multilinear_series.comp], convert has_sum_fintype _, simp only [continuous_multilinear_map.sum_apply], refl }, exact E end /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at /-! ### Associativity of the composition of formal multilinear series In this paragraph, we us prove the associativity of the composition of formal power series. By definition, ``` (r.comp q).comp p n v = ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...)) = ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v) ``` decomposing `r.comp q` in the same way, we get ``` (r.comp q).comp p n v = ∑_{a : composition n} ∑_{b : composition a.length} r b.length (apply_composition q b (apply_composition p a v)) ``` On the other hand, ``` r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v) ``` Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the `i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term, we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`, where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get ``` r.comp (q.comp p) n v = ∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0), ..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))} r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ)) ``` To show that these terms coincide, we need to explain how to reindex the sums to put them in bijection (and then the terms we are summing will correspond to each other). Suppose we have a composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of length 5 of 13. The content of the blocks may be represented as `0011222333344`. Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a` should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13` made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`. This equivalence is called `composition.sigma_equiv_sigma_pi n` below. We start with preliminary results on compositions, of a very specialized nature, then define the equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of composition of formal multilinear series in `formal_multilinear_series.comp_assoc`. -/ namespace composition variable {n : ℕ} /-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in non-dependent terms with lists, requiring that the blocks coincide. -/ lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) : i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks := begin refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩, rcases i with ⟨a, b⟩, rcases j with ⟨a', b'⟩, rintros ⟨h, h'⟩, have H : a = a', by { ext1, exact h }, induction H, congr, ext1, exact h' end /-- Rewriting equality in the dependent type `Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in non-dependent terms with lists, requiring that the lists of blocks coincide. -/ lemma sigma_pi_composition_eq_iff (u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) : u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases u with ⟨a, b⟩, rcases v with ⟨a', b'⟩, dsimp at H, have h : a = a', { ext1, have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) = map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H, simp only [map_of_fn] at this, change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) = of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this, simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this }, induction h, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext i : 2, have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i.1 (by simp [i.2]) = nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i.1 (by simp [i.2]) := nth_le_of_eq H _, rwa [nth_le_of_fn, nth_le_of_fn] at this end /-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`. For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/ def gather (a : composition n) (b : composition a.length) : composition n := { blocks := (a.blocks.split_wrt_composition b).map sum, blocks_pos := begin rw forall_mem_map_iff, intros j hj, suffices H : ∀ i ∈ j, 1 ≤ i, from calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj ... ≤ j.sum : length_le_sum_of_one_le _ H, intros i hi, apply a.one_le_blocks, rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem hj hi, end, blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } } lemma length_gather (a : composition n) (b : composition a.length) : length (a.gather b) = b.length := show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length, by rw [length_map, length_split_wrt_composition] /-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of `a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of `a.gather b`. -/ def sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin (a.gather b).length) : composition ((a.gather b).blocks_fun i) := { blocks := nth_le (a.blocks.split_wrt_composition b) i.val (by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }), blocks_pos := assume i hi, a.blocks_pos (by { rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem (nth_le_mem _ _ _) hi }), blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather] } lemma length_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) : composition.length (composition.sigma_composition_aux a b ⟨i.val, (length_gather a b).symm ▸ i.2⟩) = composition.blocks_fun b i := show list.length (nth_le (split_wrt_composition a.blocks b) i.val _) = blocks_fun b i, by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) (j : fin (blocks_fun b i)) : blocks_fun (sigma_composition_aux a b ⟨i.val, (length_gather a b).symm ▸ i.2⟩) ⟨j.val, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) := show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _, by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl } /-- Auxiliary lemma to prove that the composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a` that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks in `a.gather b`, and the second one to a sum of blocks in the next block of `sigma_composition_aux a b`. This is the content of this lemma. -/ lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length) {i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) : size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i + (size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) := begin induction j with j IHj, { show sum (take ((b.blocks.take i).sum) a.blocks) = sum (take i (map sum (split_wrt_composition a.blocks b))), induction i with i IH, { refl }, { have A : i < b.length := nat.lt_of_succ_lt hi, have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A], have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _, rw [sum_take_succ _ _ B, ← IH A C], have : take (sum (take i b.blocks)) a.blocks = take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks), { rw [take_take, min_eq_left], apply monotone_sum_take _ (nat.le_succ _) }, rw [this, nth_le_map', nth_le_split_wrt_composition, ← take_append_drop (sum (take i b.blocks)) ((take (sum (take (nat.succ i) b.blocks)) a.blocks)), sum_append], congr, rw [take_append_drop] } }, { have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj, have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩), by { convert A, rw ← length_sigma_composition_aux }, have C : size_up_to b i + j < size_up_to b (i + 1), { simp only [size_up_to_succ b hi, add_lt_add_iff_left], exact A }, have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _), have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl, rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B], simp only [sigma_composition_aux, add_assoc, add_left_inj], rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] } end /-- Natural equivalence between `(Σ (a : composition n), composition a.length)` and `(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a change of variables in the proof that composition of formal multilinear series is associative. Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is the direct map in the equiv. Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the inverse map of the equiv. -/ def sigma_equiv_sigma_pi (n : ℕ) : (Σ (a : composition n), composition a.length) ≃ (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) := { to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩, inv_fun := λ i, ⟨ { blocks := (of_fn (λ j, (i.2 j).blocks)).join, blocks_pos := begin simp only [and_imp, mem_join, exists_imp_distrib, forall_mem_of_fn_iff], exact λ i j hj, composition.blocks_pos _ hj end, blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] }, { blocks := of_fn (λ j, (i.2 j).length), blocks_pos := forall_mem_of_fn_iff.2 (λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)), blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩, left_inv := begin -- the fact that we have a left inverse is essentially `join_split_wrt_composition`, -- but we need to massage it to take care of the dependent setting. rintros ⟨a, b⟩, rw sigma_composition_eq_iff, dsimp, split, { have A := length_map list.sum (split_wrt_composition a.blocks b), conv_rhs { rw [← join_split_wrt_composition a.blocks b, ← of_fn_nth_le (split_wrt_composition a.blocks b)] }, congr, { exact A }, { exact (fin.heq_fun_iff A).2 (λ i, rfl) } }, { have B : composition.length (composition.gather a b) = list.length b.blocks := composition.length_gather _ _, conv_rhs { rw [← of_fn_nth_le b.blocks] }, congr' 1, { exact B }, { apply (fin.heq_fun_iff B).2 (λ i, _), rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)] } } end, right_inv := begin -- the fact that we have a right inverse is essentially `split_wrt_composition_join`, -- but we need to massage it to take care of the dependent setting. rintros ⟨c, d⟩, have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks, by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun], rw sigma_pi_composition_eq_iff, dsimp, congr, { ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] }, { rw fin.heq_fun_iff, { assume i, dsimp [composition.sigma_composition_aux], rw [nth_le_of_eq (split_wrt_composition_join _ _ _)], { simp only [nth_le_of_fn'] }, { simp only [map_of_fn] } }, { congr, ext1, dsimp [composition.gather], rwa split_wrt_composition_join, simp only [map_of_fn] } } end } end composition namespace formal_multilinear_series open composition theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : (r.comp q).comp p = r.comp (q.comp p) := begin ext n v, /- First, rewrite the two compositions appearing in the theorem as two sums over complicated sigma types, as in the description of the proof above. -/ let f : (Σ (a : composition n), composition a.length) → H := λ ⟨a, b⟩, r b.length (apply_composition q b (apply_composition p a v)), let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H := λ ⟨c, d⟩, r c.length (λ (i : fin c.length), q (d i).length (apply_composition p (d i) (v ∘ c.embedding i))), suffices A : ∑ c, f c = ∑ c, g c, { dsimp [formal_multilinear_series.comp], simp only [continuous_multilinear_map.sum_apply, comp_along_composition_apply], rw ← @finset.sum_sigma _ _ _ _ (finset.univ : finset (composition n)) _ f, dsimp [apply_composition], simp only [continuous_multilinear_map.sum_apply, comp_along_composition_apply, continuous_multilinear_map.map_sum], rw ← @finset.sum_sigma _ _ _ _ (finset.univ : finset (composition n)) _ g, exact A }, /- Now, we use `composition.sigma_equiv_sigma_pi n` to change variables in the second sum, and check that we get exactly the same sums. -/ rw ← finset.sum_equiv (sigma_equiv_sigma_pi n), /- To check that we have the same terms, we should check that we apply the same component of `r`, and the same component of `q`, and the same component of `p`, to the same coordinate of `v`. This is true by definition, but at each step one needs to convince Lean that the types one considers are the same, using a suitable congruence lemma to avoid dependent type issues. This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/ apply finset.sum_congr rfl, rintros ⟨a, b⟩ _, dsimp [f, g, sigma_equiv_sigma_pi], -- check that the `r` components are the same. Based on `composition.length_gather` apply r.congr (composition.length_gather a b).symm, intros i hi1 hi2, -- check that the `q` components are the same. Based on `length_sigma_composition_aux` apply q.congr (length_sigma_composition_aux a b _).symm, intros j hj1 hj2, -- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux` apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm, intros k hk1 hk2, -- finally, check that the coordinates of `v` one is using are the same. Based on -- `size_up_to_size_up_to_add`. refine congr_arg v (fin.eq_of_veq _), dsimp [composition.embedding], rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc], end end formal_multilinear_series
472651a0b65d85af31b00eaff5300cf8e29d2a69
ce89339993655da64b6ccb555c837ce6c10f9ef4
/zeptometer/tlc/newmans_lemma.lean
23663b4ce6d846d6a6780a4f85adeab91a3000d5
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
3,483
lean
-- Reflexive transitive closure inductive rtc {α : Type} (r : α → α → Prop) : α → α → Prop | base : ∀ a : α, rtc a a | next : ∀ a b c : α, rtc a b → r b c → rtc a c lemma rtc_reflexive {α : Type} {r : α → α → Prop} : ∀a : α, rtc r a a := assume a, rtc.base r a lemma rtc_left_next {α : Type} {r : α → α → Prop} : ∀{a b c: α}, r a b → rtc r b c → rtc r a c := begin intros a b c r_a_b rtc_r_b_c, induction rtc_r_b_c, case rtc.base : x { apply rtc.next, apply rtc.base, assumption }, case rtc.next : b x c rtc_r_b_x r_x_c { apply rtc.next, apply rtc_r_b_c_ih, assumption, assumption } end lemma rtc_transitive {α : Type} {r : α → α → Prop} : ∀{a b c: α}, rtc r a b → rtc r b c → rtc r a c := begin intros a b c rtc_r_a_b rtc_r_b_c, induction rtc_r_a_b, case rtc.base : x { assumption }, case rtc.next : a x b rtc_r_a_x r_x_b { apply rtc_r_a_b_ih, apply rtc_left_next, assumption, assumption } end -- Main Lemma definition weakly_confluent {α : Type} (lt: α → α → Prop) : Prop := ∀ {a b c : α}, lt b a → lt c a → ∃ d : α, rtc lt d b ∧ rtc lt d c definition confluent {α : Type} (lt: α → α → Prop) : Prop := ∀ {a b c : α}, rtc lt b a → rtc lt c a → ∃ d : α, rtc lt d b ∧ rtc lt d c lemma newmans_lemma {α : Type} {r : α → α → Prop} (wc : weakly_confluent r) (wf : well_founded r) : confluent r := well_founded.fix wf begin intros a ih b c r_b_a r_c_b, cases r_b_a, case rtc.base { existsi c, constructor, assumption, apply rtc.base }, -- main case case rtc.next : x rtc_r_b_x r_x_a { cases r_c_b, case rtc.base { existsi b, constructor, apply rtc.base, apply rtc.next, assumption, assumption }, -- main case case rtc.next : y rtc_r_c_y r_y_a { -- step 1: Get d1 from weak confluence have d1exists : ∃d1, rtc r d1 x ∧ rtc r d1 y := wc r_x_a r_y_a, cases d1exists with d1 rtc_r_d1_xandy, cases rtc_r_d1_xandy with rtc_r_d1_x rtc_r_d1_y, -- step 2: Get d2 from induction hypothesis have d2exists : ∃d2, rtc r d2 b ∧ rtc r d2 d1 := ih x r_x_a rtc_r_b_x rtc_r_d1_x, cases d2exists with d2 rtc_r_d2_bandd1, cases rtc_r_d2_bandd1 with rtc_r_d2_b rtc_r_d2_d1, have rtc_r_d2_y : rtc r d2 y := rtc_transitive rtc_r_d2_d1 rtc_r_d1_y, -- step 3: Get d3 from induction hypothesis have d3exists : ∃d3, rtc r d3 c ∧ rtc r d3 d2 := ih y r_y_a rtc_r_c_y rtc_r_d2_y, cases d3exists with d3 rtc_r_d3_candd2, cases rtc_r_d3_candd2 with rtc_r_d3_c rtc_r_d3_d2, -- step 4: Show d3 is the confluent point existsi d3, split, { exact rtc_transitive rtc_r_d3_d2 rtc_r_d2_b, }, { assumption } }} end
ea9a36f7c0a5b9958fb0defaf95d9fe73f5d4f72
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/490.lean
0023101363e26de50e91a4fe86a14f1f7b1d4072
[ "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
48
lean
namespace Foo def _root_.bar := 1 -- ok end Foo
0370d5f5315687b9f75ebd556007988aaa44cbde
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/group/min_max.lean
adefb7abbb2ca60eb2dfbd63a77aea1a88d4353e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,191
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.order.group.abs import algebra.order.monoid.min_max /-! # `min` and `max` in linearly ordered groups. -/ section variables {α : Type*} [group α] [linear_order α] [covariant_class α α (*) (≤)] @[simp, to_additive] lemma max_one_div_max_inv_one_eq_self (a : α) : max a 1 / max a⁻¹ 1 = a := by { rcases le_total a 1 with h|h; simp [h] } alias max_zero_sub_max_neg_zero_eq_self ← max_zero_sub_eq_self end section linear_ordered_comm_group variables {α : Type*} [linear_ordered_comm_group α] {a b c : α} @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] end linear_ordered_comm_group section linear_ordered_add_comm_group variables {α : Type*} [linear_ordered_add_comm_group α] {a b c : α} lemma max_sub_max_le_max (a b c d : α) : max a b - max c d ≤ max (a - c) (b - d) := begin simp only [sub_le_iff_le_add, max_le_iff], split, calc a = a - c + c : (sub_add_cancel a c).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_left _ _) (le_max_left _ _), calc b = b - d + d : (sub_add_cancel b d).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_right _ _) (le_max_right _ _) end lemma abs_max_sub_max_le_max (a b c d : α) : |max a b - max c d| ≤ max (|a - c|) (|b - d|) := begin refine abs_sub_le_iff.2 ⟨_, _⟩, { exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) }, { rw [abs_sub_comm a c, abs_sub_comm b d], exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) } end lemma abs_min_sub_min_le_max (a b c d : α) : |min a b - min c d| ≤ max (|a - c|) (|b - d|) := by simpa only [max_neg_neg, neg_sub_neg, abs_sub_comm] using abs_max_sub_max_le_max (-a) (-b) (-c) (-d) lemma abs_max_sub_max_le_abs (a b c : α) : |max a c - max b c| ≤ |a - b| := by simpa only [sub_self, abs_zero, max_eq_left (abs_nonneg _)] using abs_max_sub_max_le_max a c b c end linear_ordered_add_comm_group
9b85268059704d1d7839487652572c7a7e9705ba
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/norm_cast.lean
1749375865d55778d997314d203d90b1d8b6e4b1
[ "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
26,441
lean
/- Copyright (c) 2019 Paul-Nicolas Madelaine. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul-Nicolas Madelaine, Robert Y. Lewis Normalizing casts inside expressions. -/ import tactic.converter.interactive import tactic.hint /-! # A tactic for normalizing casts inside expressions This tactic normalizes casts inside expressions. It can be thought of as a call to the simplifier with a specific set of lemmas to move casts upwards in the expression. It has special handling of numerals and a simple heuristic to help moving casts "past" binary operators. Contrary to simp, it should be safe to use as a non-terminating tactic. The algorithm implemented here is described in the paper <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. ## Important definitions * `tactic.interactive.norm_cast` * `tactic.interactive.push_cast` * `tactic.interactive.exact_mod_cast` * `tactic.interactive.apply_mod_cast` * `tactic.interactive.rw_mod_cast` * `tactic.interactive.assumption_mod_cast` -/ setup_tactic_parser namespace tactic /-- Runs `mk_instance` with a time limit. This is a work around to the fact that in some cases mk_instance times out instead of failing, for example: `has_lift_t ℤ ℕ` `mk_instance_fast` is used when we assume the type class search should end instantly. -/ meta def mk_instance_fast (e : expr) (timeout := 1000) : tactic expr := try_for timeout (mk_instance e) end tactic namespace norm_cast open tactic expr declare_trace norm_cast /-- Output a trace message if `trace.norm_cast` is enabled. -/ meta def trace_norm_cast {α} [has_to_tactic_format α] (msg : string) (a : α) : tactic unit := when_tracing `norm_cast $ do a ← pp a, trace ("[norm_cast] " ++ msg ++ a : format) mk_simp_attribute push_cast "The `push_cast` simp attribute uses `norm_cast` lemmas to move casts toward the leaf nodes of the expression." /-- `label` is a type used to classify `norm_cast` lemmas. * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes -/ @[derive [decidable_eq, has_reflect, inhabited]] inductive label | elim : label | move : label | squash : label namespace label /-- Convert `label` into `string`. -/ protected def to_string : label → string | elim := "elim" | move := "move" | squash := "squash" instance : has_to_string label := ⟨label.to_string⟩ instance : has_repr label := ⟨label.to_string⟩ meta instance : has_to_format label := ⟨λ l, l.to_string⟩ /-- Convert `string` into `label`. -/ def of_string : string -> option label | "elim" := some elim | "move" := some move | "squash" := some squash | _ := none end label open label /-- Count how many coercions are at the top of the expression. -/ meta def count_head_coes : expr → ℕ | `(coe %%e) := count_head_coes e + 1 | `(coe_sort %%e) := count_head_coes e + 1 | `(coe_fn %%e) := count_head_coes e + 1 | _ := 0 /-- Count how many coercions are inside the expression, including the top ones. -/ meta def count_coes : expr → tactic ℕ | `(coe %%e) := (+1) <$> count_coes e | `(coe_sort %%e) := (+1) <$> count_coes e | `(coe_fn %%e) := (+1) <$> count_coes e | (app `(coe_fn %%e) x) := (+) <$> count_coes x <*> (+1) <$> count_coes e | (expr.lam n bi t e) := do l ← mk_local' n bi t, count_coes $ e.instantiate_var l | e := do as ← e.get_simp_args, list.sum <$> as.mmap count_coes /-- Count how many coercions are inside the expression, excluding the top ones. -/ private meta def count_internal_coes (e : expr) : tactic ℕ := do ncoes ← count_coes e, pure $ ncoes - count_head_coes e /-- Classifies a declaration of type `ty` as a `norm_cast` rule. -/ meta def classify_type (ty : expr) : tactic label := do (_, ty) ← open_pis ty, (lhs, rhs) ← match ty with | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | _ := fail "norm_cast: lemma must be = or ↔" end, lhs_coes ← count_coes lhs, when (lhs_coes = 0) $ fail "norm_cast: badly shaped lemma, lhs must contain at least one coe", let lhs_head_coes := count_head_coes lhs, lhs_internal_coes ← count_internal_coes lhs, let rhs_head_coes := count_head_coes rhs, rhs_internal_coes ← count_internal_coes rhs, if lhs_head_coes = 0 then return elim else if lhs_head_coes = 1 then do when (rhs_head_coes ≠ 0) $ fail "norm_cast: badly shaped lemma, rhs can't start with coe", if rhs_internal_coes = 0 then return squash else return move else if rhs_head_coes < lhs_head_coes then do return squash else do fail "norm_cast: badly shaped shaped squash lemma, rhs must have fewer head coes than lhs" /-- The cache for `norm_cast` attribute stores three `simp_lemma` objects. -/ meta structure norm_cast_cache := (up : simp_lemmas) (down : simp_lemmas) (squash : simp_lemmas) /-- Empty `norm_cast_cache`. -/ meta def empty_cache : norm_cast_cache := { up := simp_lemmas.mk, down := simp_lemmas.mk, squash := simp_lemmas.mk, } meta instance : inhabited norm_cast_cache := ⟨empty_cache⟩ /-- `add_elim cache e` adds `e` as an `elim` lemma to `cache`. -/ meta def add_elim (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_up ← simp_lemmas.add cache.up e, return { up := new_up, down := cache.down, squash := cache.squash, } /-- `add_move cache e` adds `e` as a `move` lemma to `cache`. -/ meta def add_move (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do ty ← infer_type e, new_up ← cache.up.add e tt, new_down ← simp_lemmas.add cache.down e, return { up := new_up, down := new_down, squash := cache.squash, } /-- `add_squash cache e` adds `e` as an `squash` lemma to `cache`. -/ meta def add_squash (cache : norm_cast_cache) (e : expr) : tactic norm_cast_cache := do new_squash ← simp_lemmas.add cache.squash e, new_down ← simp_lemmas.add cache.down e, return { up := cache.up, down := new_down, squash := new_squash, } /-- The type of the `norm_cast` attribute. The optional label is used to overwrite the classifier. -/ meta def norm_cast_attr_ty : Type := user_attribute norm_cast_cache (option label) /-- Efficient getter for the `@[norm_cast]` attribute parameter that does not call `eval_expr`. See Note [user attribute parameters]. -/ meta def get_label_param (attr : norm_cast_attr_ty) (decl : name) : tactic (option label) := do p ← attr.get_param_untyped decl, match p with | `(none) := pure none | `(some label.elim) := pure label.elim | `(some label.move) := pure label.move | `(some label.squash) := pure label.squash | _ := fail p end /-- `add_lemma cache decl` infers the proper `norm_cast` attribute for `decl` and adds it to `cache`. -/ meta def add_lemma (attr : norm_cast_attr_ty) (cache : norm_cast_cache) (decl : name) : tactic norm_cast_cache := do e ← mk_const decl, param ← get_label_param attr decl, l ← param <|> (infer_type e >>= classify_type), match l with | elim := add_elim cache e | move := add_move cache e | squash := add_squash cache e end -- special lemmas to handle the ≥, > and ≠ operators private lemma ge_from_le {α} [has_le α] : ∀ (x y : α), x ≥ y ↔ y ≤ x := λ _ _, iff.rfl private lemma gt_from_lt {α} [has_lt α] : ∀ (x y : α), x > y ↔ y < x := λ _ _, iff.rfl private lemma ne_from_not_eq {α} : ∀ (x y : α), x ≠ y ↔ ¬(x = y) := λ _ _, iff.rfl /-- `mk_cache names` creates a `norm_cast_cache`. It infers the proper `norm_cast` attributes for names in `names`, and collects the lemmas attributed with specific `norm_cast` attributes. -/ meta def mk_cache (attr : thunk norm_cast_attr_ty) (names : list name) : tactic norm_cast_cache := do -- names has the declarations in reverse order cache ← names.mfoldr (λ name cache, add_lemma (attr ()) cache name) empty_cache, --some special lemmas to handle binary relations let up := cache.up, up ← up.add_simp ``ge_from_le, up ← up.add_simp ``gt_from_lt, up ← up.add_simp ``ne_from_not_eq, let down := cache.down, down ← down.add_simp ``coe_coe, pure { up := up, down := down, squash := cache.squash } /-- The `norm_cast` attribute. -/ @[user_attribute] meta def norm_cast_attr : user_attribute norm_cast_cache (option label) := { name := `norm_cast, descr := "attribute for norm_cast", parser := (do some l ← (label.of_string ∘ to_string) <$> ident, return l) <|> return none, after_set := some (λ decl prio persistent, do param ← get_label_param norm_cast_attr decl, match param with | some l := when (l ≠ elim) $ simp_attr.push_cast.set decl () tt | none := do e ← mk_const decl, ty ← infer_type e, l ← classify_type ty, norm_cast_attr.set decl l persistent prio end), before_unset := some $ λ _ _, tactic.skip, cache_cfg := { mk_cache := mk_cache norm_cast_attr, dependencies := [] } } /-- Classify a declaration as a `norm_cast` rule. -/ meta def make_guess (decl : name) : tactic label := do e ← mk_const decl, ty ← infer_type e, classify_type ty /-- Gets the `norm_cast` classification label for a declaration. Applies the override specified on the attribute, if necessary. -/ meta def get_label (decl : name) : tactic label := do param ← get_label_param norm_cast_attr decl, param <|> make_guess decl end norm_cast namespace tactic.interactive open norm_cast /-- `push_cast` rewrites the expression to move casts toward the leaf nodes. For example, `↑(a + b)` will be written to `↑a + ↑b`. Equivalent to `simp only with push_cast`. Can also be used at hypotheses. `push_cast` can also be used at hypotheses and with extra simp rules. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` -/ meta def push_cast (hs : parse tactic.simp_arg_list) (l : parse location) : tactic unit := tactic.interactive.simp none none tt hs [`push_cast] l end tactic.interactive namespace norm_cast open tactic expr /-- Prove `a = b` using the given simp set. -/ meta def prove_eq_using (s : simp_lemmas) (a b : expr) : tactic expr := do (a', a_a', _) ← simplify s [] a {fail_if_unchanged := ff}, (b', b_b', _) ← simplify s [] b {fail_if_unchanged := ff}, on_exception (trace_norm_cast "failed: " (to_expr ``(%%a' = %%b') >>= pp)) $ is_def_eq a' b' reducible, b'_b ← mk_eq_symm b_b', mk_eq_trans a_a' b'_b /-- Prove `a = b` by simplifying using move and squash lemmas. -/ meta def prove_eq_using_down (a b : expr) : tactic expr := do cache ← norm_cast_attr.get_cache, trace_norm_cast "proving: " (to_expr ``(%%a = %%b) >>= pp), prove_eq_using cache.down a b /-- This is the main heuristic used alongside the elim and move lemmas. The goal is to help casts move past operators by adding intermediate casts. An expression of the shape: op (↑(x : α) : γ) (↑(y : β) : γ) is rewritten to: op (↑(↑(x : α) : β) : γ) (↑(y : β) : γ) when (↑(↑(x : α) : β) : γ) = (↑(x : α) : γ) can be proven with a squash lemma -/ meta def splitting_procedure : expr → tactic (expr × expr) | (app (app op x) y) := (do `(@coe %%α %%δ %%coe1 %%xx) ← return x, `(@coe %%β %%γ %%coe2 %%yy) ← return y, success_if_fail $ is_def_eq α β, is_def_eq δ γ, (do coe3 ← mk_app `has_lift_t [α, β] >>= mk_instance_fast, new_x ← to_expr ``(@coe %%β %%δ %%coe2 (@coe %%α %%β %%coe3 %%xx)), let new_e := app (app op new_x) y, eq_x ← prove_eq_using_down x new_x, pr ← mk_congr_arg op eq_x, pr ← mk_congr_fun pr y, return (new_e, pr) ) <|> (do coe3 ← mk_app `has_lift_t [β, α] >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%δ %%coe1 (@coe %%β %%α %%coe3 %%yy)), let new_e := app (app op x) new_y, eq_y ← prove_eq_using_down y new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_one.one %%β %%h1) ← return y, h2 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@coe %%α %%β %%coe1 %%xx) ← return x, `(@has_zero.zero %%β %%h1) ← return y, h2 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_y ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h2)), eq_y ← prove_eq_using_down y new_y, let new_e := app (app op x) new_y, pr ← mk_congr_arg (app op x) eq_y, return (new_e, pr) ) <|> (do `(@has_one.one %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_one %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_one.one %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) <|> (do `(@has_zero.zero %%β %%h1) ← return x, `(@coe %%α %%β %%coe1 %%xx) ← return y, h1 ← to_expr ``(has_zero %%α) >>= mk_instance_fast, new_x ← to_expr ``(@coe %%α %%β %%coe1 (@has_zero.zero %%α %%h1)), eq_x ← prove_eq_using_down x new_x, let new_e := app (app op new_x) y, pr ← mk_congr_arg (lam `x binder_info.default β (app (app op (var 0)) y)) eq_x, return (new_e, pr) ) | _ := failed /-- Discharging function used during simplification in the "squash" step. TODO: norm_cast takes a list of expressions to use as lemmas for the discharger TODO: a tactic to print the results the discharger fails to proove -/ private meta def prove : tactic unit := assumption /-- Core rewriting function used in the "squash" step, which moves casts upwards and eliminates them. It tries to rewrite an expression using the elim and move lemmas. On failure, it calls the splitting procedure heuristic. -/ meta def upward_and_elim (s : simp_lemmas) (e : expr) : tactic (expr × expr) := (do r ← mcond (is_prop e) (return `iff) (return `eq), (new_e, pr) ← s.rewrite e prove r, pr ← match r with | `iff := mk_app `propext [pr] | _ := return pr end, return (new_e, pr) ) <|> splitting_procedure e /-! The following auxiliary functions are used to handle numerals. -/ /-- If possible, rewrite `(n : α)` to `((n : ℕ) : α)` where `n` is a numeral and `α ≠ ℕ`. Returns a pair of the new expression and proof that they are equal. -/ meta def numeral_to_coe (e : expr) : tactic (expr × expr) := do α ← infer_type e, success_if_fail $ is_def_eq α `(ℕ), n ← e.to_nat, h1 ← mk_app `has_lift_t [`(ℕ), α] >>= mk_instance_fast, let new_e : expr := reflect n, new_e ← to_expr ``(@coe ℕ %%α %%h1 %%new_e), pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- If possible, rewrite `((n : ℕ) : α)` to `(n : α)` where `n` is a numeral. Returns a pair of the new expression and proof that they are equal. -/ meta def coe_to_numeral (e : expr) : tactic (expr × expr) := do `(@coe ℕ %%α %%h1 %%e') ← return e, n ← e'.to_nat, -- replace e' by normalized numeral is_def_eq (reflect n) e' reducible, let e := e.app_fn (reflect n), new_e ← expr.of_nat α n, pr ← prove_eq_using_down e new_e, return (new_e, pr) /-- A local variant on `simplify_top_down`. -/ private meta def simplify_top_down' {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e /-- The core simplification routine of `norm_cast`. -/ meta def derive (e : expr) : tactic (expr × expr) := do cache ← norm_cast_attr.get_cache, e ← instantiate_mvars e, let cfg : simp_config := { zeta := ff, beta := ff, eta := ff, proj := ff, iota := ff, iota_eqn := ff, fail_if_unchanged := ff }, let e0 := e, -- step 1: pre-processing of numerals ((), e1, pr1) ← simplify_top_down' () (λ _ e, prod.mk () <$> numeral_to_coe e) e0 cfg, trace_norm_cast "after numeral_to_coe: " e1, -- step 2: casts are moved upwards and eliminated ((), e2, pr2) ← simplify_bottom_up () (λ _ e, prod.mk () <$> upward_and_elim cache.up e) e1 cfg, trace_norm_cast "after upward_and_elim: " e2, -- step 3: casts are squashed (e3, pr3, _) ← simplify cache.squash [] e2 cfg, trace_norm_cast "after squashing: " e3, -- step 4: post-processing of numerals ((), e4, pr4) ← simplify_top_down' () (λ _ e, prod.mk () <$> coe_to_numeral e) e3 cfg, trace_norm_cast "after coe_to_numeral: " e4, let new_e := e4, guard (¬ new_e =ₐ e), pr ← mk_eq_trans pr1 pr2, pr ← mk_eq_trans pr pr3, pr ← mk_eq_trans pr pr4, return (new_e, pr) /-- A small variant of `push_cast` suited for non-interactive use. `derive_push_cast extra_lems e` returns an expression `e'` and a proof that `e = e'`. -/ meta def derive_push_cast (extra_lems : list simp_arg_type) (e : expr) : tactic (expr × expr) := do (s, _) ← mk_simp_set tt [`push_cast] extra_lems, (e, prf, _) ← simplify (s.erase [`int.coe_nat_succ]) [] e {fail_if_unchanged := ff}, return (e, prf) end norm_cast namespace tactic open expr norm_cast /-- `aux_mod_cast e` runs `norm_cast` on `e` and returns the result. If `include_goal` is true, it also normalizes the goal. -/ meta def aux_mod_cast (e : expr) (include_goal : bool := tt) : tactic expr := match e with | local_const _ lc _ _ := do e ← get_local lc, replace_at derive [e] include_goal, get_local lc | e := do t ← infer_type e, e ← assertv `this t e, replace_at derive [e] include_goal, get_local `this end /-- `exact_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to use `e` to close the goal. -/ meta def exact_mod_cast (e : expr) : tactic unit := decorate_error "exact_mod_cast failed:" $ do new_e ← aux_mod_cast e, exact new_e /-- `apply_mod_cast e` runs `norm_cast` on the goal and `e`, and tries to apply `e`. -/ meta def apply_mod_cast (e : expr) : tactic (list (name × expr)) := decorate_error "apply_mod_cast failed:" $ do new_e ← aux_mod_cast e, apply new_e /-- `assumption_mod_cast` runs `norm_cast` on the goal. For each local hypothesis `h`, it also normalizes `h` and tries to use that to close the goal. -/ meta def assumption_mod_cast : tactic unit := decorate_error "assumption_mod_cast failed:" $ do let cfg : simp_config := { fail_if_unchanged := ff, canonize_instances := ff, canonize_proofs := ff, proj := ff }, replace_at derive [] tt, ctx ← local_context, try_lst $ ctx.map (λ h, aux_mod_cast h ff >>= tactic.exact) end tactic namespace tactic.interactive open tactic norm_cast /-- Normalize casts at the given locations by moving them "upwards". As opposed to simp, norm_cast can be used without necessarily closing the goal. -/ meta def norm_cast (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← replace_at derive ns loc.include_goal | fail "norm_cast failed to simplify", when loc.include_goal $ try tactic.reflexivity, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Rewrite with the given rules and normalize casts between steps. -/ meta def rw_mod_cast (rs : parse rw_rules) (loc : parse location) : tactic unit := decorate_error "rw_mod_cast failed:" $ do let cfg_norm : simp_config := {}, let cfg_rw : rewrite_cfg := {}, ns ← loc.get_locals, monad.mapm' (λ r : rw_rule, do save_info r.pos, replace_at derive ns loc.include_goal, rw ⟨[r], none⟩ loc {} ) rs.rules, replace_at derive ns loc.include_goal, skip /-- Normalize the goal and the given expression, then close the goal with exact. -/ meta def exact_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr e <|> do { ty ← target, e ← i_to_expr_strict ``(%%e : %%ty), pty ← pp ty, ptgt ← pp e, fail ("exact_mod_cast failed, expression type not directly " ++ "inferrable. Try:\n\nexact_mod_cast ...\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, tactic.exact_mod_cast e /-- Normalize the goal and the given expression, then apply the expression to the goal. -/ meta def apply_mod_cast (e : parse texpr) : tactic unit := do e ← i_to_expr_for_apply e, concat_tags $ tactic.apply_mod_cast e /-- Normalize the goal and every expression in the local context, then close the goal with assumption. -/ meta def assumption_mod_cast : tactic unit := tactic.assumption_mod_cast end tactic.interactive namespace conv.interactive open conv open norm_cast (derive) /-- the converter version of `norm_cast' -/ meta def norm_cast : conv unit := replace_lhs derive end conv.interactive -- TODO: move this elsewhere? @[norm_cast] lemma ite_cast {α β} [has_lift_t α β] {c : Prop} [decidable c] {a b : α} : ↑(ite c a b) = ite c (↑a : β) (↑b : β) := by by_cases h : c; simp [h] @[norm_cast] lemma dite_cast {α β} [has_lift_t α β] {c : Prop} [decidable c] {a : c → α} {b : ¬ c → α} : ↑(dite c a b) = dite c (λ h, (↑(a h) : β)) (λ h, (↑(b h) : β)) := by by_cases h : c; simp [h] add_hint_tactic "norm_cast at *" /-- The `norm_cast` family of tactics is used to normalize casts inside expressions. It is basically a simp tactic with a specific set of lemmas to move casts upwards in the expression. Therefore it can be used more safely as a non-terminating tactic. It also has special handling of numerals. For instance, given an assumption ```lean a b : ℤ h : ↑a + ↑b < (10 : ℚ) ``` writing `norm_cast at h` will turn `h` into ```lean h : a + b < 10 ``` You can also use `exact_mod_cast`, `apply_mod_cast`, `rw_mod_cast` or `assumption_mod_cast`. Writing `exact_mod_cast h` and `apply_mod_cast h` will normalize the goal and `h` before using `exact h` or `apply h`. Writing `assumption_mod_cast` will normalize the goal and for every expression `h` in the context it will try to normalize `h` and use `exact h`. `rw_mod_cast` acts like the `rw` tactic but it applies `norm_cast` between steps. `push_cast` rewrites the expression to move casts toward the leaf nodes. This uses `norm_cast` lemmas in the forward direction. For example, `↑(a + b)` will be written to `↑a + ↑b`. It is equivalent to `simp only with push_cast`. It can also be used at hypotheses with `push_cast at h` and with extra simp lemmas with `push_cast [int.add_zero]`. ```lean example (a b : ℕ) (h1 : ((a + b : ℕ) : ℤ) = 10) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) : ((a + b : ℕ) : ℤ) = 10 := begin push_cast, push_cast at h1, push_cast [int.add_zero] at h2, end ``` The implementation and behavior of the `norm_cast` family is described in detail at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast", category := doc_category.tactic, decl_names := [``tactic.interactive.norm_cast, ``tactic.interactive.rw_mod_cast, ``tactic.interactive.apply_mod_cast, ``tactic.interactive.assumption_mod_cast, ``tactic.interactive.exact_mod_cast, ``tactic.interactive.push_cast], tags := ["coercions", "simplification"] } /-- The `norm_cast` attribute should be given to lemmas that describe the behaviour of a coercion in regard to an operator, a relation, or a particular function. It only concerns equality or iff lemmas involving `↑`, `⇑` and `↥`, describing the behavior of the coercion functions. It does not apply to the explicit functions that define the coercions. Examples: ```lean @[norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n @[norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 @[norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n @[norm_cast] theorem coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n @[norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m @[norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n @[norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n @[norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 ``` Lemmas tagged with `@[norm_cast]` are classified into three categories: `move`, `elim`, and `squash`. They are classified roughly as follows: * elim lemma: LHS has 0 head coes and ≥ 1 internal coe * move lemma: LHS has 1 head coe and 0 internal coes, RHS has 0 head coes and ≥ 1 internal coes * squash lemma: LHS has ≥ 1 head coes and 0 internal coes, RHS has fewer head coes `norm_cast` uses `move` and `elim` lemmas to factor coercions toward the root of an expression and to cancel them from both sides of an equation or relation. It uses `squash` lemmas to clean up the result. Occasionally you may want to override the automatic classification. You can do this by giving an optional `elim`, `move`, or `squash` parameter to the attribute. ```lean @[simp, norm_cast elim] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] ``` Don't do this unless you understand what you are doing. A full description of the tactic, and the use of each lemma category, can be found at <https://lean-forward.github.io/norm_cast/norm_cast.pdf>. -/ add_tactic_doc { name := "norm_cast attributes", category := doc_category.attr, decl_names := [``norm_cast.norm_cast_attr], tags := ["coercions", "simplification"] } -- Lemmas defined in core. attribute [norm_cast] int.nat_abs_of_nat int.coe_nat_sub int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_add -- Lemmas about nat.succ need to get a low priority, so that they are tried last. -- This is because `nat.succ _` matches `1`, `3`, `x+1`, etc. -- Rewriting would then produce really wrong terms. attribute [norm_cast, priority 500] int.coe_nat_succ
4596836f97687861a7e3fd128b7489bf867419dc
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/list/prod_monoid.lean
76ed42f9a87f6f7ff3db6bd2dd9056cad5e5705d
[ "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
1,140
lean
/- Copyright (c) 2021 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best -/ import algebra.group_power.basic import data.list.big_operators /-! # Products / sums of lists of terms of a monoid This file provides basic results about `list.prod` (definition in `data.list.defs`) in a monoid. It is in a separate file so that `data.list.big_operators` does not depend on `algebra.group_power.basic`. -/ open nat namespace list universes u v variables {α : Type u} @[simp, priority 500, to_additive] theorem prod_repeat [monoid α] (a : α) (n : ℕ) : (repeat a n).prod = a ^ n := begin induction n with n ih, { rw pow_zero, refl }, { rw [list.repeat_succ, list.prod_cons, ih, pow_succ] } end @[to_additive] lemma prod_le_of_forall_le [ordered_comm_monoid α] (l : list α) (n : α) (h : ∀ (x ∈ l), x ≤ n) : l.prod ≤ n ^ l.length := begin induction l with y l IH, { simp }, { specialize IH (λ x hx, h x (mem_cons_of_mem _ hx)), have hy : y ≤ n := h y (mem_cons_self _ _), simpa [pow_succ] using mul_le_mul' hy IH } end end list
0b855e287855d324e6ac0715bb12680bbf9664ce
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/ring2.lean
48ee2984ab655c787e92aa53ce4d80668dc28bbc
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
20,643
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 tactic.ring data.num.lemmas data.tree import tactic.converter.interactive /-! # ring2 An experimental variant on the `ring` tactic that uses computational reflection instead of proof generation. Useful for kernel benchmarking. -/ namespace tree /-- `(reflect' t u α)` quasiquotes a tree `(t: tree expr)` of quoted values of type `α` at level `u` into an `expr` which reifies to a `tree α` containing the reifications of the `expr`s from the original `t`. -/ protected meta def reflect' (u : level) (α : expr) : tree expr → expr | tree.nil := (expr.const ``tree.nil [u] : expr) α | (tree.node a t₁ t₂) := (expr.const ``tree.node [u] : expr) α a t₁.reflect' t₂.reflect' /-- Returns an element indexed by `n`, or zero if `n` isn't a valid index. See `tree.get`. -/ protected def get_or_zero {α} [has_zero α] (t : tree α) (n : pos_num) : α := t.get_or_else n 0 end tree namespace tactic.ring2 /-- A reflected/meta representation of an expression in a commutative semiring. This representation is a direct translation of such expressions - see `horner_expr` for a normal form. -/ @[derive has_reflect] inductive csring_expr /- (atom n) is an opaque element of the csring. For example, a local variable in the context. n indexes into a storage of such atoms - a `tree α`. -/ | atom : pos_num → csring_expr /- (const n) is technically the csring's one, added n times. Or the zero if n is 0. -/ | const : num → csring_expr | add : csring_expr → csring_expr → csring_expr | mul : csring_expr → csring_expr → csring_expr | pow : csring_expr → num → csring_expr namespace csring_expr instance : inhabited csring_expr := ⟨const 0⟩ /-- Evaluates a reflected `csring_expr` into an element of the original `comm_semiring` type `α`, retrieving opaque elements (atoms) from the tree `t`. -/ def eval {α} [comm_semiring α] (t : tree α) : csring_expr → α | (atom n) := t.get_or_zero n | (const n) := n | (add x y) := eval x + eval y | (mul x y) := eval x * eval y | (pow x n) := eval x ^ (n : ℕ) end csring_expr /-- An efficient representation of expressions in a commutative semiring using the sparse Horner normal form. This type admits non-optimal instantiations (e.g. `P` can be represented as `P+0+0`), so to get good performance out of it, care must be taken to maintain an optimal, *canonical* form. -/ @[derive decidable_eq] inductive horner_expr /- (const n) is a constant n in the csring, similarly to the same constructor in `csring_expr`. This one, however, can be negative. -/ | const : znum → horner_expr /- (horner a x n b) is a*xⁿ + b, where x is the x-th atom in the atom tree. -/ | horner : horner_expr → pos_num → num → horner_expr → horner_expr namespace horner_expr /-- True iff the `horner_expr` argument is a valid `csring_expr`. For that to be the case, all its constants must be non-negative. -/ def is_cs : horner_expr → Prop | (const n) := ∃ m:num, n = m.to_znum | (horner a x n b) := is_cs a ∧ is_cs b instance : has_zero horner_expr := ⟨const 0⟩ instance : has_one horner_expr := ⟨const 1⟩ instance : inhabited horner_expr := ⟨0⟩ /-- Represent a `csring_expr.atom` in Horner form. -/ def atom (n : pos_num) : horner_expr := horner 1 n 1 0 def to_string : horner_expr → string | (const n) := _root_.repr n | (horner a x n b) := "(" ++ to_string a ++ ") * x" ++ _root_.repr x ++ "^" ++ _root_.repr n ++ " + " ++ to_string b instance : has_to_string horner_expr := ⟨to_string⟩ /-- Alternative constructor for (horner a x n b) which maintains canonical form by simplifying special cases of `a`. -/ def horner' (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) : horner_expr := match a with | const q := if q = 0 then b else horner a x n b | horner a₁ x₁ n₁ b₁ := if x₁ = x ∧ b₁ = 0 then horner a₁ x (n₁ + n) b else horner a x n b end def add_const (k : znum) (e : horner_expr) : horner_expr := if k = 0 then e else begin induction e with n a x n b A B, { exact const (k + n) }, { exact horner a x n B } end def add_aux (a₁ : horner_expr) (A₁ : horner_expr → horner_expr) (x₁ : pos_num) : horner_expr → num → horner_expr → (horner_expr → horner_expr) → horner_expr | (const n₂) n₁ b₁ B₁ := add_const n₂ (horner a₁ x₁ n₁ b₁) | (horner a₂ x₂ n₂ b₂) n₁ b₁ B₁ := let e₂ := horner a₂ x₂ n₂ b₂ in match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (add_aux b₂ n₁ b₁ B₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (add_aux a₂ k 0 id) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end def add : horner_expr → horner_expr → horner_expr | (const n₁) e₂ := add_const n₁ e₂ | (horner a₁ x₁ n₁ b₁) e₂ := add_aux a₁ (add a₁) x₁ e₂ n₁ b₁ (add b₁) /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact add_const n₁ e₂ }, exact match e₂ with e₂ := begin induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁; let e₁ := horner a₁ x₁ n₁ b₁, { exact add_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, exact match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (B₂ n₁ b₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (A₂ k 0) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end end end end-/ def neg (e : horner_expr) : horner_expr := begin induction e with n a x n b A B, { exact const (-n) }, { exact horner A x n B } end def mul_const (k : znum) (e : horner_expr) : horner_expr := if k = 0 then 0 else if k = 1 then e else begin induction e with n a x n b A B, { exact const (n * k) }, { exact horner A x n B } end def mul_aux (a₁ x₁ n₁ b₁) (A₁ B₁ : horner_expr → horner_expr) : horner_expr → horner_expr | (const n₂) := mul_const n₂ (horner a₁ x₁ n₁ b₁) | e₂@(horner a₂ x₂ n₂ b₂) := match pos_num.cmp x₁ x₂ with | ordering.lt := horner (A₁ e₂) x₁ n₁ (B₁ e₂) | ordering.gt := horner (mul_aux a₂) x₂ n₂ (mul_aux b₂) | ordering.eq := let haa := horner' (mul_aux a₂) x₁ n₂ 0 in if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) end def mul : horner_expr → horner_expr → horner_expr | (const n₁) := mul_const n₁ | (horner a₁ x₁ n₁ b₁) := mul_aux a₁ x₁ n₁ b₁ (mul a₁) (mul b₁). /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact mul_const n₁ e₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂; let e₁ := horner a₁ x₁ n₁ b₁, { exact mul_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, cases pos_num.cmp x₁ x₂, { exact horner (A₁ e₂) x₁ n₁ (B₁ e₂) }, { let haa := horner' A₂ x₁ n₂ 0, exact if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) }, { exact horner A₂ x₂ n₂ B₂ } end-/ instance : has_add horner_expr := ⟨add⟩ instance : has_neg horner_expr := ⟨neg⟩ instance : has_mul horner_expr := ⟨mul⟩ def pow (e : horner_expr) : num → horner_expr | 0 := 1 | (num.pos p) := begin induction p with p ep p ep, { exact e }, { exact (ep.mul ep).mul e }, { exact ep.mul ep } end def inv (e : horner_expr) : horner_expr := 0 /-- Brings expressions into Horner normal form. -/ def of_csexpr : csring_expr → horner_expr | (csring_expr.atom n) := atom n | (csring_expr.const n) := const n.to_znum | (csring_expr.add x y) := (of_csexpr x).add (of_csexpr y) | (csring_expr.mul x y) := (of_csexpr x).mul (of_csexpr y) | (csring_expr.pow x n) := (of_csexpr x).pow n /-- Evaluates a reflected `horner_expr` - see `csring_expr.eval`. -/ def cseval {α} [comm_semiring α] (t : tree α) : horner_expr → α | (const n) := n.abs | (horner a x n b) := tactic.ring.horner (cseval a) (t.get_or_zero x) n (cseval b) theorem cseval_atom {α} [comm_semiring α] (t : tree α) (n : pos_num) : (atom n).is_cs ∧ cseval t (atom n) = t.get_or_zero n := ⟨⟨⟨1, rfl⟩, ⟨0, rfl⟩⟩, (tactic.ring.horner_atom _).symm⟩ theorem cseval_add_const {α} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : e.is_cs) : (add_const k.to_znum e).is_cs ∧ cseval t (add_const k.to_znum e) = k + cseval t e := begin simp [add_const], cases k; simp! *, simp [show znum.pos k ≠ 0, from dec_trivial], induction e with n a x n b A B; simp *, { rcases cs with ⟨n, rfl⟩, refine ⟨⟨n + num.pos k, by simp [add_comm]; refl⟩, _⟩, cases n; simp! }, { rcases B cs.2 with ⟨csb, h⟩, simp! [*, cs.1], rw [← tactic.ring.horner_add_const, add_comm], rw add_comm } end theorem cseval_horner' {α} [comm_semiring α] (t : tree α) (a x n b) (h₁ : is_cs a) (h₂ : is_cs b) : (horner' a x n b).is_cs ∧ cseval t (horner' a x n b) = tactic.ring.horner (cseval t a) (t.get_or_zero x) n (cseval t b) := begin cases a with n₁ a₁ x₁ n₁ b₁; simp [horner']; split_ifs, { simp! [*, tactic.ring.horner] }, { exact ⟨⟨h₁, h₂⟩, rfl⟩ }, { refine ⟨⟨h₁.1, h₂⟩, eq.symm _⟩, simp! *, apply tactic.ring.horner_horner, simp }, { exact ⟨⟨h₁, h₂⟩, rfl⟩ } end theorem cseval_add {α} [comm_semiring α] (t : tree α) {e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) : (add e₁ e₂).is_cs ∧ cseval t (add e₁ e₂) = cseval t e₁ + cseval t e₂ := begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!, { rcases cs₁ with ⟨n₁, rfl⟩, simpa using cseval_add_const t n₁ cs₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁, { rcases cs₂ with ⟨n₂, rfl⟩, simp! [cseval_add_const t n₂ cs₁, add_comm] }, cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂, simp!, have C := pos_num.cmp_to_nat x₁ x₂, cases pos_num.cmp x₁ x₂; simp!, { rcases B₁ csb₁ cs₂ with ⟨csh, h⟩, refine ⟨⟨csa₁, csh⟩, eq.symm _⟩, apply tactic.ring.horner_add_const, exact h.symm }, { cases C, have B0 : is_cs 0 → ∀ {e₂ : horner_expr}, is_cs e₂ → is_cs (add 0 e₂) ∧ cseval t (add 0 e₂) = cseval t 0 + cseval t e₂ := λ _ e₂ c, ⟨c, (zero_add _).symm⟩, cases e : num.sub' n₁ n₂ with k k; simp!, { have : n₁ = n₂, { have := congr_arg (coe : znum → ℤ) e, simp at this, have := sub_eq_zero.1 this, rw [← num.to_nat_to_int, ← num.to_nat_to_int] at this, exact num.to_nat_inj.1 (int.coe_nat_inj this) }, subst n₂, rcases cseval_horner' _ _ _ _ _ _ _ with ⟨csh, h⟩, { refine ⟨csh, h.trans (eq.symm _)⟩, simp *, apply tactic.ring.horner_add_horner_eq; try {refl} }, all_goals {simp! *} }, { simp [B₁ csb₁ csb₂, add_comm], rcases A₂ csa₂ _ _ B0 ⟨csa₁, 0, rfl⟩ with ⟨csh, h⟩, refine ⟨csh, eq.symm _⟩, rw [show id = add 0, from rfl, h], apply tactic.ring.horner_add_horner_gt, { change (_ + k : ℕ) = _, rw [← int.coe_nat_inj', int.coe_nat_add, eq_comm, ← sub_eq_iff_eq_add'], simpa using congr_arg (coe : znum → ℤ) e }, { refl }, { apply add_comm } }, { have : (horner a₂ x₁ (num.pos k) 0).is_cs := ⟨csa₂, 0, rfl⟩, simp [B₁ csb₁ csb₂, A₁ csa₁ this], symmetry, apply tactic.ring.horner_add_horner_lt, { change (_ + k : ℕ) = _, rw [← int.coe_nat_inj', int.coe_nat_add, eq_comm, ← sub_eq_iff_eq_add', ← neg_inj', neg_sub], simpa using congr_arg (coe : znum → ℤ) e }, all_goals { refl } } }, { rcases B₂ csb₂ _ _ B₁ ⟨csa₁, csb₁⟩ with ⟨csh, h⟩, refine ⟨⟨csa₂, csh⟩, eq.symm _⟩, apply tactic.ring.const_add_horner, simp [h] } end theorem cseval_mul_const {α} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : e.is_cs) : (mul_const k.to_znum e).is_cs ∧ cseval t (mul_const k.to_znum e) = cseval t e * k := begin simp [mul_const], split_ifs with h h, { cases (num.to_znum_inj.1 h : k = 0), exact ⟨⟨0, rfl⟩, (mul_zero _).symm⟩ }, { cases (num.to_znum_inj.1 h : k = 1), exact ⟨cs, (mul_one _).symm⟩ }, induction e with n a x n b A B; simp *, { rcases cs with ⟨n, rfl⟩, suffices, refine ⟨⟨n * k, this⟩, _⟩, swap, {cases n; cases k; refl}, rw [show _, from this], simp! }, { cases cs, simp! *, symmetry, apply tactic.ring.horner_mul_const; refl } end theorem cseval_mul {α} [comm_semiring α] (t : tree α) {e₁ e₂ : horner_expr} (cs₁ : e₁.is_cs) (cs₂ : e₂.is_cs) : (mul e₁ e₂).is_cs ∧ cseval t (mul e₁ e₂) = cseval t e₁ * cseval t e₂ := begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂; simp!, { rcases cs₁ with ⟨n₁, rfl⟩, simpa [mul_comm] using cseval_mul_const t n₁ cs₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂, { rcases cs₂ with ⟨n₂, rfl⟩, simpa! using cseval_mul_const t n₂ cs₁ }, cases cs₁ with csa₁ csb₁, cases id cs₂ with csa₂ csb₂, simp!, have C := pos_num.cmp_to_nat x₁ x₂, cases A₂ csa₂ with csA₂ hA₂, cases pos_num.cmp x₁ x₂; simp!, { simp [A₁ csa₁ cs₂, B₁ csb₁ cs₂], symmetry, apply tactic.ring.horner_mul_const; refl }, { cases cseval_horner' t _ x₁ n₂ 0 csA₂ ⟨0, rfl⟩ with csh₁ h₁, cases C, split_ifs, { subst b₂, refine ⟨csh₁, h₁.trans (eq.symm _)⟩, apply tactic.ring.horner_mul_horner_zero; try {refl}, simp! [hA₂] }, { cases A₁ csa₁ csb₂ with csA₁ hA₁, cases cseval_add t csh₁ _ with csh₂ h₂, { refine ⟨csh₂, h₂.trans (eq.symm _)⟩, apply tactic.ring.horner_mul_horner; try {refl}, simp! * }, exact ⟨csA₁, (B₁ csb₁ csb₂).1⟩ } }, { simp [A₂ csa₂, B₂ csb₂], rw [mul_comm, eq_comm], apply tactic.ring.horner_const_mul, {apply mul_comm}, {refl} }, end theorem cseval_pow {α} [comm_semiring α] (t : tree α) {x : horner_expr} (cs : x.is_cs) : ∀ (n : num), (pow x n).is_cs ∧ cseval t (pow x n) = cseval t x ^ (n : ℕ) | 0 := ⟨⟨1, rfl⟩, (pow_zero _).symm⟩ | (num.pos p) := begin simp [pow], induction p with p ep p ep, { simp * }, { simp [pow_bit1], cases cseval_mul t ep.1 ep.1 with cs₀ h₀, cases cseval_mul t cs₀ cs with cs₁ h₁, simp * }, { simp [pow_bit0], cases cseval_mul t ep.1 ep.1 with cs₀ h₀, simp * } end /-- For any given tree `t` of atoms and any reflected expression `r`, the Horner form of `r` is a valid csring expression, and under `t`, the Horner form evaluates to the same thing as `r`. -/ theorem cseval_of_csexpr {α} [comm_semiring α] (t : tree α) : ∀ (r : csring_expr), (of_csexpr r).is_cs ∧ cseval t (of_csexpr r) = r.eval t | (csring_expr.atom n) := cseval_atom _ _ | (csring_expr.const n) := ⟨⟨n, rfl⟩, by cases n; refl⟩ | (csring_expr.add x y) := let ⟨cs₁, h₁⟩ := cseval_of_csexpr x, ⟨cs₂, h₂⟩ := cseval_of_csexpr y, ⟨cs, h⟩ := cseval_add t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩ | (csring_expr.mul x y) := let ⟨cs₁, h₁⟩ := cseval_of_csexpr x, ⟨cs₂, h₂⟩ := cseval_of_csexpr y, ⟨cs, h⟩ := cseval_mul t cs₁ cs₂ in ⟨cs, by simp! [h, *]⟩ | (csring_expr.pow x n) := let ⟨cs, h⟩ := cseval_of_csexpr x, ⟨cs, h⟩ := cseval_pow t cs n in ⟨cs, by simp! [h, *]⟩ end horner_expr /-- The main proof-by-reflection theorem. Given reflected csring expressions `r₁` and `r₂` plus a storage `t` of atoms, if both expressions go to the same Horner normal form, then the original non-reflected expressions are equal. `H` follows from kernel reduction and is therefore `rfl`. -/ theorem correctness {α} [comm_semiring α] (t : tree α) (r₁ r₂ : csring_expr) (H : horner_expr.of_csexpr r₁ = horner_expr.of_csexpr r₂) : r₁.eval t = r₂.eval t := by repeat {rw ← (horner_expr.cseval_of_csexpr t _).2}; rw H /-- Reflects a csring expression into a `csring_expr`, together with a dlist of atoms, i.e. opaque variables over which the expression is a polynomial. -/ meta def reflect_expr : expr → csring_expr × dlist expr | `(%%e₁ + %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂, l₁ ++ l₂) /-| `(%%e₁ - %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂.neg, l₁ ++ l₂) | `(- %%e) := let (r, l) := reflect_expr e in (r.neg, l)-/ | `(%%e₁ * %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂, l₁ ++ l₂) /-| `(has_inv.inv %%e) := let (r, l) := reflect_expr e in (r.neg, l) | `(%%e₁ / %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂.inv, l₁ ++ l₂)-/ | e@`(%%e₁ ^ %%e₂) := match reflect_expr e₁, expr.to_nat e₂ with | (r₁, l₁), some n₂ := (r₁.pow (num.of_nat' n₂), l₁) | (r₁, l₁), none := (csring_expr.atom 1, dlist.singleton e) end | e := match expr.to_nat e with | some n := (csring_expr.const (num.of_nat' n), dlist.empty) | none := (csring_expr.atom 1, dlist.singleton e) end /-- In the output of `reflect_expr`, `atom`s are initialized with incorrect indices. The indices cannot be computed until the whole tree is built, so another pass over the expressions is needed - this is what `replace` does. The computation (expressed in the state monad) fixes up `atom`s to match their positions in the atom tree. The initial state is a list of all atom occurrences in the goal, left-to-right. -/ meta def csring_expr.replace (t : tree expr) : csring_expr → state_t (list expr) option csring_expr | (csring_expr.atom _) := do e ← get, p ← monad_lift (t.index_of (<) e.head), put e.tail, pure (csring_expr.atom p) | (csring_expr.const n) := pure (csring_expr.const n) | (csring_expr.add x y) := csring_expr.add <$> x.replace <*> y.replace | (csring_expr.mul x y) := csring_expr.mul <$> x.replace <*> y.replace | (csring_expr.pow x n) := (λ x, csring_expr.pow x n) <$> x.replace --| (csring_expr.neg x) := csring_expr.neg <$> x.replace --| (csring_expr.inv x) := csring_expr.inv <$> x.replace end tactic.ring2 namespace tactic namespace interactive open interactive interactive.types lean.parser open tactic.ring2 local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of rings. This variant on the `ring` tactic uses kernel computation instead of proof generation. -/ meta def ring2 : tactic unit := do `[repeat {rw ← nat.pow_eq_pow}], `(%%e₁ = %%e₂) ← target | fail "ring2 tactic failed: the goal is not an equality", α ← infer_type e₁, expr.sort (level.succ u) ← infer_type α, let (r₁, l₁) := reflect_expr e₁, let (r₂, l₂) := reflect_expr e₂, let L := (l₁ ++ l₂).to_list, let s := tree.of_rbnode (rbtree_of L).1, (r₁, L) ← (state_t.run (r₁.replace s) L : option _), (r₂, _) ← (state_t.run (r₂.replace s) L : option _), let se : expr := s.reflect' u α, let er₁ : expr := reflect r₁, let er₂ : expr := reflect r₂, cs ← mk_app ``comm_semiring [α] >>= mk_instance, e ← to_expr ``(correctness %%se %%er₁ %%er₂ rfl) <|> fail ("ring2 tactic failed, cannot show equality:\n" ++ to_string (horner_expr.of_csexpr r₁) ++ "\n =?=\n" ++ to_string (horner_expr.of_csexpr r₂)), tactic.exact e end interactive end tactic namespace conv.interactive open conv meta def ring2 : conv unit := discharge_eq_lhs tactic.interactive.ring2 end conv.interactive
a37adb8602a099062c5f734a99e39efb7ade6d25
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/nateq.lean
27cbd6fbf4c46b581d6b06816a7936035295eba8
[ "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
929
lean
import data.nat.basic data.bool open bool nat eq.ops attribute nat.rec_on [reducible] definition is_eq (a b : nat) : bool := nat.rec_on a (λ b, nat.cases_on b tt (λb₁, ff)) (λ a₁ r₁ b, nat.cases_on b ff (λb₁, r₁ b₁)) b example : is_eq 3 3 = tt := rfl example : is_eq 3 5 = ff := rfl theorem eq.to_is_eq (a b : nat) (H : a = b) : is_eq a b = tt := have aux : is_eq a a = tt, from nat.induction_on a rfl (λ (a₁ : nat) (ih : is_eq a₁ a₁ = tt), ih), H ▸ aux theorem is_eq.to_eq (a b : nat) : is_eq a b = tt → a = b := nat.induction_on a (λb, nat.cases_on b (λh, rfl) (λb₁ H, absurd H !ff_ne_tt)) (λa₁ (ih : ∀b, is_eq a₁ b = tt → a₁ = b) (b : nat), nat.cases_on b (λ (H : is_eq (succ a₁) zero = tt), absurd H !ff_ne_tt) (λb₁ (H : is_eq (succ a₁) (succ b₁) = tt), have aux : a₁ = b₁, from ih b₁ H, aux ▸ rfl)) b
bf295194b1e46c4a87f2f4fdfddd81bcec8d3776
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/770.hlean
d501464bf2cf0fb621e2ef7b3c78ebec0e6198b9
[ "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
464
hlean
open nat unit equiv eq definition code : ℕ → ℕ → Type₀ | code 0 0 := unit | code (succ n) 0 := empty | code 0 (succ m) := empty | code (succ n) (succ m) := code n m definition refl : Πn, code n n | refl 0 := star | refl (succ n) := refl n definition encode (n m : ℕ) : (n = m) ≃ code n m := equiv.MK (λp, p ▸ refl n) (match n m with | 0 0 := sorry end) sorry sorry
5d2bcd82c797f4c8be68355f86663137f4720222
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/topology/algebra/group.lean
f517d4d88d781205e53a13d1586546a606fdbd9a
[ "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
20,766
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of topological groups. -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph open classical set filter topological_space open_locale classical topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_group section prio set_option default_priority 100 -- see Note [default priority] /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends has_continuous_add α : Prop := (continuous_neg : continuous (λa:α, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive topological_add_group] class topological_group (α : Type*) [topological_space α] [group α] extends has_continuous_mul α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) end prio variables [topological_space α] [group α] @[to_additive] lemma continuous_inv [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv @[to_additive] lemma continuous.inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf @[to_additive] lemma continuous_on_inv [topological_group α] {s : set α} : continuous_on (λx:α, x⁻¹) s := continuous_inv.continuous_on @[to_additive] lemma continuous_on.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma tendsto_inv {α : Type*} [group α] [topological_space α] [topological_group α] (a : α) : tendsto (λ x, x⁻¹) (nhds a) (nhds (a⁻¹)) := continuous_inv.tendsto a /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (𝓝 a)) : tendsto (λx, (f x)⁻¹) x (𝓝 a⁻¹) := tendsto.comp (continuous_iff_continuous_at.mp topological_group.continuous_inv a) hf @[to_additive] lemma continuous_at.inv [topological_group α] [topological_space β] {f : β → α} {x : β} (hf : continuous_at f x) : continuous_at (λx, (f x)⁻¹) x := hf.inv @[to_additive] lemma continuous_within_at.inv [topological_group α] [topological_space β] {f : β → α} {s : set β} {x : β} (hf : continuous_within_at f s x) : continuous_within_at (λx, (f x)⁻¹) s x := hf.inv @[to_additive topological_add_group] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous_fst.inv.prod_mk continuous_snd.inv } attribute [instance] prod.topological_add_group @[to_additive] protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left [topological_group α] (a : α) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map @[to_additive] protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right [topological_group α] (a : α) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv α } @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : α × α) := tendsto_mul (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ v w ∈ V, v * w⁻¹ ∈ s := begin have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) ((𝓝 (1:α)).prod (𝓝 (1:α))) (𝓝 1), { simpa using (@tendsto_fst α α (𝓝 1) (𝓝 1)).mul tendsto_snd.inv }, have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ (𝓝 (1:α)).prod (𝓝 (1:α)) := this (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ 𝓝 (1 : α)) : ∃ V ∈ 𝓝 (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (𝓝 (1 : α)) = 𝓝 (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (𝓝 1) (𝓝 1), { simpa using (@tendsto_id α (𝓝 1)).inv }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (𝓝 x) (𝓝 (x * x⁻¹)), { simpa }, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space α] [group α] [topological_group α] (N : set α) [normal_subgroup N] @[to_additive] instance {α : Type u} [group α] [topological_space α] (N : set α) [normal_subgroup N] : topological_space (quotient_group.quotient N) := by dunfold quotient_group.quotient; apply_instance open quotient_group @[to_additive quotient_add_group_saturate] lemma quotient_group_saturate {α : Type u} [group α] (N : set α) [normal_subgroup N] (s : set α) : (coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, quotient_group.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left, hi]⟩ } end @[to_additive] lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) := begin intros s s_op, change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)), rw quotient_group_saturate N s, apply is_open_Union, rintro ⟨n, _⟩, exact is_open_map_mul_right n s s_op end @[to_additive topological_add_group_quotient] instance topological_group_quotient : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) }, { exact (continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd) }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)), exact continuous_quot_mk.comp continuous_inv end } attribute [instance] topological_add_group_quotient end quotient_topological_group section topological_add_group variables [topological_space α] [add_group α] lemma continuous.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma continuous_sub [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_fst.sub continuous_snd lemma continuous_on.sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} {s : set β} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := continuous_sub.comp_continuous_on (hf.prod hg) lemma filter.tendsto.sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x - g x) x (𝓝 (a - b)) := by simp [sub_eq_add_neg]; exact hf.add hg.neg lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x end topological_add_group section prio set_option default_priority 100 -- see Note [default priority] /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z [] : filter α) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z) end prio namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ v w ∈ V, v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ (Z α).prod (Z α) := add_Z (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end lemma nhds_eq (a : α) : 𝓝 a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 b t0 hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ _ hxt hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z α := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α)) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space α] [group α] [topological_group α] @[to_additive] lemma is_open_mul_left {s t : set α} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : α), a * x) '' t), assume a, apply is_open_map_mul_left, exact ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open_mul_right {s t : set α} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : α), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (α) lemma topological_group.t1_space (h : @is_closed α _ {1}) : t1_space α := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space α] : regular_space α := ⟨assume s a hs ha, let f := λ p : α × α, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_mul.comp (continuous_fst.prod_mk (continuous_inv.comp continuous_snd)), -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 (hf _ (is_open_compl_iff.2 hs)) a (1:α) (by simpa [f]) in begin use s * t₂, use is_open_mul_left ht₂, use λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩, apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space α] : t2_space α := regular_space.t2_space α end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space α] [group α] [topological_group α] /-- Given a open neighborhood `U` of `1` there is a open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma one_open_separated_mul {U : set α} (h1U : is_open U) (h2U : (1 : α) ∈ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ V * V ⊆ U := begin rcases exists_nhds_square (continuous_mul U h1U) (by simp only [mem_preimage, one_mul, h2U] : ((1 : α), (1 : α)) ∈ (λ p : α × α, p.1 * p.2) ⁻¹' U) with ⟨V, h1V, h2V, h3V⟩, refine ⟨V, h1V, h2V, _⟩, rwa [← image_subset_iff, image_mul_prod] at h3V end /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set α, is_open V ∧ (1 : α) ∈ V ∧ K * V ⊆ U := begin let W : α → set α := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, continuous_mul_left x U hU, have h2W : ∀ x ∈ K, (1 : α) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, one_open_separated_mul (h1W x) (h2W x.1 x.2), let X : K → set α := λ x, (λ y, (x : α)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, continuous_mul_left x⁻¹ (V x) (hV x).1) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : α)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set α} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset α, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : α, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space α] [comm_group α] [topological_group α] @[to_additive] lemma nhds_mul (x y : α) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_split ht with ⟨V, V_mem, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V_mem, subset.refl _⟩, ⟨V, V_mem, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) (w * y⁻¹) v_mem w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:α, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
06847bcb48ff6522f101b0c584d39d670a1dd406
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/combinatorics/simple_graph/basic.lean
85fd20b873a31ff7f81263967843bacd5d03d101
[]
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
17,030
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.data.sym2 import Mathlib.data.set.finite import Mathlib.PostPort universes u l namespace Mathlib /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `neighbor_set` is the `set` of vertices adjacent to a given vertex * `neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `incidence_set` is the `set` of edges containing a given vertex * `incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite ## Implementation notes * A locally finite graph is one with instances `∀ v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. ## Naming Conventions * If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`. TODO: This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. TODO: Part of this would include defining, for example, subgraphs of a simple graph. -/ /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent edges; see `simple_graph.edge_set` for the corresponding edge set. -/ structure simple_graph (V : Type u) where adj : V → V → Prop sym : autoParam (symmetric adj) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) loopless : autoParam (irreflexive adj) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := simple_graph.mk fun (a b : V) => a ≠ b ∧ (r a b ∨ r b a) protected instance simple_graph.fintype {V : Type u} [fintype V] : fintype (simple_graph V) := fintype.of_injective simple_graph.adj simple_graph.ext @[simp] theorem simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v : V) (w : V) : simple_graph.adj (simple_graph.from_rel r) v w ↔ v ≠ w ∧ (r v w ∨ r w v) := iff.rfl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. -/ def complete_graph (V : Type u) : simple_graph V := simple_graph.mk ne protected instance simple_graph.inhabited (V : Type u) : Inhabited (simple_graph V) := { default := complete_graph V } protected instance complete_graph_adj_decidable (V : Type u) [DecidableEq V] : DecidableRel (simple_graph.adj (complete_graph V)) := fun (v w : V) => not.decidable namespace simple_graph /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set {V : Type u} (G : simple_graph V) (v : V) : set V := set_of (adj G v) protected instance neighbor_set.mem_decidable {V : Type u} (G : simple_graph V) (v : V) [DecidableRel (adj G)] : decidable_pred fun (_x : V) => _x ∈ neighbor_set G v := eq.mpr sorry fun (a : V) => set.decidable_mem (set_of (adj G v)) a theorem ne_of_adj {V : Type u} (G : simple_graph V) {a : V} {b : V} (hab : adj G a b) : a ≠ b := id fun (ᾰ : a = b) => Eq._oldrec (fun (hab : adj G a a) => loopless G a hab) ᾰ hab /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. -/ def edge_set {V : Type u} (G : simple_graph V) : set (sym2 V) := sym2.from_rel (sym G) /-- The `incidence_set` is the set of edges incident to a given vertex. -/ def incidence_set {V : Type u} (G : simple_graph V) (v : V) : set (sym2 V) := has_sep.sep (fun (e : sym2 V) => v ∈ e) (edge_set G) theorem incidence_set_subset {V : Type u} (G : simple_graph V) (v : V) : incidence_set G v ⊆ edge_set G := fun (_x : sym2 V) (h : _x ∈ incidence_set G v) => and.left h @[simp] theorem mem_edge_set {V : Type u} (G : simple_graph V) {v : V} {w : V} : quotient.mk (v, w) ∈ edge_set G ↔ adj G v w := iff.refl (quotient.mk (v, w) ∈ edge_set G) /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ theorem adj_iff_exists_edge {V : Type u} (G : simple_graph V) {v : V} {w : V} : adj G v w ↔ v ≠ w ∧ ∃ (e : sym2 V), ∃ (H : e ∈ edge_set G), v ∈ e ∧ w ∈ e := sorry theorem edge_other_ne {V : Type u} (G : simple_graph V) {e : sym2 V} (he : e ∈ edge_set G) {v : V} (h : v ∈ e) : sym2.mem.other h ≠ v := ne_of_adj G (eq.mp (Eq._oldrec (Eq.refl (quotient.mk (v, sym2.mem.other h) ∈ edge_set G)) sym2.eq_swap) (eq.mp (Eq._oldrec (Eq.refl (e ∈ edge_set G)) (Eq.symm (sym2.mem_other_spec h))) he)) protected instance edge_set_decidable_pred {V : Type u} (G : simple_graph V) [DecidableRel (adj G)] : decidable_pred (edge_set G) := sym2.from_rel.decidable_pred (sym G) protected instance edges_fintype {V : Type u} (G : simple_graph V) [DecidableEq V] [fintype V] [DecidableRel (adj G)] : fintype ↥(edge_set G) := subtype.fintype fun (x : sym2 V) => x ∈ edge_set G protected instance incidence_set_decidable_pred {V : Type u} (G : simple_graph V) [DecidableEq V] [DecidableRel (adj G)] (v : V) : decidable_pred (incidence_set G v) := fun (e : sym2 V) => and.decidable /-- The `edge_set` of the graph as a `finset`. -/ def edge_finset {V : Type u} (G : simple_graph V) [DecidableEq V] [fintype V] [DecidableRel (adj G)] : finset (sym2 V) := set.to_finset (edge_set G) @[simp] theorem mem_edge_finset {V : Type u} (G : simple_graph V) [DecidableEq V] [fintype V] [DecidableRel (adj G)] (e : sym2 V) : e ∈ edge_finset G ↔ e ∈ edge_set G := set.mem_to_finset @[simp] theorem edge_set_univ_card {V : Type u} (G : simple_graph V) [DecidableEq V] [fintype V] [DecidableRel (adj G)] : finset.card finset.univ = finset.card (edge_finset G) := fintype.card_of_subtype (edge_finset G) (mem_edge_finset G) @[simp] theorem irrefl {V : Type u} (G : simple_graph V) {v : V} : ¬adj G v v := loopless G v theorem edge_symm {V : Type u} (G : simple_graph V) (u : V) (v : V) : adj G u v ↔ adj G v u := { mp := fun (x : adj G u v) => sym G x, mpr := fun (x : adj G v u) => sym G x } @[simp] theorem mem_neighbor_set {V : Type u} (G : simple_graph V) (v : V) (w : V) : w ∈ neighbor_set G v ↔ adj G v w := iff.rfl @[simp] theorem mem_incidence_set {V : Type u} (G : simple_graph V) (v : V) (w : V) : quotient.mk (v, w) ∈ incidence_set G v ↔ adj G v w := sorry theorem mem_incidence_iff_neighbor {V : Type u} (G : simple_graph V) {v : V} {w : V} : quotient.mk (v, w) ∈ incidence_set G v ↔ w ∈ neighbor_set G v := sorry theorem adj_incidence_set_inter {V : Type u} (G : simple_graph V) {v : V} {e : sym2 V} (he : e ∈ edge_set G) (h : v ∈ e) : incidence_set G v ∩ incidence_set G (sym2.mem.other h) = singleton e := sorry /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors {V : Type u} (G : simple_graph V) (v : V) (w : V) : set V := neighbor_set G v ∩ neighbor_set G w theorem common_neighbors_eq {V : Type u} (G : simple_graph V) (v : V) (w : V) : common_neighbors G v w = neighbor_set G v ∩ neighbor_set G w := rfl theorem mem_common_neighbors {V : Type u} (G : simple_graph V) {u : V} {v : V} {w : V} : u ∈ common_neighbors G v w ↔ adj G v u ∧ adj G w u := sorry theorem common_neighbors_symm {V : Type u} (G : simple_graph V) (v : V) (w : V) : common_neighbors G v w = common_neighbors G w v := sorry theorem not_mem_common_neighbors_left {V : Type u} (G : simple_graph V) (v : V) (w : V) : ¬v ∈ common_neighbors G v w := sorry theorem not_mem_common_neighbors_right {V : Type u} (G : simple_graph V) (v : V) (w : V) : ¬w ∈ common_neighbors G v w := sorry theorem common_neighbors_subset_neighbor_set {V : Type u} (G : simple_graph V) (v : V) (w : V) : common_neighbors G v w ⊆ neighbor_set G v := sorry /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {V : Type u} (G : simple_graph V) [DecidableEq V] {v : V} {e : sym2 V} (h : e ∈ incidence_set G v) : V := sym2.mem.other' sorry theorem edge_mem_other_incident_set {V : Type u} (G : simple_graph V) [DecidableEq V] {v : V} {e : sym2 V} (h : e ∈ incidence_set G v) : e ∈ incidence_set G (other_vertex_of_incident G h) := sorry theorem incidence_other_prop {V : Type u} (G : simple_graph V) [DecidableEq V] {v : V} {e : sym2 V} (h : e ∈ incidence_set G v) : other_vertex_of_incident G h ∈ neighbor_set G v := sorry @[simp] theorem incidence_other_neighbor_edge {V : Type u} (G : simple_graph V) [DecidableEq V] {v : V} {w : V} (h : w ∈ neighbor_set G v) : other_vertex_of_incident G (iff.mpr (mem_incidence_iff_neighbor G) h) = w := iff.mp sym2.congr_right (sym2.mem_other_spec' (and.right (iff.mpr (mem_incidence_iff_neighbor G) h))) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ def incidence_set_equiv_neighbor_set {V : Type u} (G : simple_graph V) [DecidableEq V] (v : V) : ↥(incidence_set G v) ≃ ↥(neighbor_set G v) := equiv.mk (fun (e : ↥(incidence_set G v)) => { val := other_vertex_of_incident G sorry, property := sorry }) (fun (w : ↥(neighbor_set G v)) => { val := quotient.mk (v, subtype.val w), property := sorry }) sorry sorry /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] : finset V := set.to_finset (neighbor_set G v) @[simp] theorem mem_neighbor_finset {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] (w : V) : w ∈ neighbor_finset G v ↔ adj G v w := set.mem_to_finset /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] : ℕ := finset.card (neighbor_finset G v) @[simp] theorem card_neighbor_set_eq_degree {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] : fintype.card ↥(neighbor_set G v) = degree G v := Eq.symm (set.to_finset_card (neighbor_set G v)) theorem degree_pos_iff_exists_adj {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] : 0 < degree G v ↔ ∃ (w : V), adj G v w := sorry protected instance incidence_set_fintype {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] [DecidableEq V] : fintype ↥(incidence_set G v) := fintype.of_equiv (↥(neighbor_set G v)) (equiv.symm (incidence_set_equiv_neighbor_set G v)) /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] [DecidableEq V] : finset (sym2 V) := set.to_finset (incidence_set G v) @[simp] theorem card_incidence_set_eq_degree {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] [DecidableEq V] : fintype.card ↥(incidence_set G v) = degree G v := sorry @[simp] theorem mem_incidence_finset {V : Type u} (G : simple_graph V) (v : V) [fintype ↥(neighbor_set G v)] [DecidableEq V] (e : sym2 V) : e ∈ incidence_finset G v ↔ e ∈ incidence_set G v := set.mem_to_finset /-- A graph is locally finite if every vertex has a finite neighbor set. -/ def locally_finite {V : Type u} (G : simple_graph V) := (v : V) → fintype ↥(neighbor_set G v) /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree {V : Type u} (G : simple_graph V) [locally_finite G] (d : ℕ) := ∀ (v : V), degree G v = d theorem is_regular_of_degree_eq {V : Type u} (G : simple_graph V) [locally_finite G] {d : ℕ} (h : is_regular_of_degree G d) (v : V) : degree G v = d := h v protected instance neighbor_set_fintype {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] (v : V) : fintype ↥(neighbor_set G v) := subtype.fintype fun (x : V) => x ∈ neighbor_set G v theorem neighbor_finset_eq_filter {V : Type u} (G : simple_graph V) [fintype V] {v : V} [DecidableRel (adj G)] : neighbor_finset G v = finset.filter (adj G v) finset.univ := sorry @[simp] theorem complete_graph_degree {V : Type u} [fintype V] [DecidableEq V] (v : V) : degree (complete_graph V) v = fintype.card V - 1 := sorry theorem complete_graph_is_regular {V : Type u} [fintype V] [DecidableEq V] : is_regular_of_degree (complete_graph V) (fintype.card V - 1) := sorry /-- The minimum degree of all vertices -/ def min_degree {V : Type u} [fintype V] (G : simple_graph V) [Nonempty V] [DecidableRel (adj G)] : ℕ := finset.min' (finset.image (fun (v : V) => degree G v) finset.univ) sorry /-- The maximum degree of all vertices -/ def max_degree {V : Type u} [fintype V] (G : simple_graph V) [Nonempty V] [DecidableRel (adj G)] : ℕ := finset.max' (finset.image (fun (v : V) => degree G v) finset.univ) sorry /-! The following lemmas about `fintype.card` use noncomputable decidable instances to get fintype assumptions. -/ theorem degree_lt_card_verts {V : Type u} [fintype V] (G : simple_graph V) (v : V) : degree G v < fintype.card V := sorry theorem card_common_neighbors_le_degree_left {V : Type u} (G : simple_graph V) [fintype V] (v : V) (w : V) : fintype.card ↥(common_neighbors G v w) ≤ degree G v := sorry theorem card_common_neighbors_le_degree_right {V : Type u} (G : simple_graph V) [fintype V] (v : V) (w : V) : fintype.card ↥(common_neighbors G v w) ≤ degree G w := eq.mpr (id (Eq._oldrec (Eq.refl (fintype.card ↥(common_neighbors G v w) ≤ degree G w)) (common_neighbors_symm G v w))) (card_common_neighbors_le_degree_left G w v) theorem card_common_neighbors_lt_card_verts {V : Type u} (G : simple_graph V) [fintype V] (v : V) (w : V) : fintype.card ↥(common_neighbors G v w) < fintype.card V := nat.lt_of_le_of_lt (card_common_neighbors_le_degree_left G v w) (degree_lt_card_verts G v) /-- If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is the best we can do in general. -/ theorem adj.card_common_neighbors_lt_degree {V : Type u} [fintype V] {G : simple_graph V} {v : V} {w : V} (h : adj G v w) : fintype.card ↥(common_neighbors G v w) < degree G v := sorry /-! ## Complement of a simple graph This section contains definitions and lemmas concerning the complement of a simple graph. -/ /-- We define `compl G` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves.) -/ def compl {V : Type u} (G : simple_graph V) : simple_graph V := mk fun (v w : V) => v ≠ w ∧ ¬adj G v w protected instance has_compl {V : Type u} : has_compl (simple_graph V) := has_compl.mk compl @[simp] theorem compl_adj {V : Type u} (G : simple_graph V) (v : V) (w : V) : adj (Gᶜ) v w ↔ v ≠ w ∧ ¬adj G v w := iff.rfl @[simp] theorem compl_compl {V : Type u} (G : simple_graph V) : Gᶜᶜ = G := sorry @[simp] theorem compl_involutive {V : Type u} : function.involutive compl := compl_compl theorem compl_neighbor_set_disjoint {V : Type u} (G : simple_graph V) (v : V) : disjoint (neighbor_set G v) (neighbor_set (Gᶜ) v) := sorry theorem neighbor_set_union_compl_neighbor_set_eq {V : Type u} (G : simple_graph V) (v : V) : neighbor_set G v ∪ neighbor_set (Gᶜ) v = (singleton vᶜ) := sorry
59bb22221d4d0756018ce424c0e5a9d6d01c9638
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/filter/countable_Inter.lean
126b8994933c0f0f2f3b1640f2d5cedf430bea74
[ "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,314
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import order.filter.basic import data.set.countable /-! # Filters with countable intersection property In this file we define `countable_Inter_filter` to be the class of filters with the following property: for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. Two main examples are the `residual` filter defined in `topology.metric_space.baire` and the `measure.ae` filter defined in `measure_theory.measure_space`. -/ open set filter open_locale filter variables {ι α : Type*} /-- A filter `l` has the countable intersection property if for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. -/ class countable_Inter_filter (l : filter α) : Prop := (countable_sInter_mem_sets' : ∀ {S : set (set α)} (hSc : countable S) (hS : ∀ s ∈ S, s ∈ l), ⋂₀ S ∈ l) variables {l : filter α} [countable_Inter_filter l] lemma countable_sInter_mem_sets {S : set (set α)} (hSc : countable S) : ⋂₀ S ∈ l ↔ ∀ s ∈ S, s ∈ l := ⟨λ hS s hs, mem_of_superset hS (sInter_subset_of_mem hs), countable_Inter_filter.countable_sInter_mem_sets' hSc⟩ lemma countable_Inter_mem_sets [encodable ι] {s : ι → set α} : (⋂ i, s i) ∈ l ↔ ∀ i, s i ∈ l := sInter_range s ▸ (countable_sInter_mem_sets (countable_range _)).trans forall_range_iff lemma countable_bInter_mem {S : set ι} (hS : countable S) {s : Π i ∈ S, set α} : (⋂ i ∈ S, s i ‹_›) ∈ l ↔ ∀ i ∈ S, s i ‹_› ∈ l := begin rw [bInter_eq_Inter], haveI := hS.to_encodable, exact countable_Inter_mem_sets.trans subtype.forall end lemma eventually_countable_forall [encodable ι] {p : α → ι → Prop} : (∀ᶠ x in l, ∀ i, p x i) ↔ ∀ i, ∀ᶠ x in l, p x i := by simpa only [filter.eventually, set_of_forall] using @countable_Inter_mem_sets _ _ l _ _ (λ i, {x | p x i}) lemma eventually_countable_ball {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᶠ x in l, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᶠ x in l, p x i ‹_› := by simpa only [filter.eventually, set_of_forall] using @countable_bInter_mem _ _ l _ _ hS (λ i hi, {x | p x i hi}) lemma eventually_le.countable_Union [encodable ι] {s t : ι → set α} (h : ∀ i, s i ≤ᶠ[l] t i) : (⋃ i, s i) ≤ᶠ[l] ⋃ i, t i := (eventually_countable_forall.2 h).mono $ λ x hst hs, mem_Union.2 $ (mem_Union.1 hs).imp hst lemma eventually_eq.countable_Union [encodable ι] {s t : ι → set α} (h : ∀ i, s i =ᶠ[l] t i) : (⋃ i, s i) =ᶠ[l] ⋃ i, t i := (eventually_le.countable_Union (λ i, (h i).le)).antisymm (eventually_le.countable_Union (λ i, (h i).symm.le)) lemma eventually_le.countable_bUnion {S : set ι} (hS : countable S) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› ≤ᶠ[l] t i ‹_›) : (⋃ i ∈ S, s i ‹_›) ≤ᶠ[l] ⋃ i ∈ S, t i ‹_› := begin simp only [bUnion_eq_Union], haveI := hS.to_encodable, exact eventually_le.countable_Union (λ i, h i i.2) end lemma eventually_eq.countable_bUnion {S : set ι} (hS : countable S) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› =ᶠ[l] t i ‹_›) : (⋃ i ∈ S, s i ‹_›) =ᶠ[l] ⋃ i ∈ S, t i ‹_› := (eventually_le.countable_bUnion hS (λ i hi, (h i hi).le)).antisymm (eventually_le.countable_bUnion hS (λ i hi, (h i hi).symm.le)) lemma eventually_le.countable_Inter [encodable ι] {s t : ι → set α} (h : ∀ i, s i ≤ᶠ[l] t i) : (⋂ i, s i) ≤ᶠ[l] ⋂ i, t i := (eventually_countable_forall.2 h).mono $ λ x hst hs, mem_Inter.2 $ λ i, hst _ (mem_Inter.1 hs i) lemma eventually_eq.countable_Inter [encodable ι] {s t : ι → set α} (h : ∀ i, s i =ᶠ[l] t i) : (⋂ i, s i) =ᶠ[l] ⋂ i, t i := (eventually_le.countable_Inter (λ i, (h i).le)).antisymm (eventually_le.countable_Inter (λ i, (h i).symm.le)) lemma eventually_le.countable_bInter {S : set ι} (hS : countable S) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› ≤ᶠ[l] t i ‹_›) : (⋂ i ∈ S, s i ‹_›) ≤ᶠ[l] ⋂ i ∈ S, t i ‹_› := begin simp only [bInter_eq_Inter], haveI := hS.to_encodable, exact eventually_le.countable_Inter (λ i, h i i.2) end lemma eventually_eq.countable_bInter {S : set ι} (hS : countable S) {s t : Π i ∈ S, set α} (h : ∀ i ∈ S, s i ‹_› =ᶠ[l] t i ‹_›) : (⋂ i ∈ S, s i ‹_›) =ᶠ[l] ⋂ i ∈ S, t i ‹_› := (eventually_le.countable_bInter hS (λ i hi, (h i hi).le)).antisymm (eventually_le.countable_bInter hS (λ i hi, (h i hi).symm.le)) instance countable_Inter_filter_principal (s : set α) : countable_Inter_filter (𝓟 s) := ⟨λ S hSc hS, subset_sInter hS⟩ instance countable_Inter_filter_bot : countable_Inter_filter (⊥ : filter α) := by { rw ← principal_empty, apply countable_Inter_filter_principal } instance countable_Inter_filter_top : countable_Inter_filter (⊤ : filter α) := by { rw ← principal_univ, apply countable_Inter_filter_principal } /-- Infimum of two `countable_Inter_filter`s is a `countable_Inter_filter`. This is useful, e.g., to automatically get an instance for `residual α ⊓ 𝓟 s`. -/ instance countable_Inter_filter_inf (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊓ l₂) := begin refine ⟨λ S hSc hS, _⟩, choose s hs t ht hst using hS, replace hs : (⋂ i ∈ S, s i ‹_›) ∈ l₁ := (countable_bInter_mem hSc).2 hs, replace ht : (⋂ i ∈ S, t i ‹_›) ∈ l₂ := (countable_bInter_mem hSc).2 ht, refine mem_of_superset (inter_mem_inf hs ht) (subset_sInter $ λ i hi, _), rw hst i hi, apply inter_subset_inter ; exact Inter_subset_of_subset i (Inter_subset _ _) end /-- Supremum of two `countable_Inter_filter`s is a `countable_Inter_filter`. -/ instance countable_Inter_filter_sup (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊔ l₂) := begin refine ⟨λ S hSc hS, ⟨_, _⟩⟩; refine (countable_sInter_mem_sets hSc).2 (λ s hs, _), exacts [(hS s hs).1, (hS s hs).2] end